repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/BuildValidator/Util.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Reflection.Metadata; using System.Reflection.PortableExecutable; namespace BuildValidator { internal static class Util { internal static PortableExecutableInfo? GetPortableExecutableInfo(string filePath) { using var stream = File.OpenRead(filePath); var peReader = new PEReader(stream); if (GetMvid(peReader) is { } mvid) { var isReadyToRun = IsReadyToRunImage(peReader); return new PortableExecutableInfo(filePath, mvid, isReadyToRun); } return null; } internal static Guid? GetMvid(PEReader peReader) { if (peReader.HasMetadata) { var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } else { return null; } } internal static bool IsReadyToRunImage(PEReader peReader) { if (peReader.PEHeaders is null || peReader.PEHeaders.PEHeader is null || peReader.PEHeaders.CorHeader is null) { return false; } if ((peReader.PEHeaders.CorHeader.Flags & CorFlags.ILLibrary) == 0) { PEExportTable exportTable = peReader.GetExportTable(); return exportTable.TryGetValue("RTR_HEADER", out _); } else { return peReader.PEHeaders.CorHeader.ManagedNativeHeaderDirectory.Size != 0; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; namespace BuildValidator { internal static class Util { internal static PortableExecutableInfo? GetPortableExecutableInfo(string filePath) { using var stream = File.OpenRead(filePath); var peReader = new PEReader(stream); if (GetMvid(peReader) is { } mvid) { var isReadyToRun = IsReadyToRunImage(peReader); return new PortableExecutableInfo(filePath, mvid, isReadyToRun); } return null; } internal static Guid? GetMvid(PEReader peReader) { if (peReader.HasMetadata) { var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } else { return null; } } internal static bool IsReadyToRunImage(PEReader peReader) { if (peReader.PEHeaders is null || peReader.PEHeaders.PEHeader is null || peReader.PEHeaders.CorHeader is null) { return false; } if ((peReader.PEHeaders.CorHeader.Flags & CorFlags.ILLibrary) == 0) { PEExportTable exportTable = peReader.GetExportTable(); return exportTable.TryGetValue("RTR_HEADER", out _); } else { return peReader.PEHeaders.CorHeader.ManagedNativeHeaderDirectory.Size != 0; } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/LanguageServer/ProtocolUnitTests/Definitions/GoToDefinitionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Definitions { public class GoToDefinitionTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGotoDefinitionAsync() { var markup = @"class A { string {|definition:aString|} = 'hello'; void M() { var len = {|caret:|}aString.Length; } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoDefinitionAsync_DifferentDocument() { var markups = new string[] { @"namespace One { class A { public static int {|definition:aInt|} = 1; } }", @"namespace One { class B { int bInt = One.A.{|caret:|}aInt; } }" }; using var testLspServer = CreateTestLspServer(markups, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoDefinitionAsync_MappedFile() { var markup = @"class A { string aString = 'hello'; void M() { var len = aString.Length; } }"; using var testLspServer = CreateTestLspServer(string.Empty, out var _); AddMappedDocument(testLspServer.TestWorkspace, markup); var position = new LSP.Position { Line = 5, Character = 18 }; var results = await RunGotoDefinitionAsync(testLspServer, new LSP.Location { Uri = new Uri($"C:\\{TestSpanMapper.GeneratedFileName}"), Range = new LSP.Range { Start = position, End = position } }); AssertLocationsEqual(ImmutableArray.Create(TestSpanMapper.MappedFileLocation), results); } [Fact] public async Task TestGotoDefinitionAsync_InvalidLocation() { var markup = @"class A { void M() {{|caret:|} var len = aString.Length; } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } [Fact, WorkItem(1264627, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1264627")] public async Task TestGotoDefinitionAsync_NoResultsOnNamespace() { var markup = @"namespace {|caret:M|} { class A { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } private static async Task<LSP.Location[]> RunGotoDefinitionAsync(TestLspServer testLspServer, LSP.Location caret) { return await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.Location[]>(LSP.Methods.TextDocumentDefinitionName, CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), null, CancellationToken.None); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Definitions { public class GoToDefinitionTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGotoDefinitionAsync() { var markup = @"class A { string {|definition:aString|} = 'hello'; void M() { var len = {|caret:|}aString.Length; } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoDefinitionAsync_DifferentDocument() { var markups = new string[] { @"namespace One { class A { public static int {|definition:aInt|} = 1; } }", @"namespace One { class B { int bInt = One.A.{|caret:|}aInt; } }" }; using var testLspServer = CreateTestLspServer(markups, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoDefinitionAsync_MappedFile() { var markup = @"class A { string aString = 'hello'; void M() { var len = aString.Length; } }"; using var testLspServer = CreateTestLspServer(string.Empty, out var _); AddMappedDocument(testLspServer.TestWorkspace, markup); var position = new LSP.Position { Line = 5, Character = 18 }; var results = await RunGotoDefinitionAsync(testLspServer, new LSP.Location { Uri = new Uri($"C:\\{TestSpanMapper.GeneratedFileName}"), Range = new LSP.Range { Start = position, End = position } }); AssertLocationsEqual(ImmutableArray.Create(TestSpanMapper.MappedFileLocation), results); } [Fact] public async Task TestGotoDefinitionAsync_InvalidLocation() { var markup = @"class A { void M() {{|caret:|} var len = aString.Length; } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } [Fact, WorkItem(1264627, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1264627")] public async Task TestGotoDefinitionAsync_NoResultsOnNamespace() { var markup = @"namespace {|caret:M|} { class A { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoDefinitionAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } private static async Task<LSP.Location[]> RunGotoDefinitionAsync(TestLspServer testLspServer, LSP.Location caret) { return await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.Location[]>(LSP.Methods.TextDocumentDefinitionName, CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), null, CancellationToken.None); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.SynthesizedMethodBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.CSharp.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { /// <summary> /// Represents a base implementation for anonymous type synthesized methods. /// </summary> private abstract class SynthesizedMethodBase : SynthesizedInstanceMethodSymbol { private readonly NamedTypeSymbol _containingType; private readonly string _name; public SynthesizedMethodBase(NamedTypeSymbol containingType, string name) { _containingType = containingType; _name = name; } internal sealed override bool GenerateDebugInfo { get { return false; } } public sealed override int Arity { get { return 0; } } public sealed override Symbol ContainingSymbol { get { return _containingType; } } public override NamedTypeSymbol ContainingType { get { return _containingType; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public sealed override Accessibility DeclaredAccessibility { get { return Accessibility.Public; } } public sealed override bool IsStatic { get { return false; } } public sealed override bool IsVirtual { get { return false; } } public sealed override bool IsAsync { get { return false; } } internal sealed override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return default(System.Reflection.MethodImplAttributes); } } internal sealed override Cci.CallingConvention CallingConvention { get { return Cci.CallingConvention.HasThis; } } public sealed override bool IsExtensionMethod { get { return false; } } public sealed override bool HidesBaseMethodsByName { get { return false; } } public sealed override bool IsVararg { get { return false; } } public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public sealed override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; public sealed override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations { get { return ImmutableArray<TypeWithAnnotations>.Empty; } } public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } internal sealed override bool IsExplicitInterfaceImplementation { get { return false; } } public sealed override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } // methods on classes are never 'readonly' internal sealed override bool IsDeclaredReadOnly => false; internal sealed override bool IsInitOnly => false; public sealed override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public override Symbol AssociatedSymbol { get { return null; } } public sealed override bool IsAbstract { get { return false; } } public sealed override bool IsSealed { get { return false; } } public sealed override bool IsExtern { get { return false; } } public sealed override string Name { get { return _name; } } internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); AddSynthesizedAttribute(ref attributes, Manager.Compilation.TrySynthesizeAttribute( WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor)); } protected AnonymousTypeManager Manager { get { AnonymousTypeTemplateSymbol template = _containingType as AnonymousTypeTemplateSymbol; return ((object)template != null) ? template.Manager : ((AnonymousTypePublicSymbol)_containingType).Manager; } } internal sealed override bool RequiresSecurityObject { get { return false; } } public sealed override DllImportData GetDllImportData() { return null; } internal sealed override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation { get { return null; } } internal sealed override bool HasDeclarativeSecurity { get { return false; } } internal sealed override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal sealed override ImmutableArray<string> GetAppliedConditionalSymbols() { return ImmutableArray<string>.Empty; } internal override bool SynthesizesLoweredBoundBody { get { return true; } } protected SyntheticBoundNodeFactory CreateBoundNodeFactory(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.GetNonNullSyntaxNode(), compilationState, diagnostics); F.CurrentFunction = this; return F; } internal sealed override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { throw 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 Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.CSharp.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { /// <summary> /// Represents a base implementation for anonymous type synthesized methods. /// </summary> private abstract class SynthesizedMethodBase : SynthesizedInstanceMethodSymbol { private readonly NamedTypeSymbol _containingType; private readonly string _name; public SynthesizedMethodBase(NamedTypeSymbol containingType, string name) { _containingType = containingType; _name = name; } internal sealed override bool GenerateDebugInfo { get { return false; } } public sealed override int Arity { get { return 0; } } public sealed override Symbol ContainingSymbol { get { return _containingType; } } public override NamedTypeSymbol ContainingType { get { return _containingType; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public sealed override Accessibility DeclaredAccessibility { get { return Accessibility.Public; } } public sealed override bool IsStatic { get { return false; } } public sealed override bool IsVirtual { get { return false; } } public sealed override bool IsAsync { get { return false; } } internal sealed override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return default(System.Reflection.MethodImplAttributes); } } internal sealed override Cci.CallingConvention CallingConvention { get { return Cci.CallingConvention.HasThis; } } public sealed override bool IsExtensionMethod { get { return false; } } public sealed override bool HidesBaseMethodsByName { get { return false; } } public sealed override bool IsVararg { get { return false; } } public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public sealed override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; public sealed override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations { get { return ImmutableArray<TypeWithAnnotations>.Empty; } } public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } internal sealed override bool IsExplicitInterfaceImplementation { get { return false; } } public sealed override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } // methods on classes are never 'readonly' internal sealed override bool IsDeclaredReadOnly => false; internal sealed override bool IsInitOnly => false; public sealed override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public override Symbol AssociatedSymbol { get { return null; } } public sealed override bool IsAbstract { get { return false; } } public sealed override bool IsSealed { get { return false; } } public sealed override bool IsExtern { get { return false; } } public sealed override string Name { get { return _name; } } internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); AddSynthesizedAttribute(ref attributes, Manager.Compilation.TrySynthesizeAttribute( WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor)); } protected AnonymousTypeManager Manager { get { AnonymousTypeTemplateSymbol template = _containingType as AnonymousTypeTemplateSymbol; return ((object)template != null) ? template.Manager : ((AnonymousTypePublicSymbol)_containingType).Manager; } } internal sealed override bool RequiresSecurityObject { get { return false; } } public sealed override DllImportData GetDllImportData() { return null; } internal sealed override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation { get { return null; } } internal sealed override bool HasDeclarativeSecurity { get { return false; } } internal sealed override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal sealed override ImmutableArray<string> GetAppliedConditionalSymbols() { return ImmutableArray<string>.Empty; } internal override bool SynthesizesLoweredBoundBody { get { return true; } } protected SyntheticBoundNodeFactory CreateBoundNodeFactory(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.GetNonNullSyntaxNode(), compilationState, diagnostics); F.CurrentFunction = this; return F; } internal sealed override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { throw ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/CSharp/Impl/Options/IntelliSenseOptionPage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { [Guid(Guids.CSharpOptionPageIntelliSenseIdString)] internal class IntelliSenseOptionPage : AbstractOptionPage { protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore) => new IntelliSenseOptionPageControl(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 System.Runtime.InteropServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { [Guid(Guids.CSharpOptionPageIntelliSenseIdString)] internal class IntelliSenseOptionPage : AbstractOptionPage { protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore) => new IntelliSenseOptionPageControl(optionStore); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest2/Recommendations/BaseKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class BaseKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTopLevelMethod() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"void Goo() { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement() { await VerifyAbsenceAsync( @"System.Console.WriteLine(); $$", options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration() { await VerifyAbsenceAsync( @"int i = 0; $$", options: CSharp9ParseOptions); } [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 TestInClassConstructorInitializer() { await VerifyKeywordAsync( @"class C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInRecordConstructorInitializer() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync(@" record C { public C() : $$", absent: false, options: TestOptions.RegularPreview); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticClassConstructorInitializer() { await VerifyAbsenceAsync( @"class C { static C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStructConstructorInitializer() { await VerifyAbsenceAsync( @"struct C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterCast() { await VerifyKeywordAsync( @"struct C { new internal ErrorCode Code { get { return (ErrorCode)$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyMethod() { await VerifyKeywordAsync( SourceCodeKind.Regular, AddInsideMethod( @"$$")); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumMemberInitializer1() { await VerifyAbsenceAsync( @"enum E { a = $$ }"); } [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(16335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/16335")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InExpressionBodyAccessor() { await VerifyKeywordAsync(@" class B { public virtual int T { get => bas$$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class BaseKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTopLevelMethod() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"void Goo() { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement() { await VerifyAbsenceAsync( @"System.Console.WriteLine(); $$", options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration() { await VerifyAbsenceAsync( @"int i = 0; $$", options: CSharp9ParseOptions); } [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 TestInClassConstructorInitializer() { await VerifyKeywordAsync( @"class C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInRecordConstructorInitializer() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync(@" record C { public C() : $$", absent: false, options: TestOptions.RegularPreview); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticClassConstructorInitializer() { await VerifyAbsenceAsync( @"class C { static C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStructConstructorInitializer() { await VerifyAbsenceAsync( @"struct C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterCast() { await VerifyKeywordAsync( @"struct C { new internal ErrorCode Code { get { return (ErrorCode)$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyMethod() { await VerifyKeywordAsync( SourceCodeKind.Regular, AddInsideMethod( @"$$")); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumMemberInitializer1() { await VerifyAbsenceAsync( @"enum E { a = $$ }"); } [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(16335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/16335")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InExpressionBodyAccessor() { await VerifyKeywordAsync(@" class B { public virtual int T { get => bas$$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest2/Recommendations/ParamKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ParamKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(529127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529127")] public async Task TestNotOfferedInsideArgumentList() => await VerifyAbsenceAsync("class C { void M([$$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(529127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529127")] public async Task TestNotOfferedInsideArgumentList2() => await VerifyAbsenceAsync("delegate void M([$$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(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 TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [Goo] [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterMethod() { await VerifyAbsenceAsync( @"class C { void Goo() { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterProperty() { await VerifyAbsenceAsync( @"class C { int Goo { get; } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterField() { await VerifyAbsenceAsync( @"class C { int Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterEvent() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInOuterAttribute() { await VerifyAbsenceAsync( @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameterAttribute() { await VerifyAbsenceAsync( @"class C { void Goo([$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPropertyAttribute1() { await VerifyKeywordAsync( @"class C { int Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPropertyAttribute2() { await VerifyKeywordAsync( @"class C { int Goo { get { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEventAttribute1() { await VerifyKeywordAsync( @"class C { event Action<int> Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEventAttribute2() { await VerifyKeywordAsync( @"class C { event Action<int> Goo { add { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTypeParameters() { await VerifyAbsenceAsync( @"class C<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInInterface() { await VerifyAbsenceAsync( @"interface I { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStruct() { await VerifyAbsenceAsync( @"struct S { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnum() { await VerifyAbsenceAsync( @"enum E { [$$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ParamKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(529127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529127")] public async Task TestNotOfferedInsideArgumentList() => await VerifyAbsenceAsync("class C { void M([$$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(529127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529127")] public async Task TestNotOfferedInsideArgumentList2() => await VerifyAbsenceAsync("delegate void M([$$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(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 TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [Goo] [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterMethod() { await VerifyAbsenceAsync( @"class C { void Goo() { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterProperty() { await VerifyAbsenceAsync( @"class C { int Goo { get; } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterField() { await VerifyAbsenceAsync( @"class C { int Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterEvent() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInOuterAttribute() { await VerifyAbsenceAsync( @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameterAttribute() { await VerifyAbsenceAsync( @"class C { void Goo([$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPropertyAttribute1() { await VerifyKeywordAsync( @"class C { int Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPropertyAttribute2() { await VerifyKeywordAsync( @"class C { int Goo { get { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEventAttribute1() { await VerifyKeywordAsync( @"class C { event Action<int> Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEventAttribute2() { await VerifyKeywordAsync( @"class C { event Action<int> Goo { add { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTypeParameters() { await VerifyAbsenceAsync( @"class C<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInInterface() { await VerifyAbsenceAsync( @"interface I { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStruct() { await VerifyAbsenceAsync( @"struct S { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnum() { await VerifyAbsenceAsync( @"enum E { [$$"); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/GenerateOverrides/GenerateOverridesCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.GenerateOverrides { [ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeRefactoringProviderNames.GenerateOverrides), Shared] [ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.AddConstructorParametersFromMembers)] internal partial class GenerateOverridesCodeRefactoringProvider : CodeRefactoringProvider { private readonly IPickMembersService? _pickMembersService_forTestingPurposes; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GenerateOverridesCodeRefactoringProvider() : this(null) { } [SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")] public GenerateOverridesCodeRefactoringProvider(IPickMembersService? pickMembersService) => _pickMembersService_forTestingPurposes = pickMembersService; public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // We offer the refactoring when the user is either on the header of a class/struct, // or if they're between any members of a class/struct and are on a blank line. if (!syntaxFacts.IsOnTypeHeader(root, textSpan.Start, out var typeDeclaration) && !syntaxFacts.IsBetweenTypeMembers(sourceText, root, textSpan.Start, out typeDeclaration)) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); // Only supported on classes/structs. var containingType = (INamedTypeSymbol)semanticModel.GetRequiredDeclaredSymbol(typeDeclaration, cancellationToken); var overridableMembers = containingType.GetOverridableMembers(cancellationToken); if (overridableMembers.Length == 0) { return; } context.RegisterRefactoring( new GenerateOverridesWithDialogCodeAction( this, document, textSpan, containingType, overridableMembers), typeDeclaration.Span); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.GenerateOverrides { [ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeRefactoringProviderNames.GenerateOverrides), Shared] [ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.AddConstructorParametersFromMembers)] internal partial class GenerateOverridesCodeRefactoringProvider : CodeRefactoringProvider { private readonly IPickMembersService? _pickMembersService_forTestingPurposes; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GenerateOverridesCodeRefactoringProvider() : this(null) { } [SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")] public GenerateOverridesCodeRefactoringProvider(IPickMembersService? pickMembersService) => _pickMembersService_forTestingPurposes = pickMembersService; public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // We offer the refactoring when the user is either on the header of a class/struct, // or if they're between any members of a class/struct and are on a blank line. if (!syntaxFacts.IsOnTypeHeader(root, textSpan.Start, out var typeDeclaration) && !syntaxFacts.IsBetweenTypeMembers(sourceText, root, textSpan.Start, out typeDeclaration)) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); // Only supported on classes/structs. var containingType = (INamedTypeSymbol)semanticModel.GetRequiredDeclaredSymbol(typeDeclaration, cancellationToken); var overridableMembers = containingType.GetOverridableMembers(cancellationToken); if (overridableMembers.Length == 0) { return; } context.RegisterRefactoring( new GenerateOverridesWithDialogCodeAction( this, document, textSpan, containingType, overridableMembers), typeDeclaration.Span); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Symbols/IDiscardSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis { /// <summary> /// A symbol representing a discarded value, e.g. a symbol in the result of /// GetSymbolInfo for <c>_</c> in <c>M(out _)</c> or <c>(x, _) = e</c>. /// </summary> public interface IDiscardSymbol : ISymbol { /// <summary> /// The type of the discarded value. /// </summary> ITypeSymbol Type { get; } /// <summary> /// The top-level nullability of the discarded value. /// </summary> NullableAnnotation NullableAnnotation { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; namespace Microsoft.CodeAnalysis { /// <summary> /// A symbol representing a discarded value, e.g. a symbol in the result of /// GetSymbolInfo for <c>_</c> in <c>M(out _)</c> or <c>(x, _) = e</c>. /// </summary> public interface IDiscardSymbol : ISymbol { /// <summary> /// The type of the discarded value. /// </summary> ITypeSymbol Type { get; } /// <summary> /// The top-level nullability of the discarded value. /// </summary> NullableAnnotation NullableAnnotation { get; } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Scripting/CSharpTest/ScriptTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Test; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using KeyValuePairUtil = Roslyn.Utilities.KeyValuePairUtil; namespace Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests { public class ScriptTests : TestBase { public class Globals { public int X; public int Y; } [Fact] public void TestCreateScript() { var script = CSharpScript.Create("1 + 2"); Assert.Equal("1 + 2", script.Code); } [Fact] public void TestCreateScript_CodeIsNull() { Assert.Throws<ArgumentNullException>(() => CSharpScript.Create((string)null)); } [Fact] public void TestCreateFromStreamScript() { var script = CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("1 + 2"))); Assert.Equal("1 + 2", script.Code); } [Fact] public void TestCreateFromStreamScript_StreamIsNull() { Assert.Throws<ArgumentNullException>(() => CSharpScript.Create((Stream)null)); } [Fact] public async Task TestGetCompilation() { var state = await CSharpScript.RunAsync("1 + 2", globals: new ScriptTests()); var compilation = state.Script.GetCompilation(); Assert.Equal(state.Script.Code, compilation.SyntaxTrees.First().GetText().ToString()); } [Fact] public async Task TestGetCompilationSourceText() { var state = await CSharpScript.RunAsync("1 + 2", globals: new ScriptTests()); var compilation = state.Script.GetCompilation(); Assert.Equal(state.Script.SourceText, compilation.SyntaxTrees.First().GetText()); } [Fact] public void TestEmit_PortablePdb() => TestEmit(DebugInformationFormat.PortablePdb); [ConditionalFact(typeof(WindowsOnly))] public void TestEmit_WindowsPdb() => TestEmit(DebugInformationFormat.Pdb); private void TestEmit(DebugInformationFormat format) { var script = CSharpScript.Create("1 + 2", options: ScriptOptions.Default.WithEmitDebugInformation(true)); var compilation = script.GetCompilation(); var emitOptions = ScriptBuilder.GetEmitOptions(emitDebugInformation: true).WithDebugInformationFormat(format); var peStream = new MemoryStream(); var pdbStream = new MemoryStream(); var emitResult = ScriptBuilder.Emit(peStream, pdbStream, compilation, emitOptions, cancellationToken: default); peStream.Position = 0; pdbStream.Position = 0; PdbValidation.ValidateDebugDirectory( peStream, portablePdbStreamOpt: (format == DebugInformationFormat.PortablePdb) ? pdbStream : null, pdbPath: compilation.AssemblyName + ".pdb", hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } [Fact] public async Task TestCreateScriptDelegate() { // create a delegate for the entire script var script = CSharpScript.Create("1 + 2"); var fn = script.CreateDelegate(); Assert.Equal(3, fn().Result); await Assert.ThrowsAsync<ArgumentException>("globals", () => fn(new object())); } [Fact] public async Task TestCreateScriptDelegateWithGlobals() { // create a delegate for the entire script var script = CSharpScript.Create<int>("X + Y", globalsType: typeof(Globals)); var fn = script.CreateDelegate(); await Assert.ThrowsAsync<ArgumentException>("globals", () => fn()); await Assert.ThrowsAsync<ArgumentException>("globals", () => fn(new object())); Assert.Equal(4, fn(new Globals { X = 1, Y = 3 }).Result); } [Fact] public async Task TestRunScript() { var state = await CSharpScript.RunAsync("1 + 2"); Assert.Equal(3, state.ReturnValue); } [Fact] public async Task TestCreateAndRunScript() { var script = CSharpScript.Create("1 + 2"); var state = await script.RunAsync(); Assert.Same(script, state.Script); Assert.Equal(3, state.ReturnValue); } [Fact] public async Task TestCreateFromStreamAndRunScript() { var script = CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("1 + 2"))); var state = await script.RunAsync(); Assert.Same(script, state.Script); Assert.Equal(3, state.ReturnValue); } [Fact] public async Task TestEvalScript() { var value = await CSharpScript.EvaluateAsync("1 + 2"); Assert.Equal(3, value); } [Fact] public async Task TestRunScriptWithSpecifiedReturnType() { var state = await CSharpScript.RunAsync("1 + 2"); Assert.Equal(3, state.ReturnValue); } [Fact] public void TestRunVoidScript() { var state = ScriptingTestHelpers.RunScriptWithOutput( CSharpScript.Create("System.Console.WriteLine(0);"), "0"); Assert.Null(state.ReturnValue); } [WorkItem(5279, "https://github.com/dotnet/roslyn/issues/5279")] [Fact] public async Task TestRunExpressionStatement() { var state = await CSharpScript.RunAsync( @"int F() { return 1; } F();"); Assert.Null(state.ReturnValue); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")] public async Task TestRunDynamicVoidScriptWithTerminatingSemicolon() { await CSharpScript.RunAsync(@" class SomeClass { public void Do() { } } dynamic d = new SomeClass(); d.Do();" , ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")] public async Task TestRunDynamicVoidScriptWithoutTerminatingSemicolon() { await CSharpScript.RunAsync(@" class SomeClass { public void Do() { } } dynamic d = new SomeClass(); d.Do()" , ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef)); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void TestRunEmbeddedStatementNotFollowedBySemicolon() { var exceptionThrown = false; try { var state = CSharpScript.RunAsync(@"if (true) System.Console.WriteLine(true)", globals: new ScriptTests()); } catch (CompilationErrorException ex) { exceptionThrown = true; ex.Diagnostics.Verify( // (2,32): error CS1002: ; expected // System.Console.WriteLine(true) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(2, 32)); } Assert.True(exceptionThrown); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void TestRunEmbeddedStatementFollowedBySemicolon() { var state = CSharpScript.RunAsync(@"if (true) System.Console.WriteLine(true);", globals: new ScriptTests()); Assert.Null(state.Exception); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void TestRunStatementFollowedBySpace() { var state = CSharpScript.RunAsync(@"System.Console.WriteLine(true) ", globals: new ScriptTests()); Assert.Null(state.Exception); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void TestRunStatementFollowedByNewLineNoSemicolon() { var state = CSharpScript.RunAsync(@" System.Console.WriteLine(true) ", globals: new ScriptTests()); Assert.Null(state.Exception); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void TestRunEmbeddedNoSemicolonFollowedByAnotherStatement() { var exceptionThrown = false; try { var state = CSharpScript.RunAsync(@"if (e) a = b throw e;", globals: new ScriptTests()); } catch (CompilationErrorException ex) { exceptionThrown = true; // Verify that it produces a single ExpectedSemicolon error. // No duplicates for the same error. ex.Diagnostics.Verify( // (1,13): error CS1002: ; expected // if (e) a = b Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 13)); } Assert.True(exceptionThrown); } [Fact] public async Task TestRunScriptWithGlobals() { var state = await CSharpScript.RunAsync("X + Y", globals: new Globals { X = 1, Y = 2 }); Assert.Equal(3, state.ReturnValue); } [Fact] public async Task TestRunCreatedScriptWithExpectedGlobals() { var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals)); var state = await script.RunAsync(new Globals { X = 1, Y = 2 }); Assert.Equal(3, state.ReturnValue); Assert.Same(script, state.Script); } [Fact] public async Task TestRunCreatedScriptWithUnexpectedGlobals() { var script = CSharpScript.Create("X + Y"); // Global variables passed to a script without a global type await Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync(new Globals { X = 1, Y = 2 })); } [Fact] public async Task TestRunCreatedScriptWithoutGlobals() { var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals)); // The script requires access to global variables but none were given await Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync()); } [Fact] public async Task TestRunCreatedScriptWithMismatchedGlobals() { var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals)); // The globals of type 'System.Object' is not assignable to 'Microsoft.CodeAnalysis.CSharp.Scripting.Test.ScriptTests+Globals' await Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync(new object())); } [Fact] public async Task ContinueAsync_Error1() { var state = await CSharpScript.RunAsync("X + Y", globals: new Globals()); await Assert.ThrowsAsync<ArgumentNullException>("previousState", () => state.Script.RunFromAsync(null)); } [Fact] public async Task ContinueAsync_Error2() { var state1 = await CSharpScript.RunAsync("X + Y + 1", globals: new Globals()); var state2 = await CSharpScript.RunAsync("X + Y + 2", globals: new Globals()); await Assert.ThrowsAsync<ArgumentException>("previousState", () => state1.Script.RunFromAsync(state2)); } [Fact] public async Task TestRunScriptWithScriptState() { // run a script using another scripts end state as the starting state (globals) var state = await CSharpScript.RunAsync("int X = 100;").ContinueWith("X + X"); Assert.Equal(200, state.ReturnValue); } [Fact] public async Task TestRepl() { var submissions = new[] { "int x = 100;", "int y = x * x;", "x + y" }; var state = await CSharpScript.RunAsync(""); foreach (var submission in submissions) { state = await state.ContinueWithAsync(submission); } Assert.Equal(10100, state.ReturnValue); } #if TODO // https://github.com/dotnet/roslyn/issues/3720 [Fact] public void TestCreateMethodDelegate() { // create a delegate to a method declared in the script var state = CSharpScript.Run("int Times(int x) { return x * x; }"); var fn = state.CreateDelegate<Func<int, int>>("Times"); var result = fn(5); Assert.Equal(25, result); } #endif [Fact] public async Task ScriptVariables_Chain() { var globals = new Globals { X = 10, Y = 20 }; var script = CSharpScript.Create( "var a = '1';", globalsType: globals.GetType()). ContinueWith("var b = 2u;"). ContinueWith("var a = 3m;"). ContinueWith("var x = a + b;"). ContinueWith("var X = Y;"); var state = await script.RunAsync(globals); AssertEx.Equal(new[] { "a", "b", "a", "x", "X" }, state.Variables.Select(v => v.Name)); AssertEx.Equal(new object[] { '1', 2u, 3m, 5m, 20 }, state.Variables.Select(v => v.Value)); AssertEx.Equal(new Type[] { typeof(char), typeof(uint), typeof(decimal), typeof(decimal), typeof(int) }, state.Variables.Select(v => v.Type)); Assert.Equal(3m, state.GetVariable("a").Value); Assert.Equal(2u, state.GetVariable("b").Value); Assert.Equal(5m, state.GetVariable("x").Value); Assert.Equal(20, state.GetVariable("X").Value); Assert.Null(state.GetVariable("A")); Assert.Same(state.GetVariable("X"), state.GetVariable("X")); } [Fact] public async Task ScriptVariable_SetValue() { var script = CSharpScript.Create("var x = 1;"); var s1 = await script.RunAsync(); s1.GetVariable("x").Value = 2; Assert.Equal(2, s1.GetVariable("x").Value); // rerunning the script from the beginning rebuilds the state: var s2 = await s1.Script.RunAsync(); Assert.Equal(1, s2.GetVariable("x").Value); // continuing preserves the state: var s3 = await s1.ContinueWithAsync("x"); Assert.Equal(2, s3.GetVariable("x").Value); Assert.Equal(2, s3.ReturnValue); } [Fact] public async Task ScriptVariable_SetValue_Errors() { var state = await CSharpScript.RunAsync(@" var x = 1; readonly var y = 2; const int z = 3; "); Assert.False(state.GetVariable("x").IsReadOnly); Assert.True(state.GetVariable("y").IsReadOnly); Assert.True(state.GetVariable("z").IsReadOnly); Assert.Throws<ArgumentException>(() => state.GetVariable("x").Value = "str"); Assert.Throws<InvalidOperationException>(() => state.GetVariable("y").Value = "str"); Assert.Throws<InvalidOperationException>(() => state.GetVariable("z").Value = "str"); Assert.Throws<InvalidOperationException>(() => state.GetVariable("y").Value = 0); Assert.Throws<InvalidOperationException>(() => state.GetVariable("z").Value = 0); } [Fact] public async Task TestBranchingSubscripts() { // run script to create declaration of M var state1 = await CSharpScript.RunAsync("int M(int x) { return x + x; }"); // run second script starting from first script's end state // this script's new declaration should hide the old declaration var state2 = await state1.ContinueWithAsync("int M(int x) { return x * x; } M(5)"); Assert.Equal(25, state2.ReturnValue); // run third script also starting from first script's end state // it should not see any declarations made by the second script. var state3 = await state1.ContinueWithAsync("M(5)"); Assert.Equal(10, state3.ReturnValue); } [Fact] public async Task ReturnIntAsObject() { var expected = 42; var script = CSharpScript.Create<object>($"return {expected};"); var result = await script.EvaluateAsync(); Assert.Equal(expected, result); } [Fact] public void NoReturn() { Assert.Null(ScriptingTestHelpers.EvaluateScriptWithOutput( CSharpScript.Create("System.Console.WriteLine();"), "")); } [Fact] public async Task ReturnAwait() { var script = CSharpScript.Create<int>("return await System.Threading.Tasks.Task.FromResult(42);"); var result = await script.EvaluateAsync(); Assert.Equal(42, result); } [Fact] public async Task ReturnInNestedScopeNoTrailingExpression() { var script = CSharpScript.Create(@" bool condition = false; if (condition) { return 1; }"); var result = await script.EvaluateAsync(); Assert.Null(result); } [Fact] public async Task ReturnInNestedScopeWithTrailingVoidExpression() { var script = CSharpScript.Create(@" bool condition = false; if (condition) { return 1; } System.Console.WriteLine();"); var result = await script.EvaluateAsync(); Assert.Null(result); script = CSharpScript.Create(@" bool condition = true; if (condition) { return 1; } System.Console.WriteLine();"); Assert.Equal(1, ScriptingTestHelpers.EvaluateScriptWithOutput(script, "")); } [Fact] public async Task ReturnInNestedScopeWithTrailingVoidExpressionAsInt() { var script = CSharpScript.Create<int>(@" bool condition = false; if (condition) { return 1; } System.Console.WriteLine();"); var result = await script.EvaluateAsync(); Assert.Equal(0, result); script = CSharpScript.Create<int>(@" bool condition = false; if (condition) { return 1; } System.Console.WriteLine()"); Assert.Equal(0, ScriptingTestHelpers.EvaluateScriptWithOutput(script, "")); } [Fact] public async Task ReturnIntWithTrailingDoubleExpression() { var script = CSharpScript.Create(@" bool condition = false; if (condition) { return 1; } 1.1"); var result = await script.EvaluateAsync(); Assert.Equal(1.1, result); script = CSharpScript.Create(@" bool condition = true; if (condition) { return 1; } 1.1"); result = await script.EvaluateAsync(); Assert.Equal(1, result); } [Fact] public async Task ReturnGenericAsInterface() { var script = CSharpScript.Create<IEnumerable<int>>(@" if (false) { return new System.Collections.Generic.List<int> { 1, 2, 3 }; }"); var result = await script.EvaluateAsync(); Assert.Null(result); script = CSharpScript.Create<IEnumerable<int>>(@" if (true) { return new System.Collections.Generic.List<int> { 1, 2, 3 }; }"); result = await script.EvaluateAsync(); Assert.Equal(new List<int> { 1, 2, 3 }, result); } [Fact] public async Task ReturnNullable() { var script = CSharpScript.Create<int?>(@" if (false) { return 42; }"); var result = await script.EvaluateAsync(); Assert.False(result.HasValue); script = CSharpScript.Create<int?>(@" if (true) { return 42; }"); result = await script.EvaluateAsync(); Assert.Equal(42, result); } [Fact] public async Task ReturnInLoadedFile() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "return 42;")); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create("#load \"a.csx\"", options); var result = await script.EvaluateAsync(); Assert.Equal(42, result); script = CSharpScript.Create(@" #load ""a.csx"" -1", options); result = await script.EvaluateAsync(); Assert.Equal(42, result); } [Fact] public async Task ReturnInLoadedFileTrailingExpression() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", @" if (false) { return 42; } 1")); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create("#load \"a.csx\"", options); var result = await script.EvaluateAsync(); Assert.Null(result); script = CSharpScript.Create(@" #load ""a.csx"" 2", options); result = await script.EvaluateAsync(); Assert.Equal(2, result); } [Fact] public void ReturnInLoadedFileTrailingVoidExpression() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", @" if (false) { return 1; } System.Console.WriteLine(42)")); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create("#load \"a.csx\"", options); var result = ScriptingTestHelpers.EvaluateScriptWithOutput(script, "42"); Assert.Null(result); script = CSharpScript.Create(@" #load ""a.csx"" 2", options); result = ScriptingTestHelpers.EvaluateScriptWithOutput(script, "42"); Assert.Equal(2, result); } [Fact] public async Task MultipleLoadedFilesWithTrailingExpression() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "1"), KeyValuePairUtil.Create("b.csx", @" #load ""a.csx"" 2")); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create("#load \"b.csx\"", options); var result = await script.EvaluateAsync(); Assert.Null(result); resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "1"), KeyValuePairUtil.Create("b.csx", "2")); options = ScriptOptions.Default.WithSourceResolver(resolver); script = CSharpScript.Create(@" #load ""a.csx"" #load ""b.csx""", options); result = await script.EvaluateAsync(); Assert.Null(result); resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "1"), KeyValuePairUtil.Create("b.csx", "2")); options = ScriptOptions.Default.WithSourceResolver(resolver); script = CSharpScript.Create(@" #load ""a.csx"" #load ""b.csx"" 3", options); result = await script.EvaluateAsync(); Assert.Equal(3, result); } [Fact] public async Task MultipleLoadedFilesWithReturnAndTrailingExpression() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "return 1;"), KeyValuePairUtil.Create("b.csx", @" #load ""a.csx"" 2")); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create("#load \"b.csx\"", options); var result = await script.EvaluateAsync(); Assert.Equal(1, result); resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "return 1;"), KeyValuePairUtil.Create("b.csx", "2")); options = ScriptOptions.Default.WithSourceResolver(resolver); script = CSharpScript.Create(@" #load ""a.csx"" #load ""b.csx""", options); result = await script.EvaluateAsync(); Assert.Equal(1, result); resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "return 1;"), KeyValuePairUtil.Create("b.csx", "2")); options = ScriptOptions.Default.WithSourceResolver(resolver); script = CSharpScript.Create(@" #load ""a.csx"" #load ""b.csx"" return 3;", options); result = await script.EvaluateAsync(); Assert.Equal(1, result); } [Fact] public async Task LoadedFileWithReturnAndGoto() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", @" goto EOF; NEXT: return 1; EOF:; 2")); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create(@" #load ""a.csx"" goto NEXT; return 3; NEXT:;", options); var result = await script.EvaluateAsync(); Assert.Null(result); script = CSharpScript.Create(@" #load ""a.csx"" L1: goto EOF; L2: return 3; EOF: EOF2: ; 4", options); result = await script.EvaluateAsync(); Assert.Equal(4, result); } [Fact] public async Task VoidReturn() { var script = CSharpScript.Create("return;"); var result = await script.EvaluateAsync(); Assert.Null(result); script = CSharpScript.Create(@" var b = true; if (b) { return; } b"); result = await script.EvaluateAsync(); Assert.Null(result); } [Fact] public async Task LoadedFileWithVoidReturn() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", @" var i = 42; return; i = -1;")); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create<int>(@" #load ""a.csx"" i", options); var result = await script.EvaluateAsync(); Assert.Equal(0, result); } [Fact] public async Task Pdb_CreateFromString_CodeFromFile_WithEmitDebugInformation_WithoutFileEncoding_CompilationErrorException() { var code = "throw new System.Exception();"; try { var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx").WithFileEncoding(null); var script = await CSharpScript.RunAsync(code, opts); } catch (CompilationErrorException ex) { // CS8055: Cannot emit debug information for a source text without encoding. ex.Diagnostics.Verify(Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, code).WithLocation(1, 1)); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public Task Pdb_CreateFromString_CodeFromFile_WithEmitDebugInformation_WithFileEncoding_ResultInPdbEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx").WithFileEncoding(Encoding.UTF8); return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: "debug.csx"); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public Task Pdb_CreateFromString_CodeFromFile_WithoutEmitDebugInformation_WithoutFileEncoding_ResultInPdbNotEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFilePath(null).WithFileEncoding(null); return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts)); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public Task Pdb_CreateFromString_CodeFromFile_WithoutEmitDebugInformation_WithFileEncoding_ResultInPdbNotEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFilePath("debug.csx").WithFileEncoding(Encoding.UTF8); return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts)); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public Task Pdb_CreateFromStream_CodeFromFile_WithEmitDebugInformation_ResultInPdbEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx"); return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts), line: 1, column: 1, filename: "debug.csx"); } [Fact] public Task Pdb_CreateFromStream_CodeFromFile_WithoutEmitDebugInformation_ResultInPdbNotEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFilePath("debug.csx"); return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts)); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public Task Pdb_CreateFromString_InlineCode_WithEmitDebugInformation_WithoutFileEncoding_ResultInPdbEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFileEncoding(null); return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: ""); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public Task Pdb_CreateFromString_InlineCode_WithEmitDebugInformation_WithFileEncoding_ResultInPdbEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFileEncoding(Encoding.UTF8); return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: ""); } [Fact] public Task Pdb_CreateFromString_InlineCode_WithoutEmitDebugInformation_WithoutFileEncoding_ResultInPdbNotEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFileEncoding(null); return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts)); } [Fact] public Task Pdb_CreateFromString_InlineCode_WithoutEmitDebugInformation_WithFileEncoding_ResultInPdbNotEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFileEncoding(Encoding.UTF8); return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts)); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public Task Pdb_CreateFromStream_InlineCode_WithEmitDebugInformation_ResultInPdbEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(true); return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts), line: 1, column: 1, filename: ""); } [Fact] public Task Pdb_CreateFromStream_InlineCode_WithoutEmitDebugInformation_ResultInPdbNotEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(false); return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts)); } [WorkItem(12348, "https://github.com/dotnet/roslyn/issues/12348")] [Fact] public void StreamWithOffset() { var resolver = new StreamOffsetResolver(); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create(@"#load ""a.csx""", options); ScriptingTestHelpers.EvaluateScriptWithOutput(script, "Hello World!"); } [Fact] public void CreateScriptWithFeatureThatIsNotSupportedInTheSelectedLanguageVersion() { var script = CSharpScript.Create(@"string x = default;", ScriptOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7)); var compilation = script.GetCompilation(); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "default"). WithArguments("default literal", "7.1"). WithLocation(1, 12) ); } [Fact] public void CreateScriptWithNullableContextWithCSharp8() { var script = CSharpScript.Create(@"#nullable enable string x = null;", ScriptOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8)); var compilation = script.GetCompilation(); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(2, 28) ); } private class StreamOffsetResolver : SourceReferenceResolver { public override bool Equals(object other) => ReferenceEquals(this, other); public override int GetHashCode() => 42; public override string ResolveReference(string path, string baseFilePath) => path; public override string NormalizePath(string path, string baseFilePath) => path; public override Stream OpenRead(string resolvedPath) { // Make an ASCII text buffer with Hello World script preceded by padding Qs const int padding = 42; string text = @"System.Console.WriteLine(""Hello World!"");"; byte[] bytes = Enumerable.Repeat((byte)'Q', text.Length + padding).ToArray(); System.Text.Encoding.ASCII.GetBytes(text, 0, text.Length, bytes, padding); // Make a stream over the program portion, skipping the Qs. var stream = new MemoryStream( bytes, padding, text.Length, writable: false, publiclyVisible: true); // sanity check that reading entire stream gives us back our text. using (var streamReader = new StreamReader( stream, System.Text.Encoding.ASCII, detectEncodingFromByteOrderMarks: false, bufferSize: bytes.Length, leaveOpen: true)) { var textFromStream = streamReader.ReadToEnd(); Assert.Equal(textFromStream, text); } stream.Position = 0; return stream; } } private async Task VerifyStackTraceAsync(Func<Script<object>> scriptProvider, int line = 0, int column = 0, string filename = null) { try { var script = scriptProvider(); await script.RunAsync(); } catch (Exception ex) { // line information is only available when PDBs have been emitted var needFileInfo = true; var stackTrace = new StackTrace(ex, needFileInfo); var firstFrame = stackTrace.GetFrames()[0]; Assert.Equal(filename, firstFrame.GetFileName()); Assert.Equal(line, firstFrame.GetFileLineNumber()); Assert.Equal(column, firstFrame.GetFileColumnNumber()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Test; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using KeyValuePairUtil = Roslyn.Utilities.KeyValuePairUtil; namespace Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests { public class ScriptTests : TestBase { public class Globals { public int X; public int Y; } [Fact] public void TestCreateScript() { var script = CSharpScript.Create("1 + 2"); Assert.Equal("1 + 2", script.Code); } [Fact] public void TestCreateScript_CodeIsNull() { Assert.Throws<ArgumentNullException>(() => CSharpScript.Create((string)null)); } [Fact] public void TestCreateFromStreamScript() { var script = CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("1 + 2"))); Assert.Equal("1 + 2", script.Code); } [Fact] public void TestCreateFromStreamScript_StreamIsNull() { Assert.Throws<ArgumentNullException>(() => CSharpScript.Create((Stream)null)); } [Fact] public async Task TestGetCompilation() { var state = await CSharpScript.RunAsync("1 + 2", globals: new ScriptTests()); var compilation = state.Script.GetCompilation(); Assert.Equal(state.Script.Code, compilation.SyntaxTrees.First().GetText().ToString()); } [Fact] public async Task TestGetCompilationSourceText() { var state = await CSharpScript.RunAsync("1 + 2", globals: new ScriptTests()); var compilation = state.Script.GetCompilation(); Assert.Equal(state.Script.SourceText, compilation.SyntaxTrees.First().GetText()); } [Fact] public void TestEmit_PortablePdb() => TestEmit(DebugInformationFormat.PortablePdb); [ConditionalFact(typeof(WindowsOnly))] public void TestEmit_WindowsPdb() => TestEmit(DebugInformationFormat.Pdb); private void TestEmit(DebugInformationFormat format) { var script = CSharpScript.Create("1 + 2", options: ScriptOptions.Default.WithEmitDebugInformation(true)); var compilation = script.GetCompilation(); var emitOptions = ScriptBuilder.GetEmitOptions(emitDebugInformation: true).WithDebugInformationFormat(format); var peStream = new MemoryStream(); var pdbStream = new MemoryStream(); var emitResult = ScriptBuilder.Emit(peStream, pdbStream, compilation, emitOptions, cancellationToken: default); peStream.Position = 0; pdbStream.Position = 0; PdbValidation.ValidateDebugDirectory( peStream, portablePdbStreamOpt: (format == DebugInformationFormat.PortablePdb) ? pdbStream : null, pdbPath: compilation.AssemblyName + ".pdb", hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } [Fact] public async Task TestCreateScriptDelegate() { // create a delegate for the entire script var script = CSharpScript.Create("1 + 2"); var fn = script.CreateDelegate(); Assert.Equal(3, fn().Result); await Assert.ThrowsAsync<ArgumentException>("globals", () => fn(new object())); } [Fact] public async Task TestCreateScriptDelegateWithGlobals() { // create a delegate for the entire script var script = CSharpScript.Create<int>("X + Y", globalsType: typeof(Globals)); var fn = script.CreateDelegate(); await Assert.ThrowsAsync<ArgumentException>("globals", () => fn()); await Assert.ThrowsAsync<ArgumentException>("globals", () => fn(new object())); Assert.Equal(4, fn(new Globals { X = 1, Y = 3 }).Result); } [Fact] public async Task TestRunScript() { var state = await CSharpScript.RunAsync("1 + 2"); Assert.Equal(3, state.ReturnValue); } [Fact] public async Task TestCreateAndRunScript() { var script = CSharpScript.Create("1 + 2"); var state = await script.RunAsync(); Assert.Same(script, state.Script); Assert.Equal(3, state.ReturnValue); } [Fact] public async Task TestCreateFromStreamAndRunScript() { var script = CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("1 + 2"))); var state = await script.RunAsync(); Assert.Same(script, state.Script); Assert.Equal(3, state.ReturnValue); } [Fact] public async Task TestEvalScript() { var value = await CSharpScript.EvaluateAsync("1 + 2"); Assert.Equal(3, value); } [Fact] public async Task TestRunScriptWithSpecifiedReturnType() { var state = await CSharpScript.RunAsync("1 + 2"); Assert.Equal(3, state.ReturnValue); } [Fact] public void TestRunVoidScript() { var state = ScriptingTestHelpers.RunScriptWithOutput( CSharpScript.Create("System.Console.WriteLine(0);"), "0"); Assert.Null(state.ReturnValue); } [WorkItem(5279, "https://github.com/dotnet/roslyn/issues/5279")] [Fact] public async Task TestRunExpressionStatement() { var state = await CSharpScript.RunAsync( @"int F() { return 1; } F();"); Assert.Null(state.ReturnValue); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")] public async Task TestRunDynamicVoidScriptWithTerminatingSemicolon() { await CSharpScript.RunAsync(@" class SomeClass { public void Do() { } } dynamic d = new SomeClass(); d.Do();" , ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/170")] public async Task TestRunDynamicVoidScriptWithoutTerminatingSemicolon() { await CSharpScript.RunAsync(@" class SomeClass { public void Do() { } } dynamic d = new SomeClass(); d.Do()" , ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef)); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void TestRunEmbeddedStatementNotFollowedBySemicolon() { var exceptionThrown = false; try { var state = CSharpScript.RunAsync(@"if (true) System.Console.WriteLine(true)", globals: new ScriptTests()); } catch (CompilationErrorException ex) { exceptionThrown = true; ex.Diagnostics.Verify( // (2,32): error CS1002: ; expected // System.Console.WriteLine(true) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(2, 32)); } Assert.True(exceptionThrown); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void TestRunEmbeddedStatementFollowedBySemicolon() { var state = CSharpScript.RunAsync(@"if (true) System.Console.WriteLine(true);", globals: new ScriptTests()); Assert.Null(state.Exception); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void TestRunStatementFollowedBySpace() { var state = CSharpScript.RunAsync(@"System.Console.WriteLine(true) ", globals: new ScriptTests()); Assert.Null(state.Exception); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void TestRunStatementFollowedByNewLineNoSemicolon() { var state = CSharpScript.RunAsync(@" System.Console.WriteLine(true) ", globals: new ScriptTests()); Assert.Null(state.Exception); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void TestRunEmbeddedNoSemicolonFollowedByAnotherStatement() { var exceptionThrown = false; try { var state = CSharpScript.RunAsync(@"if (e) a = b throw e;", globals: new ScriptTests()); } catch (CompilationErrorException ex) { exceptionThrown = true; // Verify that it produces a single ExpectedSemicolon error. // No duplicates for the same error. ex.Diagnostics.Verify( // (1,13): error CS1002: ; expected // if (e) a = b Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 13)); } Assert.True(exceptionThrown); } [Fact] public async Task TestRunScriptWithGlobals() { var state = await CSharpScript.RunAsync("X + Y", globals: new Globals { X = 1, Y = 2 }); Assert.Equal(3, state.ReturnValue); } [Fact] public async Task TestRunCreatedScriptWithExpectedGlobals() { var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals)); var state = await script.RunAsync(new Globals { X = 1, Y = 2 }); Assert.Equal(3, state.ReturnValue); Assert.Same(script, state.Script); } [Fact] public async Task TestRunCreatedScriptWithUnexpectedGlobals() { var script = CSharpScript.Create("X + Y"); // Global variables passed to a script without a global type await Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync(new Globals { X = 1, Y = 2 })); } [Fact] public async Task TestRunCreatedScriptWithoutGlobals() { var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals)); // The script requires access to global variables but none were given await Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync()); } [Fact] public async Task TestRunCreatedScriptWithMismatchedGlobals() { var script = CSharpScript.Create("X + Y", globalsType: typeof(Globals)); // The globals of type 'System.Object' is not assignable to 'Microsoft.CodeAnalysis.CSharp.Scripting.Test.ScriptTests+Globals' await Assert.ThrowsAsync<ArgumentException>("globals", () => script.RunAsync(new object())); } [Fact] public async Task ContinueAsync_Error1() { var state = await CSharpScript.RunAsync("X + Y", globals: new Globals()); await Assert.ThrowsAsync<ArgumentNullException>("previousState", () => state.Script.RunFromAsync(null)); } [Fact] public async Task ContinueAsync_Error2() { var state1 = await CSharpScript.RunAsync("X + Y + 1", globals: new Globals()); var state2 = await CSharpScript.RunAsync("X + Y + 2", globals: new Globals()); await Assert.ThrowsAsync<ArgumentException>("previousState", () => state1.Script.RunFromAsync(state2)); } [Fact] public async Task TestRunScriptWithScriptState() { // run a script using another scripts end state as the starting state (globals) var state = await CSharpScript.RunAsync("int X = 100;").ContinueWith("X + X"); Assert.Equal(200, state.ReturnValue); } [Fact] public async Task TestRepl() { var submissions = new[] { "int x = 100;", "int y = x * x;", "x + y" }; var state = await CSharpScript.RunAsync(""); foreach (var submission in submissions) { state = await state.ContinueWithAsync(submission); } Assert.Equal(10100, state.ReturnValue); } #if TODO // https://github.com/dotnet/roslyn/issues/3720 [Fact] public void TestCreateMethodDelegate() { // create a delegate to a method declared in the script var state = CSharpScript.Run("int Times(int x) { return x * x; }"); var fn = state.CreateDelegate<Func<int, int>>("Times"); var result = fn(5); Assert.Equal(25, result); } #endif [Fact] public async Task ScriptVariables_Chain() { var globals = new Globals { X = 10, Y = 20 }; var script = CSharpScript.Create( "var a = '1';", globalsType: globals.GetType()). ContinueWith("var b = 2u;"). ContinueWith("var a = 3m;"). ContinueWith("var x = a + b;"). ContinueWith("var X = Y;"); var state = await script.RunAsync(globals); AssertEx.Equal(new[] { "a", "b", "a", "x", "X" }, state.Variables.Select(v => v.Name)); AssertEx.Equal(new object[] { '1', 2u, 3m, 5m, 20 }, state.Variables.Select(v => v.Value)); AssertEx.Equal(new Type[] { typeof(char), typeof(uint), typeof(decimal), typeof(decimal), typeof(int) }, state.Variables.Select(v => v.Type)); Assert.Equal(3m, state.GetVariable("a").Value); Assert.Equal(2u, state.GetVariable("b").Value); Assert.Equal(5m, state.GetVariable("x").Value); Assert.Equal(20, state.GetVariable("X").Value); Assert.Null(state.GetVariable("A")); Assert.Same(state.GetVariable("X"), state.GetVariable("X")); } [Fact] public async Task ScriptVariable_SetValue() { var script = CSharpScript.Create("var x = 1;"); var s1 = await script.RunAsync(); s1.GetVariable("x").Value = 2; Assert.Equal(2, s1.GetVariable("x").Value); // rerunning the script from the beginning rebuilds the state: var s2 = await s1.Script.RunAsync(); Assert.Equal(1, s2.GetVariable("x").Value); // continuing preserves the state: var s3 = await s1.ContinueWithAsync("x"); Assert.Equal(2, s3.GetVariable("x").Value); Assert.Equal(2, s3.ReturnValue); } [Fact] public async Task ScriptVariable_SetValue_Errors() { var state = await CSharpScript.RunAsync(@" var x = 1; readonly var y = 2; const int z = 3; "); Assert.False(state.GetVariable("x").IsReadOnly); Assert.True(state.GetVariable("y").IsReadOnly); Assert.True(state.GetVariable("z").IsReadOnly); Assert.Throws<ArgumentException>(() => state.GetVariable("x").Value = "str"); Assert.Throws<InvalidOperationException>(() => state.GetVariable("y").Value = "str"); Assert.Throws<InvalidOperationException>(() => state.GetVariable("z").Value = "str"); Assert.Throws<InvalidOperationException>(() => state.GetVariable("y").Value = 0); Assert.Throws<InvalidOperationException>(() => state.GetVariable("z").Value = 0); } [Fact] public async Task TestBranchingSubscripts() { // run script to create declaration of M var state1 = await CSharpScript.RunAsync("int M(int x) { return x + x; }"); // run second script starting from first script's end state // this script's new declaration should hide the old declaration var state2 = await state1.ContinueWithAsync("int M(int x) { return x * x; } M(5)"); Assert.Equal(25, state2.ReturnValue); // run third script also starting from first script's end state // it should not see any declarations made by the second script. var state3 = await state1.ContinueWithAsync("M(5)"); Assert.Equal(10, state3.ReturnValue); } [Fact] public async Task ReturnIntAsObject() { var expected = 42; var script = CSharpScript.Create<object>($"return {expected};"); var result = await script.EvaluateAsync(); Assert.Equal(expected, result); } [Fact] public void NoReturn() { Assert.Null(ScriptingTestHelpers.EvaluateScriptWithOutput( CSharpScript.Create("System.Console.WriteLine();"), "")); } [Fact] public async Task ReturnAwait() { var script = CSharpScript.Create<int>("return await System.Threading.Tasks.Task.FromResult(42);"); var result = await script.EvaluateAsync(); Assert.Equal(42, result); } [Fact] public async Task ReturnInNestedScopeNoTrailingExpression() { var script = CSharpScript.Create(@" bool condition = false; if (condition) { return 1; }"); var result = await script.EvaluateAsync(); Assert.Null(result); } [Fact] public async Task ReturnInNestedScopeWithTrailingVoidExpression() { var script = CSharpScript.Create(@" bool condition = false; if (condition) { return 1; } System.Console.WriteLine();"); var result = await script.EvaluateAsync(); Assert.Null(result); script = CSharpScript.Create(@" bool condition = true; if (condition) { return 1; } System.Console.WriteLine();"); Assert.Equal(1, ScriptingTestHelpers.EvaluateScriptWithOutput(script, "")); } [Fact] public async Task ReturnInNestedScopeWithTrailingVoidExpressionAsInt() { var script = CSharpScript.Create<int>(@" bool condition = false; if (condition) { return 1; } System.Console.WriteLine();"); var result = await script.EvaluateAsync(); Assert.Equal(0, result); script = CSharpScript.Create<int>(@" bool condition = false; if (condition) { return 1; } System.Console.WriteLine()"); Assert.Equal(0, ScriptingTestHelpers.EvaluateScriptWithOutput(script, "")); } [Fact] public async Task ReturnIntWithTrailingDoubleExpression() { var script = CSharpScript.Create(@" bool condition = false; if (condition) { return 1; } 1.1"); var result = await script.EvaluateAsync(); Assert.Equal(1.1, result); script = CSharpScript.Create(@" bool condition = true; if (condition) { return 1; } 1.1"); result = await script.EvaluateAsync(); Assert.Equal(1, result); } [Fact] public async Task ReturnGenericAsInterface() { var script = CSharpScript.Create<IEnumerable<int>>(@" if (false) { return new System.Collections.Generic.List<int> { 1, 2, 3 }; }"); var result = await script.EvaluateAsync(); Assert.Null(result); script = CSharpScript.Create<IEnumerable<int>>(@" if (true) { return new System.Collections.Generic.List<int> { 1, 2, 3 }; }"); result = await script.EvaluateAsync(); Assert.Equal(new List<int> { 1, 2, 3 }, result); } [Fact] public async Task ReturnNullable() { var script = CSharpScript.Create<int?>(@" if (false) { return 42; }"); var result = await script.EvaluateAsync(); Assert.False(result.HasValue); script = CSharpScript.Create<int?>(@" if (true) { return 42; }"); result = await script.EvaluateAsync(); Assert.Equal(42, result); } [Fact] public async Task ReturnInLoadedFile() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "return 42;")); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create("#load \"a.csx\"", options); var result = await script.EvaluateAsync(); Assert.Equal(42, result); script = CSharpScript.Create(@" #load ""a.csx"" -1", options); result = await script.EvaluateAsync(); Assert.Equal(42, result); } [Fact] public async Task ReturnInLoadedFileTrailingExpression() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", @" if (false) { return 42; } 1")); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create("#load \"a.csx\"", options); var result = await script.EvaluateAsync(); Assert.Null(result); script = CSharpScript.Create(@" #load ""a.csx"" 2", options); result = await script.EvaluateAsync(); Assert.Equal(2, result); } [Fact] public void ReturnInLoadedFileTrailingVoidExpression() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", @" if (false) { return 1; } System.Console.WriteLine(42)")); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create("#load \"a.csx\"", options); var result = ScriptingTestHelpers.EvaluateScriptWithOutput(script, "42"); Assert.Null(result); script = CSharpScript.Create(@" #load ""a.csx"" 2", options); result = ScriptingTestHelpers.EvaluateScriptWithOutput(script, "42"); Assert.Equal(2, result); } [Fact] public async Task MultipleLoadedFilesWithTrailingExpression() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "1"), KeyValuePairUtil.Create("b.csx", @" #load ""a.csx"" 2")); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create("#load \"b.csx\"", options); var result = await script.EvaluateAsync(); Assert.Null(result); resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "1"), KeyValuePairUtil.Create("b.csx", "2")); options = ScriptOptions.Default.WithSourceResolver(resolver); script = CSharpScript.Create(@" #load ""a.csx"" #load ""b.csx""", options); result = await script.EvaluateAsync(); Assert.Null(result); resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "1"), KeyValuePairUtil.Create("b.csx", "2")); options = ScriptOptions.Default.WithSourceResolver(resolver); script = CSharpScript.Create(@" #load ""a.csx"" #load ""b.csx"" 3", options); result = await script.EvaluateAsync(); Assert.Equal(3, result); } [Fact] public async Task MultipleLoadedFilesWithReturnAndTrailingExpression() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "return 1;"), KeyValuePairUtil.Create("b.csx", @" #load ""a.csx"" 2")); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create("#load \"b.csx\"", options); var result = await script.EvaluateAsync(); Assert.Equal(1, result); resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "return 1;"), KeyValuePairUtil.Create("b.csx", "2")); options = ScriptOptions.Default.WithSourceResolver(resolver); script = CSharpScript.Create(@" #load ""a.csx"" #load ""b.csx""", options); result = await script.EvaluateAsync(); Assert.Equal(1, result); resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "return 1;"), KeyValuePairUtil.Create("b.csx", "2")); options = ScriptOptions.Default.WithSourceResolver(resolver); script = CSharpScript.Create(@" #load ""a.csx"" #load ""b.csx"" return 3;", options); result = await script.EvaluateAsync(); Assert.Equal(1, result); } [Fact] public async Task LoadedFileWithReturnAndGoto() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", @" goto EOF; NEXT: return 1; EOF:; 2")); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create(@" #load ""a.csx"" goto NEXT; return 3; NEXT:;", options); var result = await script.EvaluateAsync(); Assert.Null(result); script = CSharpScript.Create(@" #load ""a.csx"" L1: goto EOF; L2: return 3; EOF: EOF2: ; 4", options); result = await script.EvaluateAsync(); Assert.Equal(4, result); } [Fact] public async Task VoidReturn() { var script = CSharpScript.Create("return;"); var result = await script.EvaluateAsync(); Assert.Null(result); script = CSharpScript.Create(@" var b = true; if (b) { return; } b"); result = await script.EvaluateAsync(); Assert.Null(result); } [Fact] public async Task LoadedFileWithVoidReturn() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", @" var i = 42; return; i = -1;")); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create<int>(@" #load ""a.csx"" i", options); var result = await script.EvaluateAsync(); Assert.Equal(0, result); } [Fact] public async Task Pdb_CreateFromString_CodeFromFile_WithEmitDebugInformation_WithoutFileEncoding_CompilationErrorException() { var code = "throw new System.Exception();"; try { var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx").WithFileEncoding(null); var script = await CSharpScript.RunAsync(code, opts); } catch (CompilationErrorException ex) { // CS8055: Cannot emit debug information for a source text without encoding. ex.Diagnostics.Verify(Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, code).WithLocation(1, 1)); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public Task Pdb_CreateFromString_CodeFromFile_WithEmitDebugInformation_WithFileEncoding_ResultInPdbEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx").WithFileEncoding(Encoding.UTF8); return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: "debug.csx"); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public Task Pdb_CreateFromString_CodeFromFile_WithoutEmitDebugInformation_WithoutFileEncoding_ResultInPdbNotEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFilePath(null).WithFileEncoding(null); return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts)); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public Task Pdb_CreateFromString_CodeFromFile_WithoutEmitDebugInformation_WithFileEncoding_ResultInPdbNotEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFilePath("debug.csx").WithFileEncoding(Encoding.UTF8); return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts)); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public Task Pdb_CreateFromStream_CodeFromFile_WithEmitDebugInformation_ResultInPdbEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFilePath("debug.csx"); return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts), line: 1, column: 1, filename: "debug.csx"); } [Fact] public Task Pdb_CreateFromStream_CodeFromFile_WithoutEmitDebugInformation_ResultInPdbNotEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFilePath("debug.csx"); return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts)); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public Task Pdb_CreateFromString_InlineCode_WithEmitDebugInformation_WithoutFileEncoding_ResultInPdbEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFileEncoding(null); return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: ""); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public Task Pdb_CreateFromString_InlineCode_WithEmitDebugInformation_WithFileEncoding_ResultInPdbEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(true).WithFileEncoding(Encoding.UTF8); return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts), line: 1, column: 1, filename: ""); } [Fact] public Task Pdb_CreateFromString_InlineCode_WithoutEmitDebugInformation_WithoutFileEncoding_ResultInPdbNotEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFileEncoding(null); return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts)); } [Fact] public Task Pdb_CreateFromString_InlineCode_WithoutEmitDebugInformation_WithFileEncoding_ResultInPdbNotEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(false).WithFileEncoding(Encoding.UTF8); return VerifyStackTraceAsync(() => CSharpScript.Create("throw new System.Exception();", opts)); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public Task Pdb_CreateFromStream_InlineCode_WithEmitDebugInformation_ResultInPdbEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(true); return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts), line: 1, column: 1, filename: ""); } [Fact] public Task Pdb_CreateFromStream_InlineCode_WithoutEmitDebugInformation_ResultInPdbNotEmitted() { var opts = ScriptOptions.Default.WithEmitDebugInformation(false); return VerifyStackTraceAsync(() => CSharpScript.Create(new MemoryStream(Encoding.UTF8.GetBytes("throw new System.Exception();")), opts)); } [WorkItem(12348, "https://github.com/dotnet/roslyn/issues/12348")] [Fact] public void StreamWithOffset() { var resolver = new StreamOffsetResolver(); var options = ScriptOptions.Default.WithSourceResolver(resolver); var script = CSharpScript.Create(@"#load ""a.csx""", options); ScriptingTestHelpers.EvaluateScriptWithOutput(script, "Hello World!"); } [Fact] public void CreateScriptWithFeatureThatIsNotSupportedInTheSelectedLanguageVersion() { var script = CSharpScript.Create(@"string x = default;", ScriptOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7)); var compilation = script.GetCompilation(); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "default"). WithArguments("default literal", "7.1"). WithLocation(1, 12) ); } [Fact] public void CreateScriptWithNullableContextWithCSharp8() { var script = CSharpScript.Create(@"#nullable enable string x = null;", ScriptOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8)); var compilation = script.GetCompilation(); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(2, 28) ); } private class StreamOffsetResolver : SourceReferenceResolver { public override bool Equals(object other) => ReferenceEquals(this, other); public override int GetHashCode() => 42; public override string ResolveReference(string path, string baseFilePath) => path; public override string NormalizePath(string path, string baseFilePath) => path; public override Stream OpenRead(string resolvedPath) { // Make an ASCII text buffer with Hello World script preceded by padding Qs const int padding = 42; string text = @"System.Console.WriteLine(""Hello World!"");"; byte[] bytes = Enumerable.Repeat((byte)'Q', text.Length + padding).ToArray(); System.Text.Encoding.ASCII.GetBytes(text, 0, text.Length, bytes, padding); // Make a stream over the program portion, skipping the Qs. var stream = new MemoryStream( bytes, padding, text.Length, writable: false, publiclyVisible: true); // sanity check that reading entire stream gives us back our text. using (var streamReader = new StreamReader( stream, System.Text.Encoding.ASCII, detectEncodingFromByteOrderMarks: false, bufferSize: bytes.Length, leaveOpen: true)) { var textFromStream = streamReader.ReadToEnd(); Assert.Equal(textFromStream, text); } stream.Position = 0; return stream; } } private async Task VerifyStackTraceAsync(Func<Script<object>> scriptProvider, int line = 0, int column = 0, string filename = null) { try { var script = scriptProvider(); await script.RunAsync(); } catch (Exception ex) { // line information is only available when PDBs have been emitted var needFileInfo = true; var stackTrace = new StackTrace(ex, needFileInfo); var firstFrame = stackTrace.GetFrames()[0]; Assert.Equal(filename, firstFrame.GetFileName()); Assert.Equal(line, firstFrame.GetFileLineNumber()); Assert.Equal(column, firstFrame.GetFileColumnNumber()); } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/ExtractMethod/Enums.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.ExtractMethod { internal enum DeclarationBehavior { None, Delete, MoveIn, MoveOut, SplitIn, SplitOut } internal enum ReturnBehavior { None, Initialization, Assignment } internal enum ParameterBehavior { None, Input, Out, Ref } /// <summary> /// status code for extract method operations /// </summary> [Flags] internal enum OperationStatusFlag { None = 0x0, /// <summary> /// operation has succeeded /// </summary> Succeeded = 0x1, /// <summary> /// operation has succeeded with a span that is different than original span /// </summary> Suggestion = 0x2, /// <summary> /// operation has failed but can provide some best effort result /// </summary> BestEffort = 0x4, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.ExtractMethod { internal enum DeclarationBehavior { None, Delete, MoveIn, MoveOut, SplitIn, SplitOut } internal enum ReturnBehavior { None, Initialization, Assignment } internal enum ParameterBehavior { None, Input, Out, Ref } /// <summary> /// status code for extract method operations /// </summary> [Flags] internal enum OperationStatusFlag { None = 0x0, /// <summary> /// operation has succeeded /// </summary> Succeeded = 0x1, /// <summary> /// operation has succeeded with a span that is different than original span /// </summary> Suggestion = 0x2, /// <summary> /// operation has failed but can provide some best effort result /// </summary> BestEffort = 0x4, } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/InternalUtilities/SpecializedCollections.Empty.Dictionary.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class Empty { internal class Dictionary<TKey, TValue> #nullable disable // Note: if the interfaces we implement weren't oblivious, then we'd warn about the `[MaybeNullWhen(false)] out TValue value` parameter below // We can remove this once `IDictionary` is annotated with `[MaybeNullWhen(false)]` : Collection<KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue> #nullable enable where TKey : notnull { public static new readonly Dictionary<TKey, TValue> Instance = new(); private Dictionary() { } public void Add(TKey key, TValue value) { throw new NotSupportedException(); } public bool ContainsKey(TKey key) { return false; } public ICollection<TKey> Keys { get { return Collection<TKey>.Instance; } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Keys; IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Values; public bool Remove(TKey key) { throw new NotSupportedException(); } public bool TryGetValue(TKey key, [MaybeNullWhen(returnValue: false)] out TValue value) { value = default!; return false; } public ICollection<TValue> Values { get { return Collection<TValue>.Instance; } } public TValue this[TKey key] { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class Empty { internal class Dictionary<TKey, TValue> #nullable disable // Note: if the interfaces we implement weren't oblivious, then we'd warn about the `[MaybeNullWhen(false)] out TValue value` parameter below // We can remove this once `IDictionary` is annotated with `[MaybeNullWhen(false)]` : Collection<KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue> #nullable enable where TKey : notnull { public static new readonly Dictionary<TKey, TValue> Instance = new(); private Dictionary() { } public void Add(TKey key, TValue value) { throw new NotSupportedException(); } public bool ContainsKey(TKey key) { return false; } public ICollection<TKey> Keys { get { return Collection<TKey>.Instance; } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Keys; IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Values; public bool Remove(TKey key) { throw new NotSupportedException(); } public bool TryGetValue(TKey key, [MaybeNullWhen(returnValue: false)] out TValue value) { value = default!; return false; } public ICollection<TValue> Values { get { return Collection<TValue>.Instance; } } public TValue this[TKey key] { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Implementation/EndConstructGeneration/IEndConstructGenerationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Host; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Implementation.EndConstructGeneration { internal interface IEndConstructGenerationService : ILanguageService { bool TryDo(ITextView textView, ITextBuffer subjectBuffer, char typedChar, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Implementation.EndConstructGeneration { internal interface IEndConstructGenerationService : ILanguageService { bool TryDo(ITextView textView, ITextBuffer subjectBuffer, char typedChar, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/RQName/Nodes/RQMethodBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal abstract class RQMethodBase : RQMethodOrProperty { public RQMethodBase( RQUnconstructedType containingType, RQMethodPropertyOrEventName memberName, int typeParameterCount, IList<RQParameter> parameters) : base(containingType, memberName, typeParameterCount, parameters) { } protected override string RQKeyword { get { return RQNameStrings.Meth; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal abstract class RQMethodBase : RQMethodOrProperty { public RQMethodBase( RQUnconstructedType containingType, RQMethodPropertyOrEventName memberName, int typeParameterCount, IList<RQParameter> parameters) : base(containingType, memberName, typeParameterCount, parameters) { } protected override string RQKeyword { get { return RQNameStrings.Meth; } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest2/Recommendations/ElseKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ElseKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(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 TestNotInPreprocessor1() { await VerifyAbsenceAsync( @"class C { #if $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPreprocessorFollowedBySkippedTokens() { await VerifyKeywordAsync( @"#if GOO #$$ dasd "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIf() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$ else")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfStatementElse(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} else $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseNestedIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterWhileIfWhileNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfElseIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$ else")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine()$$; // Complete statement, but we're not at the end of it. ")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSkippedToken() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine();, $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ElseKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(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 TestNotInPreprocessor1() { await VerifyAbsenceAsync( @"class C { #if $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPreprocessorFollowedBySkippedTokens() { await VerifyKeywordAsync( @"#if GOO #$$ dasd "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIf() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$ else")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfStatementElse(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} else $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseNestedIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterWhileIfWhileNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfElseIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$ else")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine()$$; // Complete statement, but we're not at the end of it. ")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSkippedToken() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine();, $$")); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Symbol/Symbols/StaticAbstractMembersInInterfacesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class StaticAbstractMembersInInterfacesTests : CSharpTestBase { [Fact] public void MethodModifiers_01() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } private static void ValidateMethodModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<MethodSymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<MethodSymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<MethodSymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<MethodSymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<MethodSymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<MethodSymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<MethodSymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<MethodSymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<MethodSymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } [Fact] public void MethodModifiers_02() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_03() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_04() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_05() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static void M02() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static void M04() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static void M09() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_06() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static void M02() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static void M04() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static void M09() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void SealedStaticConstructor_01() { var source1 = @" interface I1 { sealed static I1() {} } partial interface I2 { partial sealed static I2(); } partial interface I2 { partial static I2() {} } partial interface I3 { partial static I3(); } partial interface I3 { partial sealed static I3() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,19): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I1").WithArguments("sealed").WithLocation(4, 19), // (9,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I2(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(9, 5), // (9,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I2(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(9, 5), // (9,27): error CS0106: The modifier 'sealed' is not valid for this item // partial sealed static I2(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(9, 27), // (14,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I2() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(14, 5), // (14,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I2() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(14, 5), // (14,20): error CS0111: Type 'I2' already defines a member called 'I2' with the same parameter types // partial static I2() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I2").WithArguments("I2", "I2").WithLocation(14, 20), // (19,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I3(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(19, 5), // (19,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I3(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(19, 5), // (24,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(24, 5), // (24,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(24, 5), // (24,27): error CS0106: The modifier 'sealed' is not valid for this item // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(24, 27), // (24,27): error CS0111: Type 'I3' already defines a member called 'I3' with the same parameter types // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I3").WithArguments("I3", "I3").WithLocation(24, 27) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); } [Fact] public void SealedStaticConstructor_02() { var source1 = @" partial interface I2 { sealed static partial I2(); } partial interface I2 { static partial I2() {} } partial interface I3 { static partial I3(); } partial interface I3 { sealed static partial I3() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,19): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // sealed static partial I2(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(4, 19), // (4,27): error CS0501: 'I2.I2()' must declare a body because it is not marked abstract, extern, or partial // sealed static partial I2(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I2").WithArguments("I2.I2()").WithLocation(4, 27), // (4,27): error CS0542: 'I2': member names cannot be the same as their enclosing type // sealed static partial I2(); Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I2").WithArguments("I2").WithLocation(4, 27), // (9,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I2() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(9, 12), // (9,20): error CS0542: 'I2': member names cannot be the same as their enclosing type // static partial I2() {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I2").WithArguments("I2").WithLocation(9, 20), // (9,20): error CS0111: Type 'I2' already defines a member called 'I2' with the same parameter types // static partial I2() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I2").WithArguments("I2", "I2").WithLocation(9, 20), // (9,20): error CS0161: 'I2.I2()': not all code paths return a value // static partial I2() {} Diagnostic(ErrorCode.ERR_ReturnExpected, "I2").WithArguments("I2.I2()").WithLocation(9, 20), // (14,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I3(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(14, 12), // (14,20): error CS0501: 'I3.I3()' must declare a body because it is not marked abstract, extern, or partial // static partial I3(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I3").WithArguments("I3.I3()").WithLocation(14, 20), // (14,20): error CS0542: 'I3': member names cannot be the same as their enclosing type // static partial I3(); Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I3").WithArguments("I3").WithLocation(14, 20), // (19,19): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(19, 19), // (19,27): error CS0542: 'I3': member names cannot be the same as their enclosing type // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I3").WithArguments("I3").WithLocation(19, 27), // (19,27): error CS0111: Type 'I3' already defines a member called 'I3' with the same parameter types // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I3").WithArguments("I3", "I3").WithLocation(19, 27), // (19,27): error CS0161: 'I3.I3()': not all code paths return a value // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_ReturnExpected, "I3").WithArguments("I3.I3()").WithLocation(19, 27) ); } [Fact] public void AbstractStaticConstructor_01() { var source1 = @" interface I1 { abstract static I1(); } interface I2 { abstract static I2() {} } interface I3 { static I3(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I1").WithArguments("abstract").WithLocation(4, 21), // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I2() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("abstract").WithLocation(9, 21), // (14,12): error CS0501: 'I3.I3()' must declare a body because it is not marked abstract, extern, or partial // static I3(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I3").WithArguments("I3.I3()").WithLocation(14, 12) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); } [Fact] public void PartialSealedStatic_01() { var source1 = @" partial interface I1 { sealed static partial void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Null(m01.PartialImplementationPart); } [Fact] public void PartialSealedStatic_02() { var source1 = @" partial interface I1 { sealed static partial void M01(); } partial interface I1 { sealed static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ValidatePartialSealedStatic_02(compilation1); } private static void ValidatePartialSealedStatic_02(CSharpCompilation compilation1) { compilation1.VerifyDiagnostics(); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialSealedStatic_03() { var source1 = @" partial interface I1 { static partial void M01(); } partial interface I1 { sealed static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ValidatePartialSealedStatic_02(compilation1); } [Fact] public void PartialSealedStatic_04() { var source1 = @" partial interface I1 { sealed static partial void M01(); } partial interface I1 { static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ValidatePartialSealedStatic_02(compilation1); } [Fact] public void PartialAbstractStatic_01() { var source1 = @" partial interface I1 { abstract static partial void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Null(m01.PartialImplementationPart); } [Fact] public void PartialAbstractStatic_02() { var source1 = @" partial interface I1 { abstract static partial void M01(); } partial interface I1 { abstract static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34), // (8,34): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(8, 34), // (8,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(8, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialAbstractStatic_03() { var source1 = @" partial interface I1 { abstract static partial void M01(); } partial interface I1 { static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialAbstractStatic_04() { var source1 = @" partial interface I1 { static partial void M01(); } partial interface I1 { abstract static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,34): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(8, 34), // (8,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(8, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PrivateAbstractStatic_01() { var source1 = @" interface I1 { private abstract static void M01(); private abstract static bool P01 { get; } private abstract static event System.Action E01; private abstract static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0621: 'I1.M01()': virtual or abstract members cannot be private // private abstract static void M01(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "M01").WithArguments("I1.M01()").WithLocation(4, 34), // (5,34): error CS0621: 'I1.P01': virtual or abstract members cannot be private // private abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "P01").WithArguments("I1.P01").WithLocation(5, 34), // (6,49): error CS0621: 'I1.E01': virtual or abstract members cannot be private // private abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_VirtualPrivate, "E01").WithArguments("I1.E01").WithLocation(6, 49), // (7,40): error CS0558: User-defined operator 'I1.operator +(I1)' must be declared static and public // private abstract static I1 operator+ (I1 x); Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 40) ); } [Fact] public void PropertyModifiers_01() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } private static void ValidatePropertyModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); { var m01 = i1.GetMember<PropertySymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<PropertySymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<PropertySymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<PropertySymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<PropertySymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<PropertySymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<PropertySymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<PropertySymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<PropertySymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<PropertySymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } { var m01 = i1.GetMember<PropertySymbol>("M01").GetMethod; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<PropertySymbol>("M02").GetMethod; Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<PropertySymbol>("M03").GetMethod; Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<PropertySymbol>("M04").GetMethod; Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<PropertySymbol>("M05").GetMethod; Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<PropertySymbol>("M06").GetMethod; Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<PropertySymbol>("M07").GetMethod; Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<PropertySymbol>("M08").GetMethod; Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<PropertySymbol>("M09").GetMethod; Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<PropertySymbol>("M10").GetMethod; Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } } [Fact] public void PropertyModifiers_02() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_03() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_04() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_05() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static bool M04 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_06() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static bool M04 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void EventModifiers_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event D M01 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 29), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static event D M03 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static event D M07 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static event D M10 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } private static void ValidateEventModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); { var m01 = i1.GetMember<EventSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<EventSymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<EventSymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<EventSymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<EventSymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<EventSymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<EventSymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<EventSymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<EventSymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<EventSymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } foreach (var addAccessor in new[] { true, false }) { var m01 = getAccessor(i1.GetMember<EventSymbol>("M01"), addAccessor); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = getAccessor(i1.GetMember<EventSymbol>("M02"), addAccessor); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = getAccessor(i1.GetMember<EventSymbol>("M03"), addAccessor); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = getAccessor(i1.GetMember<EventSymbol>("M04"), addAccessor); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = getAccessor(i1.GetMember<EventSymbol>("M05"), addAccessor); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = getAccessor(i1.GetMember<EventSymbol>("M06"), addAccessor); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = getAccessor(i1.GetMember<EventSymbol>("M07"), addAccessor); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = getAccessor(i1.GetMember<EventSymbol>("M08"), addAccessor); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = getAccessor(i1.GetMember<EventSymbol>("M09"), addAccessor); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = getAccessor(i1.GetMember<EventSymbol>("M10"), addAccessor); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } static MethodSymbol getAccessor(EventSymbol e, bool addAccessor) { return addAccessor ? e.AddMethod : e.RemoveMethod; } } [Fact] public void EventModifiers_02() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 29), // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static event D M03 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_03() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_04() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_05() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static event D M01 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 29), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (7,28): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static event D M02 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static event D M03 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (13,29): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static event D M04 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static event D M07 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (28,37): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static event D M09 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static event D M10 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_06() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 29), // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (7,28): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static event D M03 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (13,29): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (28,37): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void OperatorModifiers_01() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "9.0", "preview").WithLocation(10, 30), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "9.0", "preview").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "9.0", "preview").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "9.0", "preview").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "9.0", "preview").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } private static void ValidateOperatorModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("op_UnaryPlus"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<MethodSymbol>("op_UnaryNegation"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<MethodSymbol>("op_Increment"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<MethodSymbol>("op_Decrement"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<MethodSymbol>("op_LogicalNot"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<MethodSymbol>("op_OnesComplement"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<MethodSymbol>("op_Addition"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<MethodSymbol>("op_Subtraction"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<MethodSymbol>("op_Multiply"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<MethodSymbol>("op_Division"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } [Fact] public void OperatorModifiers_02() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(4, 32), // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "9.0", "preview").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "9.0", "preview").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "9.0", "preview").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "9.0", "preview").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "9.0", "preview").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_03() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_04() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_05() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "7.3", "preview").WithLocation(10, 30), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "--").WithArguments("default interface implementation", "8.0").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "7.3", "preview").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "7.3", "preview").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "7.3", "preview").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "*").WithArguments("default interface implementation", "8.0").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "7.3", "preview").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_06() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(4, 32), // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "7.3", "preview").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "--").WithArguments("default interface implementation", "8.0").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "7.3", "preview").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "7.3", "preview").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "7.3", "preview").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "*").WithArguments("default interface implementation", "8.0").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "7.3", "preview").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_07() { var source1 = @" public interface I1 { abstract static bool operator== (I1 x, I1 y); abstract static bool operator!= (I1 x, I1 y) {return false;} } public interface I2 { sealed static bool operator== (I2 x, I2 y); sealed static bool operator!= (I2 x, I2 y) {return false;} } public interface I3 { abstract sealed static bool operator== (I3 x, I3 y); abstract sealed static bool operator!= (I3 x, I3 y) {return false;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool operator== (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "7.3", "preview").WithLocation(4, 34), // (6,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "7.3", "preview").WithLocation(6, 34), // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (18,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "7.3", "preview").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "7.3", "preview").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator== (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(4, 34), // (6,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(6, 34), // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (18,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); void validate() { foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I1").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I2").GetMembers()) { Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I3").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } } } [Fact] public void OperatorModifiers_08() { var source1 = @" public interface I1 { abstract static implicit operator int(I1 x); abstract static explicit operator I1(bool x) {return null;} } public interface I2 { sealed static implicit operator int(I2 x); sealed static explicit operator I2(bool x) {return null;} } public interface I3 { abstract sealed static implicit operator int(I3 x); abstract sealed static explicit operator I3(bool x) {return null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "7.3", "preview").WithLocation(4, 39), // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I1").WithArguments("abstract", "7.3", "preview").WithLocation(6, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "7.3", "preview").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I3").WithArguments("abstract", "7.3", "preview").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(4, 39), // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I1").WithArguments("abstract", "9.0", "preview").WithLocation(6, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I3").WithArguments("abstract", "9.0", "preview").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); void validate() { foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I1").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I2").GetMembers()) { Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I3").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } } } [Fact] public void FieldModifiers_01() { var source1 = @" public interface I1 { abstract static int F1; sealed static int F2; abstract int F3; sealed int F4; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,25): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract static int F1; Diagnostic(ErrorCode.ERR_AbstractField, "F1").WithLocation(4, 25), // (5,23): error CS0106: The modifier 'sealed' is not valid for this item // sealed static int F2; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F2").WithArguments("sealed").WithLocation(5, 23), // (6,18): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract int F3; Diagnostic(ErrorCode.ERR_AbstractField, "F3").WithLocation(6, 18), // (6,18): error CS0525: Interfaces cannot contain instance fields // abstract int F3; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F3").WithLocation(6, 18), // (7,16): error CS0106: The modifier 'sealed' is not valid for this item // sealed int F4; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F4").WithArguments("sealed").WithLocation(7, 16), // (7,16): error CS0525: Interfaces cannot contain instance fields // sealed int F4; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F4").WithLocation(7, 16) ); } [Fact] public void ExternAbstractStatic_01() { var source1 = @" interface I1 { extern abstract static void M01(); extern abstract static bool P01 { get; } extern abstract static event System.Action E01; extern abstract static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0180: 'I1.M01()' cannot be both extern and abstract // extern abstract static void M01(); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M01").WithArguments("I1.M01()").WithLocation(4, 33), // (5,33): error CS0180: 'I1.P01' cannot be both extern and abstract // extern abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P01").WithArguments("I1.P01").WithLocation(5, 33), // (6,48): error CS0180: 'I1.E01' cannot be both extern and abstract // extern abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E01").WithArguments("I1.E01").WithLocation(6, 48), // (7,39): error CS0180: 'I1.operator +(I1)' cannot be both extern and abstract // extern abstract static I1 operator+ (I1 x); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 39) ); } [Fact] public void ExternAbstractStatic_02() { var source1 = @" interface I1 { extern abstract static void M01() {} extern abstract static bool P01 { get => false; } extern abstract static event System.Action E01 { add {} remove {} } extern abstract static I1 operator+ (I1 x) => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0180: 'I1.M01()' cannot be both extern and abstract // extern abstract static void M01() {} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M01").WithArguments("I1.M01()").WithLocation(4, 33), // (5,33): error CS0180: 'I1.P01' cannot be both extern and abstract // extern abstract static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P01").WithArguments("I1.P01").WithLocation(5, 33), // (6,48): error CS0180: 'I1.E01' cannot be both extern and abstract // extern abstract static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E01").WithArguments("I1.E01").WithLocation(6, 48), // (6,52): error CS8712: 'I1.E01': abstract event cannot use event accessor syntax // extern abstract static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.E01").WithLocation(6, 52), // (7,39): error CS0180: 'I1.operator +(I1)' cannot be both extern and abstract // extern abstract static I1 operator+ (I1 x) => null; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 39) ); } [Fact] public void ExternSealedStatic_01() { var source1 = @" #pragma warning disable CS0626 // Method, operator, or accessor is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. interface I1 { extern sealed static void M01(); extern sealed static bool P01 { get; } extern sealed static event System.Action E01; extern sealed static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void AbstractStaticInClass_01() { var source1 = @" abstract class C1 { public abstract static void M01(); public abstract static bool P01 { get; } public abstract static event System.Action E01; public abstract static C1 operator+ (C1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static void M01(); Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M01").WithArguments("abstract").WithLocation(4, 33), // (5,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P01").WithArguments("abstract").WithLocation(5, 33), // (6,48): error CS0112: A static member cannot be marked as 'abstract' // public abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "E01").WithArguments("abstract").WithLocation(6, 48), // (7,39): error CS0106: The modifier 'abstract' is not valid for this item // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("abstract").WithLocation(7, 39), // (7,39): error CS0501: 'C1.operator +(C1)' must declare a body because it is not marked abstract, extern, or partial // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("C1.operator +(C1)").WithLocation(7, 39) ); } [Fact] public void SealedStaticInClass_01() { var source1 = @" class C1 { sealed static void M01() {} sealed static bool P01 { get => false; } sealed static event System.Action E01 { add {} remove {} } public sealed static C1 operator+ (C1 x) => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0238: 'C1.M01()' cannot be sealed because it is not an override // sealed static void M01() {} Diagnostic(ErrorCode.ERR_SealedNonOverride, "M01").WithArguments("C1.M01()").WithLocation(4, 24), // (5,24): error CS0238: 'C1.P01' cannot be sealed because it is not an override // sealed static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_SealedNonOverride, "P01").WithArguments("C1.P01").WithLocation(5, 24), // (6,39): error CS0238: 'C1.E01' cannot be sealed because it is not an override // sealed static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_SealedNonOverride, "E01").WithArguments("C1.E01").WithLocation(6, 39), // (7,37): error CS0106: The modifier 'sealed' is not valid for this item // public sealed static C1 operator+ (C1 x) => null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("sealed").WithLocation(7, 37) ); } [Fact] public void AbstractStaticInStruct_01() { var source1 = @" struct C1 { public abstract static void M01(); public abstract static bool P01 { get; } public abstract static event System.Action E01; public abstract static C1 operator+ (C1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static void M01(); Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M01").WithArguments("abstract").WithLocation(4, 33), // (5,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P01").WithArguments("abstract").WithLocation(5, 33), // (6,48): error CS0112: A static member cannot be marked as 'abstract' // public abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "E01").WithArguments("abstract").WithLocation(6, 48), // (7,39): error CS0106: The modifier 'abstract' is not valid for this item // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("abstract").WithLocation(7, 39), // (7,39): error CS0501: 'C1.operator +(C1)' must declare a body because it is not marked abstract, extern, or partial // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("C1.operator +(C1)").WithLocation(7, 39) ); } [Fact] public void SealedStaticInStruct_01() { var source1 = @" struct C1 { sealed static void M01() {} sealed static bool P01 { get => false; } sealed static event System.Action E01 { add {} remove {} } public sealed static C1 operator+ (C1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0238: 'C1.M01()' cannot be sealed because it is not an override // sealed static void M01() {} Diagnostic(ErrorCode.ERR_SealedNonOverride, "M01").WithArguments("C1.M01()").WithLocation(4, 24), // (5,24): error CS0238: 'C1.P01' cannot be sealed because it is not an override // sealed static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_SealedNonOverride, "P01").WithArguments("C1.P01").WithLocation(5, 24), // (6,39): error CS0238: 'C1.E01' cannot be sealed because it is not an override // sealed static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_SealedNonOverride, "E01").WithArguments("C1.E01").WithLocation(6, 39), // (7,37): error CS0106: The modifier 'sealed' is not valid for this item // public sealed static C1 operator+ (C1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("sealed").WithLocation(7, 37) ); } [Fact] public void DefineAbstractStaticMethod_01() { var source1 = @" interface I1 { abstract static void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); } } [Fact] public void DefineAbstractStaticMethod_02() { var source1 = @" interface I1 { abstract static void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 26) ); } [Theory] [InlineData("I1", "+", "(I1 x)")] [InlineData("I1", "-", "(I1 x)")] [InlineData("I1", "!", "(I1 x)")] [InlineData("I1", "~", "(I1 x)")] [InlineData("I1", "++", "(I1 x)")] [InlineData("I1", "--", "(I1 x)")] [InlineData("I1", "+", "(I1 x, I1 y)")] [InlineData("I1", "-", "(I1 x, I1 y)")] [InlineData("I1", "*", "(I1 x, I1 y)")] [InlineData("I1", "/", "(I1 x, I1 y)")] [InlineData("I1", "%", "(I1 x, I1 y)")] [InlineData("I1", "&", "(I1 x, I1 y)")] [InlineData("I1", "|", "(I1 x, I1 y)")] [InlineData("I1", "^", "(I1 x, I1 y)")] [InlineData("I1", "<<", "(I1 x, int y)")] [InlineData("I1", ">>", "(I1 x, int y)")] public void DefineAbstractStaticOperator_01(string type, string op, string paramList) { var source1 = @" interface I1 { abstract static " + type + " operator " + op + " " + paramList + @"; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); } } [Fact] public void DefineAbstractStaticOperator_02() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); abstract static I1 operator > (I1 x, I1 y); abstract static I1 operator < (I1 x, I1 y); abstract static I1 operator >= (I1 x, I1 y); abstract static I1 operator <= (I1 x, I1 y); abstract static I1 operator == (I1 x, I1 y); abstract static I1 operator != (I1 x, I1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(8, count); } } [Theory] [InlineData("I1", "+", "(I1 x)")] [InlineData("I1", "-", "(I1 x)")] [InlineData("I1", "!", "(I1 x)")] [InlineData("I1", "~", "(I1 x)")] [InlineData("I1", "++", "(I1 x)")] [InlineData("I1", "--", "(I1 x)")] [InlineData("I1", "+", "(I1 x, I1 y)")] [InlineData("I1", "-", "(I1 x, I1 y)")] [InlineData("I1", "*", "(I1 x, I1 y)")] [InlineData("I1", "/", "(I1 x, I1 y)")] [InlineData("I1", "%", "(I1 x, I1 y)")] [InlineData("I1", "&", "(I1 x, I1 y)")] [InlineData("I1", "|", "(I1 x, I1 y)")] [InlineData("I1", "^", "(I1 x, I1 y)")] [InlineData("I1", "<<", "(I1 x, int y)")] [InlineData("I1", ">>", "(I1 x, int y)")] public void DefineAbstractStaticOperator_03(string type, string op, string paramList) { var source1 = @" interface I1 { abstract static " + type + " operator " + op + " " + paramList + @"; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator + (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 31 + type.Length) ); } [Fact] public void DefineAbstractStaticOperator_04() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); abstract static I1 operator > (I1 x, I1 y); abstract static I1 operator < (I1 x, I1 y); abstract static I1 operator >= (I1 x, I1 y); abstract static I1 operator <= (I1 x, I1 y); abstract static I1 operator == (I1 x, I1 y); abstract static I1 operator != (I1 x, I1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(4, 35), // (5,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(5, 35), // (6,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator > (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, ">").WithLocation(6, 33), // (7,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator < (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "<").WithLocation(7, 33), // (8,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator >= (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, ">=").WithLocation(8, 33), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator <= (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "<=").WithLocation(9, 33), // (10,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator == (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "==").WithLocation(10, 33), // (11,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator != (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "!=").WithLocation(11, 33) ); } [Fact] public void DefineAbstractStaticConversion_01() { var source1 = @" interface I1<T> where T : I1<T> { abstract static implicit operator int(T x); abstract static explicit operator T(int x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticConversion_03() { var source1 = @" interface I1<T> where T : I1<T> { abstract static implicit operator int(T x); abstract static explicit operator T(int x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 39), // (5,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator T(int x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T").WithLocation(5, 39) ); } [Fact] public void DefineAbstractStaticProperty_01() { var source1 = @" interface I1 { abstract static int P01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var p01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.True(p01.IsAbstract); Assert.False(p01.IsVirtual); Assert.False(p01.IsSealed); Assert.True(p01.IsStatic); Assert.False(p01.IsOverride); int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticProperty_02() { var source1 = @" interface I1 { abstract static int P01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(4, 31), // (4,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(4, 36) ); } [Fact] public void DefineAbstractStaticEvent_01() { var source1 = @" interface I1 { abstract static event System.Action E01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var e01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.True(e01.IsAbstract); Assert.False(e01.IsVirtual); Assert.False(e01.IsSealed); Assert.True(e01.IsStatic); Assert.False(e01.IsOverride); int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticEvent_02() { var source1 = @" interface I1 { abstract static event System.Action E01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "E01").WithLocation(4, 41) ); } [Fact] public void ConstraintChecks_01() { var source1 = @" public interface I1 { abstract static void M01(); } public interface I2 : I1 { } public interface I3 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var source2 = @" class C1<T1> where T1 : I1 { void Test(C1<I2> x) { } } class C2 { void M<T2>() where T2 : I1 {} void Test(C2 x) { x.M<I2>(); } } class C3<T3> where T3 : I2 { void Test(C3<I2> x, C3<I3> y) { } } class C4 { void M<T4>() where T4 : I2 {} void Test(C4 x) { x.M<I2>(); x.M<I3>(); } } class C5<T5> where T5 : I3 { void Test(C5<I3> y) { } } class C6 { void M<T6>() where T6 : I3 {} void Test(C6 x) { x.M<I3>(); } } class C7<T7> where T7 : I1 { void Test(C7<I1> y) { } } class C8 { void M<T8>() where T8 : I1 {} void Test(C8 x) { x.M<I1>(); } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); var expected = new[] { // (4,22): error CS8920: The interface 'I2' cannot be used as type parameter 'T1' in the generic type or method 'C1<T1>'. The constraint interface 'I1' or its base interface has static abstract members. // void Test(C1<I2> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "x").WithArguments("C1<T1>", "I1", "T1", "I2").WithLocation(4, 22), // (15,11): error CS8920: The interface 'I2' cannot be used as type parameter 'T2' in the generic type or method 'C2.M<T2>()'. The constraint interface 'I1' or its base interface has static abstract members. // x.M<I2>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I2>").WithArguments("C2.M<T2>()", "I1", "T2", "I2").WithLocation(15, 11), // (21,22): error CS8920: The interface 'I2' cannot be used as type parameter 'T3' in the generic type or method 'C3<T3>'. The constraint interface 'I2' or its base interface has static abstract members. // void Test(C3<I2> x, C3<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "x").WithArguments("C3<T3>", "I2", "T3", "I2").WithLocation(21, 22), // (21,32): error CS8920: The interface 'I3' cannot be used as type parameter 'T3' in the generic type or method 'C3<T3>'. The constraint interface 'I2' or its base interface has static abstract members. // void Test(C3<I2> x, C3<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C3<T3>", "I2", "T3", "I3").WithLocation(21, 32), // (32,11): error CS8920: The interface 'I2' cannot be used as type parameter 'T4' in the generic type or method 'C4.M<T4>()'. The constraint interface 'I2' or its base interface has static abstract members. // x.M<I2>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I2>").WithArguments("C4.M<T4>()", "I2", "T4", "I2").WithLocation(32, 11), // (33,11): error CS8920: The interface 'I3' cannot be used as type parameter 'T4' in the generic type or method 'C4.M<T4>()'. The constraint interface 'I2' or its base interface has static abstract members. // x.M<I3>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I3>").WithArguments("C4.M<T4>()", "I2", "T4", "I3").WithLocation(33, 11), // (39,22): error CS8920: The interface 'I3' cannot be used as type parameter 'T5' in the generic type or method 'C5<T5>'. The constraint interface 'I3' or its base interface has static abstract members. // void Test(C5<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C5<T5>", "I3", "T5", "I3").WithLocation(39, 22), // (50,11): error CS8920: The interface 'I3' cannot be used as type parameter 'T6' in the generic type or method 'C6.M<T6>()'. The constraint interface 'I3' or its base interface has static abstract members. // x.M<I3>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I3>").WithArguments("C6.M<T6>()", "I3", "T6", "I3").WithLocation(50, 11), // (56,22): error CS8920: The interface 'I1' cannot be used as type parameter 'T7' in the generic type or method 'C7<T7>'. The constraint interface 'I1' or its base interface has static abstract members. // void Test(C7<I1> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C7<T7>", "I1", "T7", "I1").WithLocation(56, 22), // (67,11): error CS8920: The interface 'I1' cannot be used as type parameter 'T8' in the generic type or method 'C8.M<T8>()'. The constraint interface 'I1' or its base interface has static abstract members. // x.M<I1>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I1>").WithArguments("C8.M<T8>()", "I1", "T8", "I1").WithLocation(67, 11) }; compilation2.VerifyDiagnostics(expected); compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.EmitToImageReference() }); compilation2.VerifyDiagnostics(expected); } [Fact] public void ConstraintChecks_02() { var source1 = @" public interface I1 { abstract static void M01(); } public class C : I1 { public static void M01() {} } public struct S : I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var source2 = @" class C1<T1> where T1 : I1 { void Test(C1<C> x, C1<S> y, C1<T1> z) { } } class C2 { public void M<T2>(C2 x) where T2 : I1 { x.M<T2>(x); } void Test(C2 x) { x.M<C>(x); x.M<S>(x); } } class C3<T3> where T3 : I1 { void Test(C1<T3> z) { } } class C4 { void M<T4>(C2 x) where T4 : I1 { x.M<T4>(x); } } class C5<T5> { internal virtual void M<U5>() where U5 : T5 { } } class C6 : C5<I1> { internal override void M<U6>() { base.M<U6>(); } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyEmitDiagnostics(); compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.EmitToImageReference() }); compilation2.VerifyEmitDiagnostics(); } [Fact] public void VarianceSafety_01() { var source1 = @" interface I2<out T1, in T2> { abstract static T1 P1 { get; } abstract static T2 P2 { get; } abstract static T1 P3 { set; } abstract static T2 P4 { set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,21): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.P2'. 'T2' is contravariant. // abstract static T2 P2 { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I2<T1, T2>.P2", "T2", "contravariant", "covariantly").WithLocation(5, 21), // (6,21): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.P3'. 'T1' is covariant. // abstract static T1 P3 { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I2<T1, T2>.P3", "T1", "covariant", "contravariantly").WithLocation(6, 21) ); } [Fact] public void VarianceSafety_02() { var source1 = @" interface I2<out T1, in T2> { abstract static T1 M1(); abstract static T2 M2(); abstract static void M3(T1 x); abstract static void M4(T2 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,21): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.M2()'. 'T2' is contravariant. // abstract static T2 M2(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I2<T1, T2>.M2()", "T2", "contravariant", "covariantly").WithLocation(5, 21), // (6,29): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.M3(T1)'. 'T1' is covariant. // abstract static void M3(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I2<T1, T2>.M3(T1)", "T1", "covariant", "contravariantly").WithLocation(6, 29) ); } [Fact] public void VarianceSafety_03() { var source1 = @" interface I2<out T1, in T2> { abstract static event System.Action<System.Func<T1>> E1; abstract static event System.Action<System.Func<T2>> E2; abstract static event System.Action<System.Action<T1>> E3; abstract static event System.Action<System.Action<T2>> E4; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,58): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.E2'. 'T2' is contravariant. // abstract static event System.Action<System.Func<T2>> E2; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E2").WithArguments("I2<T1, T2>.E2", "T2", "contravariant", "covariantly").WithLocation(5, 58), // (6,60): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.E3'. 'T1' is covariant. // abstract static event System.Action<System.Action<T1>> E3; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E3").WithArguments("I2<T1, T2>.E3", "T1", "covariant", "contravariantly").WithLocation(6, 60) ); } [Fact] public void VarianceSafety_04() { var source1 = @" interface I2<out T2> { abstract static int operator +(I2<T2> x); } interface I3<out T3> { abstract static int operator +(I3<T3> x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,36): error CS1961: Invalid variance: The type parameter 'T2' must be contravariantly valid on 'I2<T2>.operator +(I2<T2>)'. 'T2' is covariant. // abstract static int operator +(I2<T2> x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "I2<T2>").WithArguments("I2<T2>.operator +(I2<T2>)", "T2", "covariant", "contravariantly").WithLocation(4, 36), // (9,36): error CS1961: Invalid variance: The type parameter 'T3' must be contravariantly valid on 'I3<T3>.operator +(I3<T3>)'. 'T3' is covariant. // abstract static int operator +(I3<T3> x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "I3<T3>").WithArguments("I3<T3>.operator +(I3<T3>)", "T3", "covariant", "contravariantly").WithLocation(9, 36) ); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("!")] [InlineData("~")] [InlineData("true")] [InlineData("false")] public void OperatorSignature_01(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x); } interface I13 { static abstract bool operator " + op + @"(I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,26): error CS0562: The parameter of a unary operator must be the containing type // static bool operator +(T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0562: The parameter of a unary operator must be the containing type // static bool operator +(T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T5 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T71 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T8 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T10 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator false(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11)").WithLocation(47, 18), // (51,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator false(int x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [InlineData("++")] [InlineData("--")] public void OperatorSignature_02(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static T1 operator " + op + @"(T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static T2? operator " + op + @"(T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract T3 operator " + op + @"(T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract T4? operator " + op + @"(T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract T5 operator " + op + @"(T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract T71 operator " + op + @"(T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract T8 operator " + op + @"(T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract T10 operator " + op + @"(T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract int operator " + op + @"(int x); } interface I13 { static abstract I13 operator " + op + @"(I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0559: The parameter type for ++ or -- operator must be the containing type // static T1 operator ++(T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, op).WithLocation(4, 24), // (9,25): error CS0559: The parameter type for ++ or -- operator must be the containing type // static T2? operator ++(T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, op).WithLocation(9, 25), // (26,37): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T5 operator ++(T5 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(26, 37), // (32,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T71 operator ++(T71 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(32, 34), // (37,33): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T8 operator ++(T8 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(37, 33), // (44,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T10 operator ++(T10 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(44, 34), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator --(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11)").WithLocation(47, 18), // (51,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract int operator ++(int x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(51, 34) ); } [Theory] [InlineData("++")] [InlineData("--")] public void OperatorSignature_03(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static T1 operator " + op + @"(I1<T1> x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static T2? operator " + op + @"(I2<T2> x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract T3 operator " + op + @"(I3<T3> x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract T4? operator " + op + @"(I4<T4> x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract T5 operator " + op + @"(I6 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract T71 operator " + op + @"(I7<T71, T72> x); } interface I8<T8> where T8 : I9<T8> { static abstract T8 operator " + op + @"(I8<T8> x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract T10 operator " + op + @"(I10<T10> x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract int operator " + op + @"(I12 x); } interface I13<T13> where T13 : struct, I13<T13> { static abstract T13? operator " + op + @"(T13 x); } interface I14<T14> where T14 : struct, I14<T14> { static abstract T14 operator " + op + @"(T14? x); } interface I15<T151, T152> where T151 : I15<T151, T152> where T152 : I15<T151, T152> { static abstract T151 operator " + op + @"(T152 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // static T1 operator ++(I1<T1> x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecRetType, op).WithLocation(4, 24), // (9,25): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // static T2? operator ++(I2<T2> x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecRetType, op).WithLocation(9, 25), // (19,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T4? operator ++(I4<T4> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(19, 34), // (26,37): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T5 operator ++(I6 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(26, 37), // (32,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T71 operator ++(I7<T71, T72> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(32, 34), // (37,33): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T8 operator ++(I8<T8> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(37, 33), // (44,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T10 operator ++(I10<T10> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(44, 34), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator ++(I10<T11>)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(I10<T11>)").WithLocation(47, 18), // (51,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract int operator ++(I12 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(51, 34), // (56,35): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T13? operator ++(T13 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(56, 35), // (61,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T14 operator ++(T14? x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(61, 34), // (66,35): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T151 operator ++(T152 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(66, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x, bool y) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x, bool y) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x, bool y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x, bool y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x, bool y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x, bool y); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x, bool y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x, bool y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x, bool y); } interface I13 { static abstract bool operator " + op + @"(I13 x, bool y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators)).Verify( // (4,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(T1 x, bool y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(T2? x, bool y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T5 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T71 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T8 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T10 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator /(T11, bool)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11, bool)").WithLocation(47, 18), // (51,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(int x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_05([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(bool y, T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(bool y, T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(bool y, T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(bool y, T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(bool y, T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(bool y, T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(bool y, T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(bool y, T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(bool y, int x); } interface I13 { static abstract bool operator " + op + @"(bool y, I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators)).Verify( // (4,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(bool y, T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(bool y, T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T5 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T71 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T8 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T10 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator <=(bool, T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(bool, T11)").WithLocation(47, 18), // (51,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, int x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [InlineData("<<")] [InlineData(">>")] public void OperatorSignature_06(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x, int y) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x, int y) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x, int y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x, int y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x, int y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x, int y); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x, int y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x, int y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x, int y); } interface I13 { static abstract bool operator " + op + @"(I13 x, int y); } interface I14 { static abstract bool operator " + op + @"(I14 x, bool y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,26): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // static bool operator <<(T1 x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // static bool operator <<(T2? x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T5 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T71 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T8 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T10 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator >>(T11, int)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11, int)").WithLocation(47, 18), // (51,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(int x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(51, 35), // (61,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(I14 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(61, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_07([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { abstract static " + op + @" operator T1(T1 y); } interface I2<T2> where T2 : I2<T2> { abstract static " + op + @" operator dynamic(T2 y); } interface I3<T3> where T3 : I3<T3> { static abstract " + op + @" operator T3(bool y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract " + op + @" operator T4?(bool y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract " + op + @" operator T5 (bool y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract " + op + @" operator T71 (bool y); } interface I8<T8> where T8 : I9<T8> { static abstract " + op + @" operator T8(bool y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract " + op + @" operator T10(bool y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract " + op + @" operator int(bool y); } interface I13 { static abstract " + op + @" operator I13(bool y); } interface I14<T14> where T14 : I14<T14> { abstract static " + op + @" operator object(T14 y); } class C15 {} class C16 : C15 {} interface I17<T17> where T17 : C15, I17<T17> { abstract static " + op + @" operator C16(T17 y); } interface I18<T18> where T18 : C16, I18<T18> { abstract static " + op + @" operator C15(T18 y); } interface I19<T19_1, T19_2> where T19_1 : I19<T19_1, T19_2>, T19_2 { abstract static " + op + @" operator T19_1(T19_2 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0555: User-defined operator cannot convert a type to itself // abstract static explicit operator T1(T1 y); Diagnostic(ErrorCode.ERR_IdentityConversion, "T1").WithLocation(4, 39), // (9,39): error CS1964: 'I2<T2>.explicit operator dynamic(T2)': user-defined conversions to or from the dynamic type are not allowed // abstract static explicit operator dynamic(T2 y); Diagnostic(ErrorCode.ERR_BadDynamicConversion, "dynamic").WithArguments("I2<T2>." + op + " operator dynamic(T2)").WithLocation(9, 39), // (26,43): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T5 (bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T5").WithLocation(26, 43), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T71 (bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T71").WithLocation(32, 39), // (37,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T8(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T8").WithLocation(37, 39), // (44,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T10(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T10").WithLocation(44, 39), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.explicit operator T11(bool)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>." + op + " operator T11(bool)").WithLocation(47, 18), // (51,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator int(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "int").WithLocation(51, 39), // (56,39): error CS0552: 'I13.explicit operator I13(bool)': user-defined conversions to or from an interface are not allowed // static abstract explicit operator I13(bool y); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I13").WithArguments("I13." + op + " operator I13(bool)").WithLocation(56, 39) ); } [Theory] [CombinatorialData] public void OperatorSignature_08([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { abstract static " + op + @" operator T1(T1 y); } interface I2<T2> where T2 : I2<T2> { abstract static " + op + @" operator T2(dynamic y); } interface I3<T3> where T3 : I3<T3> { static abstract " + op + @" operator bool(T3 y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract " + op + @" operator bool(T4? y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract " + op + @" operator bool(T5 y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract " + op + @" operator bool(T71 y); } interface I8<T8> where T8 : I9<T8> { static abstract " + op + @" operator bool(T8 y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract " + op + @" operator bool(T10 y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract " + op + @" operator bool(int y); } interface I13 { static abstract " + op + @" operator bool(I13 y); } interface I14<T14> where T14 : I14<T14> { abstract static " + op + @" operator T14(object y); } class C15 {} class C16 : C15 {} interface I17<T17> where T17 : C15, I17<T17> { abstract static " + op + @" operator T17(C16 y); } interface I18<T18> where T18 : C16, I18<T18> { abstract static " + op + @" operator T18(C15 y); } interface I19<T19_1, T19_2> where T19_1 : I19<T19_1, T19_2>, T19_2 { abstract static " + op + @" operator T19_2(T19_1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0555: User-defined operator cannot convert a type to itself // abstract static explicit operator T1(T1 y); Diagnostic(ErrorCode.ERR_IdentityConversion, "T1").WithLocation(4, 39), // (9,39): error CS1964: 'I2<T2>.explicit operator T2(dynamic)': user-defined conversions to or from the dynamic type are not allowed // abstract static explicit operator T2(dynamic y); Diagnostic(ErrorCode.ERR_BadDynamicConversion, "T2").WithArguments("I2<T2>." + op + " operator T2(dynamic)").WithLocation(9, 39), // (26,43): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T5 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(26, 43), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T71 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(32, 39), // (37,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T8 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(37, 39), // (44,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T10 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(44, 39), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.explicit operator bool(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>." + op + " operator bool(T11)").WithLocation(47, 18), // (51,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(int y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(51, 39), // (56,39): error CS0552: 'I13.explicit operator bool(I13)': user-defined conversions to or from an interface are not allowed // static abstract explicit operator bool(I13 y); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "bool").WithArguments("I13." + op + " operator bool(I13)").WithLocation(56, 39) ); } [Fact] public void ConsumeAbstractStaticMethod_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { M01(); M04(); } void M03() { this.M01(); this.M04(); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { I1.M01(); x.M01(); I1.M04(); x.M04(); } static void MT2<T>() where T : I1 { T.M03(); T.M04(); T.M00(); T.M05(); _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.M01()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // M01(); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "M01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // this.M01(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // this.M04(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.M01(); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.M01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // x.M01(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // x.M04(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M03(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M04(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M00(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.M05()' is inaccessible due to its protection level // T.M05(); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 11), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.M01()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01()").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticMethod_02() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = nameof(M01); _ = nameof(M04); } void M03() { _ = nameof(this.M01); _ = nameof(this.M04); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = nameof(I1.M01); _ = nameof(x.M01); _ = nameof(I1.M04); _ = nameof(x.M04); } static void MT2<T>() where T : I1 { _ = nameof(T.M03); _ = nameof(T.M04); _ = nameof(T.M00); _ = nameof(T.M05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = nameof(T.M05); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticMethod_03() { var source1 = @" public interface I1 { abstract static void M01(); abstract static void M04(int x); } class Test { static void M02<T, U>() where T : U where U : I1 { T.M01(); } static string M03<T, U>() where T : U where U : I1 { return nameof(T.M01); } static async void M05<T, U>() where T : U where U : I1 { T.M04(await System.Threading.Tasks.Task.FromResult(1)); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 14 (0xe) .maxstack 0 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""void I1.M01()"" IL_000c: nop IL_000d: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""M01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 12 (0xc) .maxstack 0 IL_0000: constrained. ""T"" IL_0006: call ""void I1.M01()"" IL_000b: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""M01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("T.M01()", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IInvocationOperation (virtual void I1.M01()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'T.M01()') Instance Receiver: null Arguments(0) "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("void I1.M01()", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("M01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticMethod_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.M01(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.M01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_05() { var source1 = @" public interface I1 { abstract static I1 Select(System.Func<int, int> p); } class Test { static void M02<T>() where T : I1 { _ = from t in T select t + 1; _ = from t in I1 select t + 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); // https://github.com/dotnet/roslyn/issues/53796: Confirm whether we want to enable the 'from t in T' scenario. compilation1.VerifyDiagnostics( // (11,23): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = from t in T select t + 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(11, 23), // (12,26): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = from t in I1 select t + 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "select t + 1").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.M01(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.M01(); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.M01(); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_01(string prefixOp, string postfixOp) { var source1 = @" interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); abstract static I1<T> operator" + prefixOp + postfixOp + @" (I1<T> x); static void M02(I1<T> x) { _ = " + prefixOp + "x" + postfixOp + @"; } void M03(I1<T> y) { _ = " + prefixOp + "y" + postfixOp + @"; } } class Test<T> where T : I1<T> { static void MT1(I1<T> a) { _ = " + prefixOp + "a" + postfixOp + @"; } static void MT2() { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (" + prefixOp + "b" + postfixOp + @").ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "x" + postfixOp).WithLocation(8, 13), // (13,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "y" + postfixOp).WithLocation(13, 13), // (21,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "a" + postfixOp).WithLocation(21, 13), (prefixOp + postfixOp).Length == 1 ? // (26,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (-b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, prefixOp + "b" + postfixOp).WithLocation(26, 78) : // (26,78): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b--).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, prefixOp + "b" + postfixOp).WithLocation(26, 78) ); } [Theory] [InlineData("+", "", "op_UnaryPlus", "Plus")] [InlineData("-", "", "op_UnaryNegation", "Minus")] [InlineData("!", "", "op_LogicalNot", "Not")] [InlineData("~", "", "op_OnesComplement", "BitwiseNegation")] [InlineData("++", "", "op_Increment", "Increment")] [InlineData("--", "", "op_Decrement", "Decrement")] [InlineData("", "++", "op_Increment", "Increment")] [InlineData("", "--", "op_Decrement", "Decrement")] public void ConsumeAbstractUnaryOperator_03(string prefixOp, string postfixOp, string metadataName, string opKind) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } class Test { static T M02<T, U>(T x) where T : U where U : I1<T> { return " + prefixOp + "x" + postfixOp + @"; } static T? M03<T, U>(T? y) where T : struct, U where U : I1<T> { return " + prefixOp + "y" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 21 (0x15) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: dup IL_000e: starg.s V_0 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: dup IL_002f: starg.s V_0 IL_0031: stloc.2 IL_0032: br.s IL_0034 IL_0034: ldloc.2 IL_0035: ret } "); break; case ("", "++"): case ("", "--"): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 21 (0x15) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: dup IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T)"" IL_000e: starg.s V_0 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: dup IL_0003: stloc.0 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: brtrue.s IL_0018 IL_000d: ldloca.s V_1 IL_000f: initobj ""T?"" IL_0015: ldloc.1 IL_0016: br.s IL_002f IL_0018: ldloca.s V_0 IL_001a: call ""readonly T T?.GetValueOrDefault()"" IL_001f: constrained. ""T"" IL_0025: call ""T I1<T>." + metadataName + @"(T)"" IL_002a: newobj ""T?..ctor(T)"" IL_002f: starg.s V_0 IL_0031: stloc.2 IL_0032: br.s IL_0034 IL_0034: ldloc.2 IL_0035: ret } "); break; default: verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); break; } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(T)"" IL_000c: dup IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0016 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: br.s IL_002d IL_0016: ldloca.s V_0 IL_0018: call ""readonly T T?.GetValueOrDefault()"" IL_001d: constrained. ""T"" IL_0023: call ""T I1<T>." + metadataName + @"(T)"" IL_0028: newobj ""T?..ctor(T)"" IL_002d: dup IL_002e: starg.s V_0 IL_0030: ret } "); break; case ("", "++"): case ("", "--"): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: dup IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: starg.s V_0 IL_0030: ret } "); break; default: verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(T)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""T I1<T>." + metadataName + @"(T)"" IL_0027: newobj ""T?..ctor(T)"" IL_002c: ret } "); break; } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = postfixOp != "" ? (ExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().First() : tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().First(); Assert.Equal(prefixOp + "x" + postfixOp, node.ToString()); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): case ("", "++"): case ("", "--"): VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IIncrementOrDecrementOperation (" + (prefixOp != "" ? "Prefix" : "Postfix") + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x)) (OperationKind." + opKind + @", Type: T) (Syntax: '" + prefixOp + "x" + postfixOp + @"') Target: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); break; default: VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IUnaryOperation (UnaryOperatorKind." + opKind + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x)) (OperationKind.Unary, Type: T) (Syntax: '" + prefixOp + "x" + postfixOp + @"') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); break; } } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_04(string prefixOp, string postfixOp) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1<T> { _ = " + prefixOp + "x" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = -x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, prefixOp + "x" + postfixOp).WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator- (T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, prefixOp + postfixOp).WithLocation(12, 31) ); } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_06(string prefixOp, string postfixOp) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1<T> { _ = " + prefixOp + "x" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = -x; Diagnostic(ErrorCode.ERR_FeatureInPreview, prefixOp + "x" + postfixOp).WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,31): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator- (T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, prefixOp + postfixOp).WithArguments("abstract", "9.0", "preview").WithLocation(12, 31) ); } [Fact] public void ConsumeAbstractTrueOperator_01() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); static void M02(I1 x) { _ = x ? true : false; } void M03(I1 y) { _ = y ? true : false; } } class Test { static void MT1(I1 a) { _ = a ? true : false; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b ? true : false).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x").WithLocation(9, 13), // (14,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y").WithLocation(14, 13), // (22,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a").WithLocation(22, 13), // (27,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b ? true : false).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b").WithLocation(27, 78) ); } [Fact] public void ConsumeAbstractTrueOperator_03() { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator true (T x); abstract static bool operator false (T x); } class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>.op_True(T)"" IL_000d: brtrue.s IL_0011 IL_000f: br.s IL_0011 IL_0011: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""bool I1<T>.op_True(T)"" IL_000c: pop IL_000d: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalExpressionSyntax>().First(); Assert.Equal("x ? true : false", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IConditionalOperation (OperationKind.Conditional, Type: System.Boolean) (Syntax: 'x ? true : false') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean I1<T>.op_True(T x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') WhenTrue: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') WhenFalse: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') "); } [Fact] public void ConsumeAbstractTrueOperator_04() { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1 { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(12, 35), // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(13, 35) ); } [Fact] public void ConsumeAbstractTrueOperator_06() { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1 { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(12, 35), // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); static void M02((int, C<I1>) x) { _ = x " + op + @" x; } void M03((int, C<I1>) y) { _ = y " + op + @" y; } } class Test { static void MT1((int, C<I1>) a) { _ = a " + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b " + op + @" b).ToString()); } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x == x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " x").WithLocation(9, 13), // (14,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y == y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " y").WithLocation(14, 13), // (22,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a == a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " a").WithLocation(22, 13), // (27,98): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(27, 98) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator true (T x); abstract static bool operator false (T x); } class Test { static void M02<T, U>((int, C<T>) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 55 (0x37) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0034 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_False(T)"" IL_002f: ldc.i4.0 IL_0030: ceq IL_0032: br.s IL_0035 IL_0034: ldc.i4.0 IL_0035: pop IL_0036: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_True(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.1 IL_0032: pop IL_0033: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0033 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_False(T)"" IL_002e: ldc.i4.0 IL_002f: ceq IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: pop IL_0035: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_True(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.1 IL_0031: pop IL_0032: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1 { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (21,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(21, 35), // (22,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(22, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1 { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (21,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(21, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" partial interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); static void M02(I1 x) { _ = x " + op + @" 1; } void M03(I1 y) { _ = y " + op + @" 2; } } class Test { static void MT1(I1 a) { _ = a " + op + @" 3; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + @" 4).ToString()); } } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator" + matchingOp + @" (I1 x, int y); } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x - 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " 1").WithLocation(8, 13), // (13,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y - 2; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " 2").WithLocation(13, 13), // (21,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a - 3; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " 3").WithLocation(21, 13), // (26,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b - 4).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b " + op + " 4").WithLocation(26, 78) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_01(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" static void M02(I1 x) { _ = x " + op + op + @" x; } void M03(I1 y) { _ = y " + op + op + @" y; } } class Test { static void MT1(I1 a) { _ = a " + op + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + op + @" b).ToString()); } static void MT3(I1 b, dynamic c) { _ = b " + op + op + @" c; } "; if (!success) { source1 += @" static void MT4<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T, dynamic>>)((T d, dynamic e) => (d " + op + op + @" e).ToString()); } "; } source1 += @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); if (success) { Assert.False(binaryIsAbstract); Assert.False(op == "&" ? falseIsAbstract : trueIsAbstract); var binaryMetadataName = op == "&" ? "op_BitwiseAnd" : "op_BitwiseOr"; var unaryMetadataName = op == "&" ? "op_False" : "op_True"; var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.MT1(I1)", @" { // Code size 22 (0x16) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0009: brtrue.s IL_0015 IL_000b: ldloc.0 IL_000c: ldarg.0 IL_000d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0012: pop IL_0013: br.s IL_0015 IL_0015: ret } "); if (op == "&") { verifier.VerifyIL("Test.MT3(I1, dynamic)", @" { // Code size 97 (0x61) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""bool I1.op_False(I1)"" IL_0007: brtrue.s IL_0060 IL_0009: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_000e: brfalse.s IL_0012 IL_0010: br.s IL_0047 IL_0012: ldc.i4.8 IL_0013: ldc.i4.2 IL_0014: ldtoken ""Test"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.2 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.1 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: dup IL_002f: ldc.i4.1 IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0037: stelem.ref IL_0038: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0042: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_004c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Target"" IL_0051: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0056: ldarg.0 IL_0057: ldarg.1 IL_0058: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, I1, dynamic)"" IL_005d: pop IL_005e: br.s IL_0060 IL_0060: ret } "); } else { verifier.VerifyIL("Test.MT3(I1, dynamic)", @" { // Code size 98 (0x62) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""bool I1.op_True(I1)"" IL_0007: brtrue.s IL_0061 IL_0009: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_000e: brfalse.s IL_0012 IL_0010: br.s IL_0048 IL_0012: ldc.i4.8 IL_0013: ldc.i4.s 36 IL_0015: ldtoken ""Test"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: ldc.i4.2 IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0025: dup IL_0026: ldc.i4.0 IL_0027: ldc.i4.1 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: dup IL_0030: ldc.i4.1 IL_0031: ldc.i4.0 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003e: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0043: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_004d: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Target"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0057: ldarg.0 IL_0058: ldarg.1 IL_0059: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, I1, dynamic)"" IL_005e: pop IL_005f: br.s IL_0061 IL_0061: ret } "); } } else { var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); builder.AddRange( // (10,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x && x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + op + " x").WithLocation(10, 13), // (15,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y && y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + op + " y").WithLocation(15, 13), // (23,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a && a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + op + " a").WithLocation(23, 13), // (28,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b && b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b " + op + op + " b").WithLocation(28, 78) ); if (op == "&" ? falseIsAbstract : trueIsAbstract) { builder.Add( // (33,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = b || c; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "b " + op + op + " c").WithLocation(33, 13) ); } builder.Add( // (38,98): error CS7083: Expression must be implicitly convertible to Boolean or its type 'T' must define operator 'true'. // _ = (System.Linq.Expressions.Expression<System.Action<T, dynamic>>)((T d, dynamic e) => (d || e).ToString()); Diagnostic(ErrorCode.ERR_InvalidDynamicCondition, "d").WithArguments("T", op == "&" ? "false" : "true").WithLocation(38, 98) ); compilation1.VerifyDiagnostics(builder.ToArrayAndFree()); } } [Theory] [CombinatorialData] public void ConsumeAbstractCompoundBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>")] string op) { var source1 = @" interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); static void M02(I1 x) { x " + op + @"= 1; } void M03(I1 y) { y " + op + @"= 2; } } interface I2<T> where T : I2<T> { abstract static T operator" + op + @" (T x, int y); } class Test { static void MT1(I1 a) { a " + op + @"= 3; } static void MT2<T>() where T : I2<T> { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + @"= 4).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x /= 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + "= 1").WithLocation(8, 9), // (13,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // y /= 2; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + "= 2").WithLocation(13, 9), // (26,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // a /= 3; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + "= 3").WithLocation(26, 9), // (31,78): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b /= 4).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "b " + op + "= 4").WithLocation(31, 78) ); } private static string BinaryOperatorKind(string op) { switch (op) { case "+": return "Add"; case "-": return "Subtract"; case "*": return "Multiply"; case "/": return "Divide"; case "%": return "Remainder"; case "<<": return "LeftShift"; case ">>": return "RightShift"; case "&": return "And"; case "|": return "Or"; case "^": return "ExclusiveOr"; case "<": return "LessThan"; case "<=": return "LessThanOrEqual"; case "==": return "Equals"; case "!=": return "NotEquals"; case ">=": return "GreaterThanOrEqual"; case ">": return "GreaterThan"; } throw TestExceptionUtilities.UnexpectedValue(op); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); abstract static bool operator == (I1<T> x, I1<T> y); abstract static bool operator != (I1<T> x, I1<T> y); static void M02((int, I1<T>) x) { _ = x " + op + @" x; } void M03((int, I1<T>) y) { _ = y " + op + @" y; } } class Test { static void MT1<T>((int, I1<T>) a) where T : I1<T> { _ = a " + op + @" a; } static void MT2<T>() where T : I1<T> { _ = (System.Linq.Expressions.Expression<System.Action<(int, T)>>)(((int, T) b) => (b " + op + @" b).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x == x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " x").WithLocation(12, 13), // (17,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y == y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " y").WithLocation(17, 13), // (25,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a == a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " a").WithLocation(25, 13), // (30,92): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, T)>>)(((int, T) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(30, 92) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_03([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>")] string op) { string metadataName = BinaryOperatorName(op); bool isShiftOperator = op is "<<" or ">>"; var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static T0 operator" + op + @" (T0 x, int a); } partial class Test { static void M03<T, U>(T x) where T : U where U : I1<T> { _ = x " + op + @" 1; } static void M05<T, U>(T? y) where T : struct, U where U : I1<T> { _ = y " + op + @" 1; } } "; if (!isShiftOperator) { source1 += @" public partial interface I1<T0> { abstract static T0 operator" + op + @" (int a, T0 x); abstract static T0 operator" + op + @" (I1<T0> x, T0 a); abstract static T0 operator" + op + @" (T0 x, I1<T0> a); } partial class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = 1 " + op + @" x; } static void M04<T, U>(T? y) where T : struct, U where U : I1<T> { _ = 1 " + op + @" y; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { _ = x " + op + @" y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { _ = x " + op + @" y; } } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldarg.0 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(int, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_000e IL_000c: br.s IL_0022 IL_000e: ldc.i4.1 IL_000f: ldloca.s V_0 IL_0011: call ""readonly T T?.GetValueOrDefault()"" IL_0016: constrained. ""T"" IL_001c: call ""T I1<T>." + metadataName + @"(int, T)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: pop IL_000f: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_000e IL_000c: br.s IL_0022 IL_000e: ldloca.s V_0 IL_0010: call ""readonly T T?.GetValueOrDefault()"" IL_0015: ldc.i4.1 IL_0016: constrained. ""T"" IL_001c: call ""T I1<T>." + metadataName + @"(T, int)"" IL_0021: pop IL_0022: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 32 (0x20) .maxstack 2 .locals init (T? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brfalse.s IL_001f IL_000b: ldc.i4.1 IL_000c: ldloca.s V_0 IL_000e: call ""readonly T T?.GetValueOrDefault()"" IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + metadataName + @"(int, T)"" IL_001e: pop IL_001f: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: pop IL_000e: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 32 (0x20) .maxstack 2 .locals init (T? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brfalse.s IL_001f IL_000b: ldloca.s V_0 IL_000d: call ""readonly T T?.GetValueOrDefault()"" IL_0012: ldc.i4.1 IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + metadataName + @"(T, int)"" IL_001e: pop IL_001f: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " 1").Single(); Assert.Equal("x " + op + " 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.Binary, Type: T) (Syntax: 'x " + op + @" 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractComparisonBinaryOperator_03([CombinatorialValues("<", ">", "<=", ">=", "==", "!=")] string op) { string metadataName = BinaryOperatorName(op); var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static bool operator" + op + @" (T0 x, int a); abstract static bool operator" + op + @" (int a, T0 x); abstract static bool operator" + op + @" (I1<T0> x, T0 a); abstract static bool operator" + op + @" (T0 x, I1<T0> a); } partial class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = 1 " + op + @" x; } static void M03<T, U>(T x) where T : U where U : I1<T> { _ = x " + op + @" 1; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { _ = x " + op + @" y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { _ = x " + op + @" y; } } "; string matchingOp = MatchingBinaryOperator(op); source1 += @" public partial interface I1<T0> { abstract static bool operator" + matchingOp + @" (T0 x, int a); abstract static bool operator" + matchingOp + @" (int a, T0 x); abstract static bool operator" + matchingOp + @" (I1<T0> x, T0 a); abstract static bool operator" + matchingOp + @" (T0 x, I1<T0> a); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldarg.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(int, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(T, int)"" IL_000e: pop IL_000f: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(int, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(T, int)"" IL_000d: pop IL_000e: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " 1").Single(); Assert.Equal("x " + op + " 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @") (OperatorMethod: System.Boolean I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x " + op + @" 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractLiftedComparisonBinaryOperator_03([CombinatorialValues("<", ">", "<=", ">=", "==", "!=")] string op) { string metadataName = BinaryOperatorName(op); var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static bool operator" + op + @" (T0 x, T0 a); } partial class Test { static void M04<T, U>(T? x, T? y) where T : struct, U where U : I1<T> { _ = x " + op + @" y; } } "; string matchingOp = MatchingBinaryOperator(op); source1 += @" public partial interface I1<T0> { abstract static bool operator" + matchingOp + @" (T0 x, T0 a); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op is "==" or "!=") { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 61 (0x3d) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool T?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: beq.s IL_0017 IL_0015: br.s IL_003c IL_0017: ldloca.s V_0 IL_0019: call ""readonly bool T?.HasValue.get"" IL_001e: brtrue.s IL_0022 IL_0020: br.s IL_003c IL_0022: ldloca.s V_0 IL_0024: call ""readonly T T?.GetValueOrDefault()"" IL_0029: ldloca.s V_1 IL_002b: call ""readonly T T?.GetValueOrDefault()"" IL_0030: constrained. ""T"" IL_0036: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_003b: pop IL_003c: ret } "); } else { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool T?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: and IL_0014: brtrue.s IL_0018 IL_0016: br.s IL_0032 IL_0018: ldloca.s V_0 IL_001a: call ""readonly T T?.GetValueOrDefault()"" IL_001f: ldloca.s V_1 IL_0021: call ""readonly T T?.GetValueOrDefault()"" IL_0026: constrained. ""T"" IL_002c: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_0031: pop IL_0032: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op is "==" or "!=") { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 56 (0x38) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: bne.un.s IL_0037 IL_0014: ldloca.s V_0 IL_0016: call ""readonly bool T?.HasValue.get"" IL_001b: brfalse.s IL_0037 IL_001d: ldloca.s V_0 IL_001f: call ""readonly T T?.GetValueOrDefault()"" IL_0024: ldloca.s V_1 IL_0026: call ""readonly T T?.GetValueOrDefault()"" IL_002b: constrained. ""T"" IL_0031: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_0036: pop IL_0037: ret } "); } else { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 48 (0x30) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: and IL_0013: brfalse.s IL_002f IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: ldloca.s V_1 IL_001e: call ""readonly T T?.GetValueOrDefault()"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_002e: pop IL_002f: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " y").Single(); Assert.Equal("x " + op + " y", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @", IsLifted) (OperatorMethod: System.Boolean I1<T>." + metadataName + @"(T x, T a)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x " + op + @" y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T?) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T?) (Syntax: 'y') "); } [Theory] [InlineData("&", true, true)] [InlineData("|", true, true)] [InlineData("&", true, false)] [InlineData("|", true, false)] [InlineData("&", false, true)] [InlineData("|", false, true)] public void ConsumeAbstractLogicalBinaryOperator_03(string op, bool binaryIsAbstract, bool unaryIsAbstract) { var binaryMetadataName = op == "&" ? "op_BitwiseAnd" : "op_BitwiseOr"; var unaryMetadataName = op == "&" ? "op_False" : "op_True"; var opKind = op == "&" ? "ConditionalAnd" : "ConditionalOr"; if (binaryIsAbstract && unaryIsAbstract) { consumeAbstract(op); } else { consumeMixed(op, binaryIsAbstract, unaryIsAbstract); } void consumeAbstract(string op) { var source1 = @" public interface I1<T0> where T0 : I1<T0> { abstract static T0 operator" + op + @" (T0 a, T0 x); abstract static bool operator true (T0 x); abstract static bool operator false (T0 x); } public interface I2<T0> where T0 : struct, I2<T0> { abstract static T0 operator" + op + @" (T0 a, T0 x); abstract static bool operator true (T0? x); abstract static bool operator false (T0? x); } class Test { static void M03<T, U>(T x, T y) where T : U where U : I1<T> { _ = x " + op + op + @" y; } static void M04<T, U>(T? x, T? y) where T : struct, U where U : I2<T> { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 34 (0x22) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: constrained. ""T"" IL_000a: call ""bool I1<T>." + unaryMetadataName + @"(T)"" IL_000f: brtrue.s IL_0021 IL_0011: ldloc.0 IL_0012: ldarg.1 IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + binaryMetadataName + @"(T, T)"" IL_001e: pop IL_001f: br.s IL_0021 IL_0021: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 69 (0x45) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: constrained. ""T"" IL_000a: call ""bool I2<T>." + unaryMetadataName + @"(T?)"" IL_000f: brtrue.s IL_0044 IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldarg.1 IL_0014: stloc.2 IL_0015: ldloca.s V_1 IL_0017: call ""readonly bool T?.HasValue.get"" IL_001c: ldloca.s V_2 IL_001e: call ""readonly bool T?.HasValue.get"" IL_0023: and IL_0024: brtrue.s IL_0028 IL_0026: br.s IL_0042 IL_0028: ldloca.s V_1 IL_002a: call ""readonly T T?.GetValueOrDefault()"" IL_002f: ldloca.s V_2 IL_0031: call ""readonly T T?.GetValueOrDefault()"" IL_0036: constrained. ""T"" IL_003c: call ""T I2<T>." + binaryMetadataName + @"(T, T)"" IL_0041: pop IL_0042: br.s IL_0044 IL_0044: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + unaryMetadataName + @"(T)"" IL_000e: brtrue.s IL_001e IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: constrained. ""T"" IL_0018: call ""T I1<T>." + binaryMetadataName + @"(T, T)"" IL_001d: pop IL_001e: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 64 (0x40) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I2<T>." + unaryMetadataName + @"(T?)"" IL_000e: brtrue.s IL_003f IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: ldarg.1 IL_0013: stloc.2 IL_0014: ldloca.s V_1 IL_0016: call ""readonly bool T?.HasValue.get"" IL_001b: ldloca.s V_2 IL_001d: call ""readonly bool T?.HasValue.get"" IL_0022: and IL_0023: brfalse.s IL_003f IL_0025: ldloca.s V_1 IL_0027: call ""readonly T T?.GetValueOrDefault()"" IL_002c: ldloca.s V_2 IL_002e: call ""readonly T T?.GetValueOrDefault()"" IL_0033: constrained. ""T"" IL_0039: call ""T I2<T>." + binaryMetadataName + @"(T, T)"" IL_003e: pop IL_003f: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + op + " y").First(); Assert.Equal("x " + op + op + " y", node1.ToString()); VerifyOperationTreeForNode(compilation1, model, node1, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + opKind + @") (OperatorMethod: T I1<T>." + binaryMetadataName + @"(T a, T x)) (OperationKind.Binary, Type: T) (Syntax: 'x " + op + op + @" y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T) (Syntax: 'y') "); } void consumeMixed(string op, bool binaryIsAbstract, bool unaryIsAbstract) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 a, I1 x)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (unaryIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (unaryIsAbstract ? ";" : " => throw null;") + @" " + (unaryIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (unaryIsAbstract ? ";" : " => throw null;") + @" } class Test { static void M03<T, U>(T x, T y) where T : U where U : I1 { _ = x " + op + op + @" y; } static void M04<T, U>(T? x, T? y) where T : struct, U where U : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch (binaryIsAbstract, unaryIsAbstract) { case (true, false): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000e: brtrue.s IL_0025 IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: box ""T"" IL_0017: constrained. ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T?"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000e: brtrue.s IL_0025 IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: box ""T?"" IL_0017: constrained. ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); break; case (false, true): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: constrained. ""T"" IL_000f: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldarg.1 IL_0018: box ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T?"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: constrained. ""T"" IL_000f: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldarg.1 IL_0018: box ""T?"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); break; default: Assert.True(false); break; } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch (binaryIsAbstract, unaryIsAbstract) { case (true, false): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000d: brtrue.s IL_0022 IL_000f: ldloc.0 IL_0010: ldarg.1 IL_0011: box ""T"" IL_0016: constrained. ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000d: brtrue.s IL_0022 IL_000f: ldloc.0 IL_0010: ldarg.1 IL_0011: box ""T?"" IL_0016: constrained. ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); break; case (false, true): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: constrained. ""T"" IL_000e: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0013: brtrue.s IL_0022 IL_0015: ldloc.0 IL_0016: ldarg.1 IL_0017: box ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: constrained. ""T"" IL_000e: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0013: brtrue.s IL_0022 IL_0015: ldloc.0 IL_0016: ldarg.1 IL_0017: box ""T?"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); break; default: Assert.True(false); break; } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + op + " y").First(); Assert.Equal("x " + op + op + " y", node1.ToString()); VerifyOperationTreeForNode(compilation1, model, node1, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + opKind + @") (OperatorMethod: I1 I1." + binaryMetadataName + @"(I1 a, I1 x)) (OperationKind.Binary, Type: I1) (Syntax: 'x " + op + op + @" y') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: I1, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: I1, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T) (Syntax: 'y') "); } } [Theory] [InlineData("+", "op_Addition", "Add")] [InlineData("-", "op_Subtraction", "Subtract")] [InlineData("*", "op_Multiply", "Multiply")] [InlineData("/", "op_Division", "Divide")] [InlineData("%", "op_Modulus", "Remainder")] [InlineData("&", "op_BitwiseAnd", "And")] [InlineData("|", "op_BitwiseOr", "Or")] [InlineData("^", "op_ExclusiveOr", "ExclusiveOr")] [InlineData("<<", "op_LeftShift", "LeftShift")] [InlineData(">>", "op_RightShift", "RightShift")] public void ConsumeAbstractCompoundBinaryOperator_03(string op, string metadataName, string operatorKind) { bool isShiftOperator = op.Length == 2; var source1 = @" public interface I1<T0> where T0 : I1<T0> { "; if (!isShiftOperator) { source1 += @" abstract static int operator" + op + @" (int a, T0 x); abstract static I1<T0> operator" + op + @" (I1<T0> x, T0 a); abstract static T0 operator" + op + @" (T0 x, I1<T0> a); "; } source1 += @" abstract static T0 operator" + op + @" (T0 x, int a); } class Test { "; if (!isShiftOperator) { source1 += @" static void M02<T, U>(int a, T x) where T : U where U : I1<T> { a " + op + @"= x; } static void M04<T, U>(int? a, T? y) where T : struct, U where U : I1<T> { a " + op + @"= y; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { x " + op + @"= y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { x " + op + @"= y; } "; } source1 += @" static void M03<T, U>(T x) where T : U where U : I1<T> { x " + op + @"= 1; } static void M05<T, U>(T? y) where T : struct, U where U : I1<T> { y " + op + @"= 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(int, T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""int I1<T>." + metadataName + @"(int, T)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?, T?)", @" { // Code size 66 (0x42) .maxstack 2 .locals init (int? V_0, T? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool int?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: and IL_0014: brtrue.s IL_0021 IL_0016: ldloca.s V_2 IL_0018: initobj ""int?"" IL_001e: ldloc.2 IL_001f: br.s IL_003f IL_0021: ldloca.s V_0 IL_0023: call ""readonly int int?.GetValueOrDefault()"" IL_0028: ldloca.s V_1 IL_002a: call ""readonly T T?.GetValueOrDefault()"" IL_002f: constrained. ""T"" IL_0035: call ""int I1<T>." + metadataName + @"(int, T)"" IL_003a: newobj ""int?..ctor(int)"" IL_003f: starg.s V_0 IL_0041: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""I1<T> I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: starg.s V_0 IL_0010: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 50 (0x32) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002f IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: ldc.i4.1 IL_001f: constrained. ""T"" IL_0025: call ""T I1<T>." + metadataName + @"(T, int)"" IL_002a: newobj ""T?..ctor(T)"" IL_002f: starg.s V_0 IL_0031: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(int, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(int, T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?, T?)", @" { // Code size 65 (0x41) .maxstack 2 .locals init (int? V_0, T? V_1, int? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool int?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: and IL_0013: brtrue.s IL_0020 IL_0015: ldloca.s V_2 IL_0017: initobj ""int?"" IL_001d: ldloc.2 IL_001e: br.s IL_003e IL_0020: ldloca.s V_0 IL_0022: call ""readonly int int?.GetValueOrDefault()"" IL_0027: ldloca.s V_1 IL_0029: call ""readonly T T?.GetValueOrDefault()"" IL_002e: constrained. ""T"" IL_0034: call ""int I1<T>." + metadataName + @"(int, T)"" IL_0039: newobj ""int?..ctor(int)"" IL_003e: starg.s V_0 IL_0040: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""I1<T> I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: starg.s V_0 IL_000f: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0016 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: br.s IL_002e IL_0016: ldloca.s V_0 IL_0018: call ""readonly T T?.GetValueOrDefault()"" IL_001d: ldc.i4.1 IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T, int)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: starg.s V_0 IL_0030: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(n => n.ToString() == "x " + op + "= 1").Single(); Assert.Equal("x " + op + "= 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" ICompoundAssignmentOperation (BinaryOperatorKind." + operatorKind + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.CompoundAssignment, Type: T) (Syntax: 'x " + op + @"= 1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } class Test { static void M02<T, U>((int, T) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0011: bne.un.s IL_002c IL_0013: ldloc.0 IL_0014: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001f: constrained. ""T"" IL_0025: call ""bool I1<T>.op_Equality(T, T)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.0 IL_002d: pop IL_002e: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0011: bne.un.s IL_002c IL_0013: ldloc.0 IL_0014: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001f: constrained. ""T"" IL_0025: call ""bool I1<T>.op_Inequality(T, T)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.1 IL_002d: pop IL_002e: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0010: bne.un.s IL_002b IL_0012: ldloc.0 IL_0013: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001e: constrained. ""T"" IL_0024: call ""bool I1<T>.op_Equality(T, T)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0010: bne.un.s IL_002b IL_0012: ldloc.0 IL_0013: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001e: constrained. ""T"" IL_0024: call ""bool I1<T>.op_Inequality(T, T)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.1 IL_002c: pop IL_002d: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, T)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, T)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1 { _ = x " + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x - y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " y").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator- (I1 x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 32) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_04(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" } "; var source2 = @" class Test { static void M02<T>(T x, T y) where T : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); if (success) { compilation2.VerifyDiagnostics(); } else { compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x && y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + op + " y").WithLocation(6, 13) ); } var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); if (binaryIsAbstract) { builder.Add( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator& (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 32) ); } if (trueIsAbstract) { builder.Add( // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(13, 35) ); } if (falseIsAbstract) { builder.Add( // (14,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(14, 35) ); } compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation).Verify(builder.ToArrayAndFree()); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("*")] [InlineData("/")] [InlineData("%")] [InlineData("&")] [InlineData("|")] [InlineData("^")] [InlineData("<<")] [InlineData(">>")] public void ConsumeAbstractCompoundBinaryOperator_04(string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + op + @" (T x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1<T> { x " + op + @"= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // x *= y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + "= y").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator* (T x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 31) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } "; var source2 = @" class Test { static void M02<T>((int, T) x) where T : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator == (T x, T y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "==").WithLocation(12, 35), // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator != (T x, T y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "!=").WithLocation(13, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_06([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1 { _ = x " + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x - y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " y").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator- (I1 x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 32) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_06(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" } "; var source2 = @" class Test { static void M02<T>(T x, T y) where T : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); if (success) { compilation2.VerifyDiagnostics(); } else { compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x && y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + op + " y").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); } var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); if (binaryIsAbstract) { builder.Add( // (12,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator& (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 32) ); } if (trueIsAbstract) { builder.Add( // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } if (falseIsAbstract) { builder.Add( // (14,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(14, 35) ); } compilation3.VerifyDiagnostics(builder.ToArrayAndFree()); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("*")] [InlineData("/")] [InlineData("%")] [InlineData("&")] [InlineData("|")] [InlineData("^")] [InlineData("<<")] [InlineData(">>")] public void ConsumeAbstractCompoundBinaryOperator_06(string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + op + @" (T x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1<T> { x " + op + @"= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x <<= y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + "= y").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,31): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator<< (T x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 31) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } "; var source2 = @" class Test { static void M02<T>((int, T) x) where T : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator == (T x, T y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(12, 35), // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator != (T x, T y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { _ = P01; _ = P04; } void M03() { _ = this.P01; _ = this.P04; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { _ = I1.P01; _ = x.P01; _ = I1.P04; _ = x.P04; } static void MT2<T>() where T : I1 { _ = T.P03; _ = T.P04; _ = T.P00; _ = T.P05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01.ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = P01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 13), // (14,13): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = this.P01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 13), // (15,13): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = this.P04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 13), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = I1.P01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 13), // (28,13): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = x.P01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 13), // (30,13): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = x.P04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 13), // (35,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 13), // (36,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 13), // (37,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 13), // (38,15): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = T.P05; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 15), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01.ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticPropertySet_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { P01 = 1; P04 = 1; } void M03() { this.P01 = 1; this.P04 = 1; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { I1.P01 = 1; x.P01 = 1; I1.P04 = 1; x.P04 = 1; } static void MT2<T>() where T : I1 { T.P03 = 1; T.P04 = 1; T.P00 = 1; T.P05 = 1; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 = 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 = 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 = 1; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 = 1").WithLocation(40, 71), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { P01 += 1; P04 += 1; } void M03() { this.P01 += 1; this.P04 += 1; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { I1.P01 += 1; x.P01 += 1; I1.P04 += 1; x.P04 += 1; } static void MT2<T>() where T : I1 { T.P03 += 1; T.P04 += 1; T.P00 += 1; T.P05 += 1; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 += 1; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 += 1").WithLocation(40, 71), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticProperty_02() { var source1 = @" interface I1 { abstract static int P01 { get; set; } static void M02() { _ = nameof(P01); _ = nameof(P04); } void M03() { _ = nameof(this.P01); _ = nameof(this.P04); } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { _ = nameof(I1.P01); _ = nameof(x.P01); _ = nameof(I1.P04); _ = nameof(x.P04); } static void MT2<T>() where T : I1 { _ = nameof(T.P03); _ = nameof(T.P04); _ = nameof(T.P00); _ = nameof(T.P05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (14,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 20), // (15,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 20), // (28,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 20), // (30,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 20), // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = nameof(T.P05); Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""int I1.P01.get"" IL_000c: pop IL_000d: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: constrained. ""T"" IL_0006: call ""int I1.P01.get"" IL_000b: pop IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Right; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertySet_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 15 (0xf) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""void I1.P01.set"" IL_000d: nop IL_000e: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: constrained. ""T"" IL_0007: call ""void I1.P01.set"" IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertyCompound_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { T.P01 += 1; } static string M03<T, U>() where T : U where U : I1 { return nameof(T.P01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""int I1.P01.get"" IL_000c: ldc.i4.1 IL_000d: add IL_000e: constrained. ""T"" IL_0014: call ""void I1.P01.set"" IL_0019: nop IL_001a: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""P01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: constrained. ""T"" IL_0006: call ""int I1.P01.get"" IL_000b: ldc.i4.1 IL_000c: add IL_000d: constrained. ""T"" IL_0013: call ""void I1.P01.set"" IL_0018: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""P01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertyGet_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = T.P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertySet_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 = 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9), // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = T.P01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = T.P01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 13), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticPropertySet_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 = 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 = 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticEventAdd_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used interface I1 { abstract static event System.Action P01; static void M02() { P01 += null; P04 += null; } void M03() { this.P01 += null; this.P04 += null; } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { I1.P01 += null; x.P01 += null; I1.P04 += null; x.P04 += null; } static void MT2<T>() where T : I1 { T.P03 += null; T.P04 += null; T.P00 += null; T.P05 += null; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += null); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01 += null").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (14,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // this.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "this.P01 += null").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01 += null").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (28,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x.P01 += null").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += null); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 += null").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticEventRemove_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used interface I1 { abstract static event System.Action P01; static void M02() { P01 -= null; P04 -= null; } void M03() { this.P01 -= null; this.P04 -= null; } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { I1.P01 -= null; x.P01 -= null; I1.P04 -= null; x.P04 -= null; } static void MT2<T>() where T : I1 { T.P03 -= null; T.P04 -= null; T.P00 -= null; T.P05 -= null; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 -= null); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01 -= null").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (14,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // this.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "this.P01 -= null").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01 -= null").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (28,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x.P01 -= null").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 -= null); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 -= null").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticEvent_02() { var source1 = @" interface I1 { abstract static event System.Action P01; static void M02() { _ = nameof(P01); _ = nameof(P04); } void M03() { _ = nameof(this.P01); _ = nameof(this.P04); } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { _ = nameof(I1.P01); _ = nameof(x.P01); _ = nameof(I1.P04); _ = nameof(x.P04); } static void MT2<T>() where T : I1 { _ = nameof(T.P03); _ = nameof(T.P04); _ = nameof(T.P00); _ = nameof(T.P05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (14,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 20), // (15,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 20), // (28,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 20), // (30,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 20), // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = nameof(T.P05); Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticEvent_03() { var source1 = @" public interface I1 { abstract static event System.Action E01; } class Test { static void M02<T, U>() where T : U where U : I1 { T.E01 += null; T.E01 -= null; } static string M03<T, U>() where T : U where U : I1 { return nameof(T.E01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 28 (0x1c) .maxstack 1 IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: call ""void I1.E01.add"" IL_000d: nop IL_000e: ldnull IL_000f: constrained. ""T"" IL_0015: call ""void I1.E01.remove"" IL_001a: nop IL_001b: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""E01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 25 (0x19) .maxstack 1 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: call ""void I1.E01.add"" IL_000c: ldnull IL_000d: constrained. ""T"" IL_0013: call ""void I1.E01.remove"" IL_0018: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""E01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.E01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IEventReferenceOperation: event System.Action I1.E01 (Static) (OperationKind.EventReference, Type: System.Action) (Syntax: 'T.E01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "E01").Single().ToTestDisplayString()); Assert.Equal("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "E01").Single().ToTestDisplayString()); Assert.Contains("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("event System.Action I1.E01", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "E01").Single().ToTestDisplayString()); Assert.Equal("event System.Action I1.E01", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "E01").Single().ToTestDisplayString()); Assert.Contains("event System.Action I1.E01", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("event System.Action I1.E01", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("E01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticEventAdd_04() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01 += null").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "P01").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventRemove_04() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 -= null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01 -= null").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "P01").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventAdd_06() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventRemove_06() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 -= null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 -= null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticIndexedProperty_03() { var ilSource = @" .class interface public auto ansi abstract I1 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) // Methods .method public hidebysig specialname newslot abstract virtual static int32 get_Item ( int32 x ) cil managed { } // end of method I1::get_Item .method public hidebysig specialname newslot abstract virtual static void set_Item ( int32 x, int32 'value' ) cil managed { } // end of method I1::set_Item // Properties .property int32 Item( int32 x ) { .get int32 I1::get_Item(int32) .set void I1::set_Item(int32, int32) } } // end of class I1 "; var source1 = @" class Test { static void M02<T>() where T : I1 { T.Item[0] += 1; } static string M03<T>() where T : I1 { return nameof(T.Item); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.Item[0] += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(6, 9), // (11,23): error CS0119: 'T' is a type parameter, which is not valid in the given context // return nameof(T.Item); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(11, 23) ); var source2 = @" class Test { static void M02<T>() where T : I1 { T[0] += 1; } static void M03<T>() where T : I1 { T.set_Item(0, T.get_Item(0) + 1); } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,9): error CS0119: 'T' is a type, which is not valid in the given context // T[0] += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(6, 9), // (11,11): error CS0571: 'I1.this[int].set': cannot explicitly call operator or accessor // T.set_Item(0, T.get_Item(0) + 1); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Item").WithArguments("I1.this[int].set").WithLocation(11, 11), // (11,25): error CS0571: 'I1.this[int].get': cannot explicitly call operator or accessor // T.set_Item(0, T.get_Item(0) + 1); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("I1.this[int].get").WithLocation(11, 25) ); } [Fact] public void ConsumeAbstractStaticIndexedProperty_04() { var ilSource = @" .class interface public auto ansi abstract I1 { // Methods .method public hidebysig specialname newslot abstract virtual static int32 get_Item ( int32 x ) cil managed { } // end of method I1::get_Item .method public hidebysig specialname newslot abstract virtual static void set_Item ( int32 x, int32 'value' ) cil managed { } // end of method I1::set_Item // Properties .property int32 Item( int32 x ) { .get int32 I1::get_Item(int32) .set void I1::set_Item(int32, int32) } } // end of class I1 "; var source1 = @" class Test { static void M02<T>() where T : I1 { T.Item[0] += 1; } static string M03<T>() where T : I1 { return nameof(T.Item); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,11): error CS1545: Property, indexer, or event 'I1.Item[int]' is not supported by the language; try directly calling accessor methods 'I1.get_Item(int)' or 'I1.set_Item(int, int)' // T.Item[0] += 1; Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Item").WithArguments("I1.Item[int]", "I1.get_Item(int)", "I1.set_Item(int, int)").WithLocation(6, 11), // (11,25): error CS1545: Property, indexer, or event 'I1.Item[int]' is not supported by the language; try directly calling accessor methods 'I1.get_Item(int)' or 'I1.set_Item(int, int)' // return nameof(T.Item); Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Item").WithArguments("I1.Item[int]", "I1.get_Item(int)", "I1.set_Item(int, int)").WithLocation(11, 25) ); var source2 = @" class Test { static void M02<T>() where T : I1 { T.set_Item(0, T.get_Item(0) + 1); } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation2, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T>()", @" { // Code size 29 (0x1d) .maxstack 3 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: ldc.i4.0 IL_0003: constrained. ""T"" IL_0009: call ""int I1.get_Item(int)"" IL_000e: ldc.i4.1 IL_000f: add IL_0010: constrained. ""T"" IL_0016: call ""void I1.set_Item(int, int)"" IL_001b: nop IL_001c: ret } "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = (System.Action)M01; _ = (System.Action)M04; } void M03() { _ = (System.Action)this.M01; _ = (System.Action)this.M04; } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = (System.Action)I1.M01; _ = (System.Action)x.M01; _ = (System.Action)I1.M04; _ = (System.Action)x.M04; } static void MT2<T>() where T : I1 { _ = (System.Action)T.M03; _ = (System.Action)T.M04; _ = (System.Action)T.M00; _ = (System.Action)T.M05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.Action)T.M01).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (System.Action)M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(System.Action)M01").WithLocation(8, 13), // (14,28): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)this.M01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 28), // (15,28): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)this.M04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 28), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (System.Action)I1.M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(System.Action)I1.M01").WithLocation(27, 13), // (28,28): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)x.M01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 28), // (30,28): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)x.M04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 28), // (35,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 28), // (36,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 28), // (37,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 28), // (38,30): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = (System.Action)T.M05; Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 30), // (40,87): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.Action)T.M01).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01").WithLocation(40, 87) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_03() { var source1 = @" public interface I1 { abstract static void M01(); } class Test { static System.Action M02<T, U>() where T : U where U : I1 { return T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 24 (0x18) .maxstack 2 .locals init (System.Action V_0) IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: ldftn ""void I1.M01()"" IL_000e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0012: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = (System.Action)T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "(System.Action)T.M01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = (System.Action)T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,28): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 28) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,28): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 28), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = new System.Action(M01); _ = new System.Action(M04); } void M03() { _ = new System.Action(this.M01); _ = new System.Action(this.M04); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = new System.Action(I1.M01); _ = new System.Action(x.M01); _ = new System.Action(I1.M04); _ = new System.Action(x.M04); } static void MT2<T>() where T : I1 { _ = new System.Action(T.M03); _ = new System.Action(T.M04); _ = new System.Action(T.M00); _ = new System.Action(T.M05); _ = (System.Linq.Expressions.Expression<System.Action>)(() => new System.Action(T.M01).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,31): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = new System.Action(M01); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "M01").WithLocation(8, 31), // (14,31): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(this.M01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 31), // (15,31): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(this.M04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 31), // (27,31): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = new System.Action(I1.M01); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.M01").WithLocation(27, 31), // (28,31): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(x.M01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 31), // (30,31): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(x.M04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 31), // (35,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 31), // (36,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 31), // (37,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 31), // (38,33): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = new System.Action(T.M05); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 33), // (40,89): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => new System.Action(T.M01).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01").WithLocation(40, 89) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_03() { var source1 = @" public interface I1 { abstract static void M01(); } class Test { static System.Action M02<T, U>() where T : U where U : I1 { return new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 24 (0x18) .maxstack 2 .locals init (System.Action V_0) IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: ldftn ""void I1.M01()"" IL_000e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0012: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.M01").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_01() { var source1 = @" unsafe interface I1 { abstract static void M01(); static void M02() { _ = (delegate*<void>)&M01; _ = (delegate*<void>)&M04; } void M03() { _ = (delegate*<void>)&this.M01; _ = (delegate*<void>)&this.M04; } static void M04() {} protected abstract static void M05(); } unsafe class Test { static void MT1(I1 x) { _ = (delegate*<void>)&I1.M01; _ = (delegate*<void>)&x.M01; _ = (delegate*<void>)&I1.M04; _ = (delegate*<void>)&x.M04; } static void MT2<T>() where T : I1 { _ = (delegate*<void>)&T.M03; _ = (delegate*<void>)&T.M04; _ = (delegate*<void>)&T.M00; _ = (delegate*<void>)&T.M05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (delegate*<void>)&M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(delegate*<void>)&M01").WithLocation(8, 13), // (14,13): error CS8757: No overload for 'M01' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&this.M01; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&this.M01").WithArguments("M01", "delegate*<void>").WithLocation(14, 13), // (15,13): error CS8757: No overload for 'M04' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&this.M04; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&this.M04").WithArguments("M04", "delegate*<void>").WithLocation(15, 13), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (delegate*<void>)&I1.M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(delegate*<void>)&I1.M01").WithLocation(27, 13), // (28,13): error CS8757: No overload for 'M01' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&x.M01; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&x.M01").WithArguments("M01", "delegate*<void>").WithLocation(28, 13), // (30,13): error CS8757: No overload for 'M04' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&x.M04; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&x.M04").WithArguments("M04", "delegate*<void>").WithLocation(30, 13), // (35,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 31), // (36,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 31), // (37,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 31), // (38,33): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = (delegate*<void>)&T.M05; Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 33), // (40,88): error CS1944: An expression tree may not contain an unsafe pointer operation // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "(delegate*<void>)&T.M01").WithLocation(40, 88), // (40,106): error CS8810: '&' on method groups cannot be used in expression trees // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); Diagnostic(ErrorCode.ERR_AddressOfMethodGroupInExpressionTree, "T.M01").WithLocation(40, 106) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_03() { var source1 = @" public interface I1 { abstract static void M01(); } unsafe class Test { static delegate*<void> M02<T, U>() where T : U where U : I1 { return &T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 18 (0x12) .maxstack 1 .locals init (delegate*<void> V_0) IL_0000: nop IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: constrained. ""T"" IL_0006: ldftn ""void I1.M01()"" IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionFunctionPointer_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" unsafe class Test { static void M02<T>() where T : I1 { _ = (delegate*<void>)&T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "(delegate*<void>)&T.M01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" unsafe class Test { static void M02<T>() where T : I1 { _ = (delegate*<void>)&T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public void M01() {} } " + typeKeyword + @" C3 : I1 { static void M01() {} } " + typeKeyword + @" C4 : I1 { void I1.M01() {} } " + typeKeyword + @" C5 : I1 { public static int M01() => throw null; } " + typeKeyword + @" C6 : I1 { static int I1.M01() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01()' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01()").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01()'. 'C2.M01()' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01()", "C2.M01()").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01()'. 'C3.M01()' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01()", "C3.M01()").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01()' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01()").WithLocation(24, 10), // (26,13): error CS0539: 'C4.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01()").WithLocation(26, 13), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01()'. 'C5.M01()' cannot implement 'I1.M01()' because it does not have the matching return type of 'void'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01()", "C5.M01()", "void").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01()' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01()").WithLocation(36, 10), // (38,19): error CS0539: 'C6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01()").WithLocation(38, 19) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract void M01(); } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static void M01() {} } " + typeKeyword + @" C3 : I1 { void M01() {} } " + typeKeyword + @" C4 : I1 { static void I1.M01() {} } " + typeKeyword + @" C5 : I1 { public int M01() => throw null; } " + typeKeyword + @" C6 : I1 { int I1.M01() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01()' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01()").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01()'. 'C2.M01()' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01()", "C2.M01()").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01()'. 'C3.M01()' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01()", "C3.M01()").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01()' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01()").WithLocation(24, 10), // (26,20): error CS0539: 'C4.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01()").WithLocation(26, 20), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01()'. 'C5.M01()' cannot implement 'I1.M01()' because it does not have the matching return type of 'void'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01()", "C5.M01()", "void").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01()' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01()").WithLocation(36, 10), // (38,12): error CS0539: 'C6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01()").WithLocation(38, 12) ); } [Fact] public void ImplementAbstractStaticMethod_03() { var source1 = @" public interface I1 { abstract static void M01(); } interface I2 : I1 {} interface I3 : I1 { public virtual void M01() {} } interface I4 : I1 { static void M01() {} } interface I5 : I1 { void I1.M01() {} } interface I6 : I1 { static void I1.M01() {} } interface I7 : I1 { abstract static void M01(); } interface I8 : I1 { abstract static void I1.M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,25): warning CS0108: 'I3.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // public virtual void M01() {} Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01()", "I1.M01()").WithLocation(12, 25), // (17,17): warning CS0108: 'I4.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // static void M01() {} Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01()", "I1.M01()").WithLocation(17, 17), // (22,13): error CS0539: 'I5.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01()").WithLocation(22, 13), // (27,20): error CS0106: The modifier 'static' is not valid for this item // static void I1.M01() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 20), // (27,20): error CS0539: 'I6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01()").WithLocation(27, 20), // (32,26): warning CS0108: 'I7.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // abstract static void M01(); Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01()", "I1.M01()").WithLocation(32, 26), // (37,29): error CS0106: The modifier 'static' is not valid for this item // abstract static void I1.M01(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 29), // (37,29): error CS0539: 'I8.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static void I1.M01(); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01()").WithLocation(37, 29) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); abstract static void M02(); } "; var source2 = typeKeyword + @" Test: I1 { static void I1.M01() {} public static void M02() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,20): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 20) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,20): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 20), // (10,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 26), // (11,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M02(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = typeKeyword + @" Test1: I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01()' cannot implement interface member 'I1.M01()' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01()", "I1.M01()", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01()' cannot implement interface member 'I1.M01()' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01()", "I1.M01()", "Test1").WithLocation(2, 12), // (9,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = typeKeyword + @" Test1: I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,20): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 20) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,20): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 20), // (9,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C : I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, cM01.MethodKind); Assert.Equal("void C.M01()", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C : I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.Equal("void C.I1.M01()", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticMethod_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static void M01(); } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C2.I1.M01()", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticMethod_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig static abstract virtual void M01 () cil managed { } // end of method I1::M01 } // end of class I1 .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static void I1.M01 () cil managed { .override method void I1::M01() .maxstack 8 IL_0000: ret } // end of method C1::I1.M01 .method public hidebysig static void M01 () cil managed { IL_0000: ret } // end of method C1::M01 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } // end of method C1::.ctor } // end of class C1 .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static void M01 () cil managed { IL_0000: ret } // end of method C2::M01 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1.I1.M01()", c1M01.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); Assert.Equal("void C2.M01()", c5.FindImplementationForInterfaceMember(m01).ToTestDisplayString()); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticMethod_11() { // Ignore invalid metadata (non-abstract static virtual method). var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig virtual static void M01 () cil managed { IL_0000: ret } // end of method I1::M01 } // end of class I1 "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static void I1.M01() {} } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,19): error CS0539: 'C1.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01()").WithLocation(4, 19) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Fact] public void ImplementAbstractStaticMethod_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void M01 () cil managed { } // end of method I1::M01 } // end of class I1 .class interface public auto ansi abstract I2 implements I1 { // Methods .method private hidebysig static void I1.M01 () cil managed { .override method void I1::M01() IL_0000: ret } // end of method I2::I1.M01 } // end of class I2 "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01()' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01()").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticMethod_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static void M01(); } class C1 { public static void M01() {} } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("void C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1.M01"); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Ordinary, c2M01.MethodKind); Assert.Equal("void C1.M01()", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C1.M01()"" IL_0005: ret } "); } [Fact] public void ImplementAbstractStaticMethod_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void modopt(I1) M01 () cil managed { } // end of method I1::M01 } // end of class I1 "; var source1 = @" class C1 : I1 { public static void M01() {} } class C2 : I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("void modopt(I1) C1.I1.M01()", c1M01.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1.M01"); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("void modopt(I1) C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C1.M01()"" IL_0005: ret } "); } [Fact] public void ImplementAbstractStaticMethod_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static void M01(); abstract static void M02(); } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static void I1.M02() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<MethodSymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>("M01"); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<MethodSymbol>().Single(); var c2M02 = c3.BaseType().GetMember<MethodSymbol>("I1.M02"); Assert.Equal("void C2.I1.M02()", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Fact] public void ImplementAbstractStaticMethod_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static void M01(); } public class C1 : I1 { public static void M01() {} } public class C2 : C1 { new public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C2.M01()"" IL_0005: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<MethodSymbol>("M01"); Assert.Equal("void C2.M01()", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C3.I1.M01()", c3M01.ToTestDisplayString()); Assert.Same(m01, c3M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_17(bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(System.Int32 x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(System.Int32 x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_18(bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(T x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(T x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_19(bool genericFirst) { // Same as ImplementAbstractStaticMethod_17 only implementation is explicit in source. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" static void I1.M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.I1.M01(System.Int32 x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_20(bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implementation is explicit in source. var generic = @" static void I1<T>.M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.I1<T>.M01(T x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_21(bool genericFirst) { // Same as ImplementAbstractStaticMethod_17 only implicit implementation is in an intermediate base. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T> : C1<T>, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C11<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "void C11<T>.I1.M01(System.Int32 x)" : "void C1<T>.M01(System.Int32 x)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_22(bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implicit implementation is in an intermediate base. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T> : C1<T>, I1<T> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C11<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "void C11<T>.I1<T>.M01(T x)" : "void C1<T>.M01(T x)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } private static string UnaryOperatorName(string op) => OperatorFacts.UnaryOperatorNameFromSyntaxKindIfAny(SyntaxFactory.ParseToken(op).Kind()); private static string BinaryOperatorName(string op) => op switch { ">>" => WellKnownMemberNames.RightShiftOperatorName, _ => OperatorFacts.BinaryOperatorNameFromSyntaxKindIfAny(SyntaxFactory.ParseToken(op).Kind()) }; [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = UnaryOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public C2 operator " + op + @"(C2 x) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static C3 operator " + op + @"(C3 x) => throw null; } " + typeKeyword + @" C4 : I1<C4> { C4 I1<C4>.operator " + op + @"(C4 x) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static int operator " + op + @" (C5 x) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static int I1<C6>.operator " + op + @" (C6 x) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static C7 " + opName + @"(C7 x) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static C8 I1<C8>." + opName + @"(C8 x) => throw null; } public interface I2<T> where T : I2<T> { abstract static T " + opName + @"(T x); } " + typeKeyword + @" C9 : I2<C9> { public static C9 operator " + op + @"(C9 x) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static C10 I2<C10>.operator " + op + @"(C10 x) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_BadIncDecRetType or (int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.operator +(C1)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>.operator " + op + "(C1)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.operator +(C2)'. 'C2.operator +(C2)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>.operator " + op + "(C2)", "C2.operator " + op + "(C2)").WithLocation(12, 10), // (14,24): error CS0558: User-defined operator 'C2.operator +(C2)' must be declared static and public // public C2 operator +(C2 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C2.operator " + op + "(C2)").WithLocation(14, 24), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.operator +(C3)'. 'C3.operator +(C3)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>.operator " + op + "(C3)", "C3.operator " + op + "(C3)").WithLocation(18, 10), // (20,24): error CS0558: User-defined operator 'C3.operator +(C3)' must be declared static and public // static C3 operator +(C3 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C3.operator " + op + "(C3)").WithLocation(20, 24), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.operator +(C4)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>.operator " + op + "(C4)").WithLocation(24, 10), // (26,24): error CS8930: Explicit implementation of a user-defined operator 'C4.operator +(C4)' must be declared static // C4 I1<C4>.operator +(C4 x) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("C4.operator " + op + "(C4)").WithLocation(26, 24), // (26,24): error CS0539: 'C4.operator +(C4)' in explicit interface declaration is not found among members of the interface that can be implemented // C4 I1<C4>.operator +(C4 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C4.operator " + op + "(C4)").WithLocation(26, 24), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.operator +(C5)'. 'C5.operator +(C5)' cannot implement 'I1<C5>.operator +(C5)' because it does not have the matching return type of 'C5'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>.operator " + op + "(C5)", "C5.operator " + op + "(C5)", "C5").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.operator +(C6)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>.operator " + op + "(C6)").WithLocation(36, 10), // (38,32): error CS0539: 'C6.operator +(C6)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C6>.operator + (C6 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C6.operator " + op + "(C6)").WithLocation(38, 32), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.operator +(C7)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>.operator " + op + "(C7)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.operator +(C8)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>.operator " + op + "(C8)").WithLocation(48, 10), // (50,22): error CS0539: 'C8.op_UnaryPlus(C8)' in explicit interface declaration is not found among members of the interface that can be implemented // static C8 I1<C8>.op_UnaryPlus(C8 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8)").WithLocation(50, 22), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_UnaryPlus(C9)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_UnaryPlus(C10)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10)").WithLocation(65, 11), // (67,33): error CS0539: 'C10.operator +(C10)' in explicit interface declaration is not found among members of the interface that can be implemented // static C10 I2<C10>.operator +(C10 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C10.operator " + op + "(C10)").WithLocation(67, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = BinaryOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public C2 operator " + op + @"(C2 x, int y) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static C3 operator " + op + @"(C3 x, int y) => throw null; } " + typeKeyword + @" C4 : I1<C4> { C4 I1<C4>.operator " + op + @"(C4 x, int y) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static int operator " + op + @" (C5 x, int y) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static int I1<C6>.operator " + op + @" (C6 x, int y) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static C7 " + opName + @"(C7 x, int y) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static C8 I1<C8>." + opName + @"(C8 x, int y) => throw null; } public interface I2<T> where T : I2<T> { abstract static T " + opName + @"(T x, int y); } " + typeKeyword + @" C9 : I2<C9> { public static C9 operator " + op + @"(C9 x, int y) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static C10 I2<C10>.operator " + op + @"(C10 x, int y) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.operator >>(C1, int)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>.operator " + op + "(C1, int)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.operator >>(C2, int)'. 'C2.operator >>(C2, int)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>.operator " + op + "(C2, int)", "C2.operator " + op + "(C2, int)").WithLocation(12, 10), // (14,24): error CS0558: User-defined operator 'C2.operator >>(C2, int)' must be declared static and public // public C2 operator >>(C2 x, int y) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C2.operator " + op + "(C2, int)").WithLocation(14, 24), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.operator >>(C3, int)'. 'C3.operator >>(C3, int)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>.operator " + op + "(C3, int)", "C3.operator " + op + "(C3, int)").WithLocation(18, 10), // (20,24): error CS0558: User-defined operator 'C3.operator >>(C3, int)' must be declared static and public // static C3 operator >>(C3 x, int y) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C3.operator " + op + "(C3, int)").WithLocation(20, 24), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.operator >>(C4, int)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>.operator " + op + "(C4, int)").WithLocation(24, 10), // (26,24): error CS8930: Explicit implementation of a user-defined operator 'C4.operator >>(C4, int)' must be declared static // C4 I1<C4>.operator >>(C4 x, int y) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("C4.operator " + op + "(C4, int)").WithLocation(26, 24), // (26,24): error CS0539: 'C4.operator >>(C4, int)' in explicit interface declaration is not found among members of the interface that can be implemented // C4 I1<C4>.operator >>(C4 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C4.operator " + op + "(C4, int)").WithLocation(26, 24), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.operator >>(C5, int)'. 'C5.operator >>(C5, int)' cannot implement 'I1<C5>.operator >>(C5, int)' because it does not have the matching return type of 'C5'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>.operator " + op + "(C5, int)", "C5.operator " + op + "(C5, int)", "C5").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.operator >>(C6, int)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>.operator " + op + "(C6, int)").WithLocation(36, 10), // (38,32): error CS0539: 'C6.operator >>(C6, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C6>.operator >> (C6 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C6.operator " + op + "(C6, int)").WithLocation(38, 32), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.operator >>(C7, int)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>.operator " + op + "(C7, int)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.operator >>(C8, int)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>.operator " + op + "(C8, int)").WithLocation(48, 10), // (50,22): error CS0539: 'C8.op_RightShift(C8, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static C8 I1<C8>.op_RightShift(C8 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8, int)").WithLocation(50, 22), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_RightShift(C9, int)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9, int)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_RightShift(C10, int)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10, int)").WithLocation(65, 11), // (67,33): error CS0539: 'C10.operator >>(C10, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static C10 I2<C10>.operator >>(C10 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C10.operator " + op + "(C10, int)").WithLocation(67, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_03([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } interface I2 : I1 {} interface I3 : I1 { I1 operator " + op + @"(I1 x) => default; } interface I4 : I1 { static I1 operator " + op + @"(I1 x) => default; } interface I5 : I1 { I1 I1.operator " + op + @"(I1 x) => default; } interface I6 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } interface I7 : I1 { abstract static I1 operator " + op + @"(I1 x); } public interface I11<T> where T : I11<T> { abstract static T operator " + op + @"(T x); } interface I8<T> : I11<T> where T : I8<T> { T operator " + op + @"(T x) => default; } interface I9<T> : I11<T> where T : I9<T> { static T operator " + op + @"(T x) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static T operator " + op + @"(T x); } interface I12<T> : I11<T> where T : I12<T> { static T I11<T>.operator " + op + @"(T x) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static T I11<T>.operator " + op + @"(T x); } interface I14 : I1 { abstract static I1 I1.operator " + op + @"(I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ErrorCode badSignatureError = op.Length != 2 ? ErrorCode.ERR_BadUnaryOperatorSignature : ErrorCode.ERR_BadIncDecSignature; ErrorCode badAbstractSignatureError = op.Length != 2 ? ErrorCode.ERR_BadAbstractUnaryOperatorSignature : ErrorCode.ERR_BadAbstractIncDecSignature; compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (12,17): error CS0558: User-defined operator 'I3.operator +(I1)' must be declared static and public // I1 operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I3.operator " + op + "(I1)").WithLocation(12, 17), // (12,17): error CS0562: The parameter of a unary operator must be the containing type // I1 operator +(I1 x) => default; Diagnostic(badSignatureError, op).WithLocation(12, 17), // (17,24): error CS0562: The parameter of a unary operator must be the containing type // static I1 operator +(I1 x) => default; Diagnostic(badSignatureError, op).WithLocation(17, 24), // (22,20): error CS8930: Explicit implementation of a user-defined operator 'I5.operator +(I1)' must be declared static // I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("I5.operator " + op + "(I1)").WithLocation(22, 20), // (22,20): error CS0539: 'I5.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I5.operator " + op + "(I1)").WithLocation(22, 20), // (27,27): error CS0539: 'I6.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I6.operator " + op + "(I1)").WithLocation(27, 27), // (32,33): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // abstract static I1 operator +(I1 x); Diagnostic(badAbstractSignatureError, op).WithLocation(32, 33), // (42,16): error CS0558: User-defined operator 'I8<T>.operator +(T)' must be declared static and public // T operator +(T x) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I8<T>.operator " + op + "(T)").WithLocation(42, 16), // (42,16): error CS0562: The parameter of a unary operator must be the containing type // T operator +(T x) => default; Diagnostic(badSignatureError, op).WithLocation(42, 16), // (47,23): error CS0562: The parameter of a unary operator must be the containing type // static T operator +(T x) => default; Diagnostic(badSignatureError, op).WithLocation(47, 23), // (57,30): error CS0539: 'I12<T>.operator +(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static T I11<T>.operator +(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I12<T>.operator " + op + "(T)").WithLocation(57, 30), // (62,39): error CS0106: The modifier 'abstract' is not valid for this item // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(62, 39), // (62,39): error CS0501: 'I13<T>.operator +(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I13<T>.operator " + op + "(T)").WithLocation(62, 39), // (62,39): error CS0539: 'I13<T>.operator +(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I13<T>.operator " + op + "(T)").WithLocation(62, 39), // (67,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(67, 36), // (67,36): error CS0501: 'I14.operator +(I1)' must declare a body because it is not marked abstract, extern, or partial // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I14.operator " + op + "(I1)").WithLocation(67, 36), // (67,36): error CS0539: 'I14.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I14.operator " + op + "(I1)").WithLocation(67, 36) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_03([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } interface I2 : I1 {} interface I3 : I1 { I1 operator " + op + @"(I1 x, int y) => default; } interface I4 : I1 { static I1 operator " + op + @"(I1 x, int y) => default; } interface I5 : I1 { I1 I1.operator " + op + @"(I1 x, int y) => default; } interface I6 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } interface I7 : I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public interface I11<T> where T : I11<T> { abstract static T operator " + op + @"(T x, int y); } interface I8<T> : I11<T> where T : I8<T> { T operator " + op + @"(T x, int y) => default; } interface I9<T> : I11<T> where T : I9<T> { static T operator " + op + @"(T x, int y) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static T operator " + op + @"(T x, int y); } interface I12<T> : I11<T> where T : I12<T> { static T I11<T>.operator " + op + @"(T x, int y) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static T I11<T>.operator " + op + @"(T x, int y); } interface I14 : I1 { abstract static I1 I1.operator " + op + @"(I1 x, int y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); bool isShift = op == "<<" || op == ">>"; ErrorCode badSignatureError = isShift ? ErrorCode.ERR_BadShiftOperatorSignature : ErrorCode.ERR_BadBinaryOperatorSignature; ErrorCode badAbstractSignatureError = isShift ? ErrorCode.ERR_BadAbstractShiftOperatorSignature : ErrorCode.ERR_BadAbstractBinaryOperatorSignature; var expected = new[] { // (12,17): error CS0563: One of the parameters of a binary operator must be the containing type // I1 operator |(I1 x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(12, 17), // (17,24): error CS0563: One of the parameters of a binary operator must be the containing type // static I1 operator |(I1 x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(17, 24), // (22,20): error CS8930: Explicit implementation of a user-defined operator 'I5.operator |(I1, int)' must be declared static // I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("I5.operator " + op + "(I1, int)").WithLocation(22, 20), // (22,20): error CS0539: 'I5.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I5.operator " + op + "(I1, int)").WithLocation(22, 20), // (27,27): error CS0539: 'I6.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I6.operator " + op + "(I1, int)").WithLocation(27, 27), // (32,33): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // abstract static I1 operator |(I1 x, int y); Diagnostic(badAbstractSignatureError, op).WithLocation(32, 33), // (42,16): error CS0563: One of the parameters of a binary operator must be the containing type // T operator |(T x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(42, 16), // (47,23): error CS0563: One of the parameters of a binary operator must be the containing type // static T operator |(T x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(47, 23), // (57,30): error CS0539: 'I12<T>.operator |(T, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static T I11<T>.operator |(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I12<T>.operator " + op + "(T, int)").WithLocation(57, 30), // (62,39): error CS0106: The modifier 'abstract' is not valid for this item // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(62, 39), // (62,39): error CS0501: 'I13<T>.operator |(T, int)' must declare a body because it is not marked abstract, extern, or partial // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I13<T>.operator " + op + "(T, int)").WithLocation(62, 39), // (62,39): error CS0539: 'I13<T>.operator |(T, int)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I13<T>.operator " + op + "(T, int)").WithLocation(62, 39), // (67,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(67, 36), // (67,36): error CS0501: 'I14.operator |(I1, int)' must declare a body because it is not marked abstract, extern, or partial // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I14.operator " + op + "(I1, int)").WithLocation(67, 36), // (67,36): error CS0539: 'I14.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I14.operator " + op + "(I1, int)").WithLocation(67, 36) }; if (op is "==" or "!=") { expected = expected.Concat( new[] { // (12,17): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // I1 operator ==(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(12, 17), // (17,24): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static I1 operator ==(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(17, 24), // (42,16): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // T operator ==(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(42, 16), // (47,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static T operator ==(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(47, 23), } ).ToArray(); } else { expected = expected.Concat( new[] { // (12,17): error CS0558: User-defined operator 'I3.operator |(I1, int)' must be declared static and public // I1 operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I3.operator " + op + "(I1, int)").WithLocation(12, 17), // (42,16): error CS0558: User-defined operator 'I8<T>.operator |(T, int)' must be declared static and public // T operator |(T x, int y) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I8<T>.operator " + op + "(T, int)").WithLocation(42, 16) } ).ToArray(); } compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify(expected); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_04([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public interface I2<T> where T : I2<T> { abstract static T operator " + op + @"(T x); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static Test2 operator " + op + @"(Test2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15), // (14,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator +(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(14, 33), // (19,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator +(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(19, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public interface I2<T> where T : I2<T> { abstract static T operator " + op + @"(T x, int y); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static Test2 operator " + op + @"(Test2 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15), // (14,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator +(I1 x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(14, 33), // (19,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator +(T x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(19, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_05([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static Test1 operator " + op + @"(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (2,12): error CS8929: 'Test1.operator +(Test1)' cannot implement interface member 'I1<Test1>.operator +(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1)", "I1<Test1>.operator " + op + "(Test1)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (2,12): error CS8929: 'Test1.operator +(Test1)' cannot implement interface member 'I1<Test1>.operator +(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1)", "I1<Test1>.operator " + op + "(Test1)", "Test1").WithLocation(2, 12), // (9,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator +(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_05([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static Test1 operator " + op + @"(Test1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (2,12): error CS8929: 'Test1.operator >>(Test1, int)' cannot implement interface member 'I1<Test1>.operator >>(Test1, int)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1, int)", "I1<Test1>.operator " + op + "(Test1, int)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (2,12): error CS8929: 'Test1.operator >>(Test1, int)' cannot implement interface member 'I1<Test1>.operator >>(Test1, int)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1, int)", "I1<Test1>.operator " + op + "(Test1, int)", "Test1").WithLocation(2, 12), // (9,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator >>(T x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_06([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator +(I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_06([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator +(I1 x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_07([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } " + typeKeyword + @" C : I1<C> { public static C operator " + op + @"(C x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("C C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_07([CombinatorialValues("true", "false")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static bool operator " + op + @"(T x); } partial " + typeKeyword + @" C : I1<C> { public static bool operator " + op + @"(C x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1<T> where T : I1<T> { abstract static bool operator " + matchingOp + @"(T x); } partial " + typeKeyword + @" C { public static bool operator " + matchingOp + @"(C x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("System.Boolean C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_07([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() partial " + typeKeyword + @" C : I1<C> { public static C operator " + op + @"(C x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + matchingOp + @"(T x, int y); } partial " + typeKeyword + @" C { public static C operator " + matchingOp + @"(C x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.Equal(matchingOp is null ? 1 : 2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("C C." + opName + "(C x, System.Int32 y)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_08([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } " + typeKeyword + @" C : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal("default", node.ToString()); Assert.Equal("I1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("I1 C.I1." + opName + "(I1 x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("I1 C.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_08([CombinatorialValues("true", "false")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1 { abstract static bool operator " + op + @"(I1 x); } partial " + typeKeyword + @" C : I1 { static bool I1.operator " + op + @"(I1 x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1 { abstract static bool operator " + matchingOp + @"(I1 x); } partial " + typeKeyword + @" C { static bool I1.operator " + matchingOp + @"(I1 x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", node.ToString()); Assert.Equal("System.Boolean", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("System.Boolean C.I1." + opName + "(I1 x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers(opName).OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("System.Boolean C.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_08([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } partial " + typeKeyword + @" C : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator " + matchingOp + @"(I1 x, int y); } partial " + typeKeyword + @" C { static I1 I1.operator " + matchingOp + @"(I1 x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", node.ToString()); Assert.Equal("I1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("I1 C.I1." + opName + "(I1 x, System.Int32 y)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers(opName).OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(matchingOp is null ? 1 : 2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("I1 C.I1." + opName + "(I1 x, System.Int32 y)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_09([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public class C2 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_09([CombinatorialValues("true", "false")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public partial interface I1 { abstract static bool operator " + op + @"(I1 x); } public partial class C2 : I1 { static bool I1.operator " + op + @"(I1 x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1 { abstract static bool operator " + matchingOp + @"(I1 x); } public partial class C2 { static bool I1.operator " + matchingOp + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Boolean C2.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_09([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public partial interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public partial class C2 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator " + matchingOp + @"(I1 x, int y); } public partial class C2 { static I1 I1.operator " + matchingOp + @"(I1 x, int y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2.I1." + opName + "(I1 x, System.Int32 y)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_10([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x) cil managed { .override method class I1 I1::" + opName + @"(class I1) IL_0000: ldnull IL_0001: ret } .method public hidebysig static specialname class I1 " + opName + @" (class I1 x) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static specialname class I1 " + opName + @" (class I1 x) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Equal(MethodKind.UserDefinedOperator, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C1.I1." + opName + "(I1 x)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2." + opName + "(I1 x)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_10([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x, int32 y) cil managed { .override method class I1 I1::" + opName + @"(class I1, int32) IL_0000: ldnull IL_0001: ret } .method public hidebysig static specialname class I1 " + opName + @" (class I1 x, int32 y) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static specialname class I1 " + opName + @" (class I1 x, int32 y) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Equal(MethodKind.UserDefinedOperator, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C1.I1." + opName + "(I1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2." + opName + "(I1 x, System.Int32 y)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_11([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname virtual static class I1 " + opName + @" ( class I1 x ) cil managed { IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,27): error CS0539: 'C1.operator ~(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator ~(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C1.operator " + op + "(I1)").WithLocation(4, 27) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("I1 I1." + opName + "(I1 x)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_11([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,27): error CS0539: 'C1.operator <(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator <(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C1.operator " + op + "(I1, int)").WithLocation(4, 27) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("I1 I1." + opName + "(I1 x, System.Int32 y)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_12([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x ) cil managed { } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x) cil managed { .override method class I1 I1::" + opName + @"(class I1) IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.operator ~(I1)' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.operator " + op + "(I1)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_12([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x, int32 y) cil managed { .override method class I1 I1::" + opName + @"(class I1, int32) IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.operator /(I1, int)' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.operator " + op + "(I1, int)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_13([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public class C2 : C1, I1<C2> { } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); } public partial class C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var i1 = c2.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.False(c2M01.HasSpecialName); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.False(c1M01.HasRuntimeSpecialName); Assert.True(c1M01.HasSpecialName); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.True(c2M01.HasSpecialName); Assert.Equal("C2 C1." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1<C2>." + opName + "(C2, C1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C2 C1." + opName + @"(C2, C1)"" IL_0007: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_14([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static !T modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static C1 operator " + op + @"(C1 x) => default; } class C2 : I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("C1 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("C1 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("C1 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("C2 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""C1 C1." + opName + @"(C1)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_14([CombinatorialValues("true", "false")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static bool modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static bool operator " + op + @"(C1 x) => default; public static bool operator " + (op == "true" ? "false" : "true") + @"(C1 x) => default; } class C2 : I1<C2> { static bool I1<C2>.operator " + op + @"(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("System.Boolean modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("System.Boolean C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("System.Boolean C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("System.Boolean modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""bool C1." + opName + @"(C1)"" IL_0006: ret } "); } private static string MatchingBinaryOperator(string op) { return op switch { "<" => ">", ">" => "<", "<=" => ">=", ">=" => "<=", "==" => "!=", "!=" => "==", _ => null }; } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_14([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static !T modopt(I1`1) " + opName + @" ( !T x, int32 y ) cil managed { } } "; string matchingOp = MatchingBinaryOperator(op); string additionalMethods = ""; if (matchingOp is object) { additionalMethods = @" public static C1 operator " + matchingOp + @"(C1 x, int y) => default; "; } var source1 = @" #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() class C1 : I1<C1> { public static C1 operator " + op + @"(C1 x, int y) => default; " + additionalMethods + @" } class C2 : I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x, int y) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("C1 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("C1 C1." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("C1 C1." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("C2 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x, System.Int32 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1, int)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C1 C1." + opName + @"(C1, int)"" IL_0007: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_15([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public partial class C2 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M02 = c3.BaseType().GetMembers("I1." + opName).OfType<MethodSymbol>().Single(); Assert.Equal("I1 C2.I1." + opName + "(I1 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Fact] public void ImplementAbstractStaticUnaryTrueFalseOperator_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static bool operator true(I1 x); abstract static bool operator false(I1 x); } public partial class C2 : I1 { static bool I1.operator true(I1 x) => default; static bool I1.operator false(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("op_True").OfType<MethodSymbol>().Single(); var m02 = c3.Interfaces().Single().GetMembers("op_False").OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMembers("I1.op_True").OfType<MethodSymbol>().Single(); Assert.Equal("System.Boolean C2.I1.op_True(I1 x)", c2M01.ToTestDisplayString()); Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); var c2M02 = c3.BaseType().GetMembers("I1.op_False").OfType<MethodSymbol>().Single(); Assert.Equal("System.Boolean C2.I1.op_False(I1 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_15([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); abstract static T operator " + op + @"(T x, C2 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public partial class C2 : C1, I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x, C2 y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); abstract static T operator " + matchingOp + @"(T x, C2 y); } public partial class C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } public partial class C2 { static C2 I1<C2>.operator " + matchingOp + @"(C2 x, C2 y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().First(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C2 C1." + opName + "(C2 x, C1 y)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().ElementAt(1); var c2M02 = c3.BaseType().GetMembers("I1<C2>." + opName).OfType<MethodSymbol>().First(); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C2 y)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_16([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A new implicit implementation is properly considered. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 : I1<C2> { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public partial class C2 : C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); } public partial class C1 : I1<C2> { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } public partial class C2 : C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1<C2>." + opName + "(C2, C1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C2 C2." + opName + @"(C2, C1)"" IL_0007: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C2 C2." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C2 C3.I1<C2>." + opName + "(C2 x, C1 y)", c3M01.ToTestDisplayString()); Assert.Equal(m01, c3M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_18([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, U y) => default; "; var nonGeneric = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, int y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> { public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, U y) => default; public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>." + opName + "(C1<T, U> x, U y)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>." + opName + "(C1<T, U> x, U y)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_20([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // Same as ImplementAbstractStaticBinaryOperator_18 only implementation is explicit in source. var generic = @" static C1<T, U> I1<C1<T, U>, U>.operator " + op + @"(C1<T, U> x, U y) => default; "; var nonGeneric = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, int y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> : I1<C1<T, U>, U> { public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, int y) => default; static C1<T, U> I1<C1<T, U>, U>.operator " + matchingOp + @"(C1<T, U> x, U y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>.I1<C1<T, U>, U>." + opName + "(C1<T, U> x, U y)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_22([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implicit implementation is in an intermediate base. var generic = @" public static C11<T, U> operator " + op + @"(C11<T, U> x, C1<T, U> y) => default; "; var nonGeneric = @" public static C11<T, U> operator " + op + @"(C11<T, int> x, C1<T, U> y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T, U> : C1<T, U>, I1<C11<T, U>, C1<T, U>> { } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> { public static C11<T, U> operator " + matchingOp + @"(C11<T, U> x, C1<T, U> y) => default; public static C11<T, U> operator " + matchingOp + @"(C11<T, int> x, C1<T, U> y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C11<int, int>, I1<C11<int, int>, C1<int, int>> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "C11<T, U> C11<T, U>.I1<C11<T, U>, C1<T, U>>." + opName + "(C11<T, U> x, C1<T, U> y)" : "C11<T, U> C1<T, U>." + opName + "(C11<T, U> x, C1<T, U> y)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } class C1 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } class C2 : I1 { private static I1 I1.operator " + op + @"(I1 x) => default; } class C3 : I1 { protected static I1 I1.operator " + op + @"(I1 x) => default; } class C4 : I1 { internal static I1 I1.operator " + op + @"(I1 x) => default; } class C5 : I1 { protected internal static I1 I1.operator " + op + @"(I1 x) => default; } class C6 : I1 { private protected static I1 I1.operator " + op + @"(I1 x) => default; } class C7 : I1 { public static I1 I1.operator " + op + @"(I1 x) => default; } class C8 : I1 { static partial I1 I1.operator " + op + @"(I1 x) => default; } class C9 : I1 { async static I1 I1.operator " + op + @"(I1 x) => default; } class C10 : I1 { unsafe static I1 I1.operator " + op + @"(I1 x) => default; } class C11 : I1 { static readonly I1 I1.operator " + op + @"(I1 x) => default; } class C12 : I1 { extern static I1 I1.operator " + op + @"(I1 x); } class C13 : I1 { abstract static I1 I1.operator " + op + @"(I1 x) => default; } class C14 : I1 { virtual static I1 I1.operator " + op + @"(I1 x) => default; } class C15 : I1 { sealed static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.WRN_ExternMethodNoImplementation or (int)ErrorCode.ERR_OpTFRetType or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (16,35): error CS0106: The modifier 'private' is not valid for this item // private static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private").WithLocation(16, 35), // (22,37): error CS0106: The modifier 'protected' is not valid for this item // protected static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected").WithLocation(22, 37), // (28,36): error CS0106: The modifier 'internal' is not valid for this item // internal static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("internal").WithLocation(28, 36), // (34,46): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected internal").WithLocation(34, 46), // (40,45): error CS0106: The modifier 'private protected' is not valid for this item // private protected static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private protected").WithLocation(40, 45), // (46,34): error CS0106: The modifier 'public' is not valid for this item // public static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("public").WithLocation(46, 34), // (52,12): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // static partial I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(52, 12), // (58,33): error CS0106: The modifier 'async' is not valid for this item // async static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("async").WithLocation(58, 33), // (70,36): error CS0106: The modifier 'readonly' is not valid for this item // static readonly I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("readonly").WithLocation(70, 36), // (82,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(82, 36), // (88,35): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("virtual").WithLocation(88, 35), // (94,34): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("sealed").WithLocation(94, 34) ); } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } struct C1 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C2 : I1 { private static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C3 : I1 { protected static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C4 : I1 { internal static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C5 : I1 { protected internal static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C6 : I1 { private protected static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C7 : I1 { public static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C8 : I1 { static partial I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C9 : I1 { async static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C10 : I1 { unsafe static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C11 : I1 { static readonly I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C12 : I1 { extern static I1 I1.operator " + op + @"(I1 x, int y); } struct C13 : I1 { abstract static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C14 : I1 { virtual static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C15 : I1 { sealed static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.WRN_ExternMethodNoImplementation or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (16,35): error CS0106: The modifier 'private' is not valid for this item // private static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private").WithLocation(16, 35), // (22,37): error CS0106: The modifier 'protected' is not valid for this item // protected static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected").WithLocation(22, 37), // (28,36): error CS0106: The modifier 'internal' is not valid for this item // internal static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("internal").WithLocation(28, 36), // (34,46): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected internal").WithLocation(34, 46), // (40,45): error CS0106: The modifier 'private protected' is not valid for this item // private protected static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private protected").WithLocation(40, 45), // (46,34): error CS0106: The modifier 'public' is not valid for this item // public static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("public").WithLocation(46, 34), // (52,12): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // static partial I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(52, 12), // (58,33): error CS0106: The modifier 'async' is not valid for this item // async static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("async").WithLocation(58, 33), // (70,36): error CS0106: The modifier 'readonly' is not valid for this item // static readonly I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("readonly").WithLocation(70, 36), // (82,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(82, 36), // (88,35): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("virtual").WithLocation(88, 35), // (94,34): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("sealed").WithLocation(94, 34) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1<T> where T : struct { abstract static I1<T> operator " + op + @"(I1<T> x); } class C1 { static I1<int> I1<int>.operator " + op + @"(I1<int> x) => default; } class C2 : I1<C2> { static I1<C2> I1<C2>.operator " + op + @"(I1<C2> x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OpTFRetType or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (9,20): error CS0540: 'C1.I1<int>.operator -(I1<int>)': containing type does not implement interface 'I1<int>' // static I1<int> I1<int>.operator -(I1<int> x) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<int>").WithArguments("C1.I1<int>.operator " + op + "(I1<int>)", "I1<int>").WithLocation(9, 20), // (12,7): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // class C2 : I1<C2> Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 7), // (14,19): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 19), // (14,35): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, op).WithArguments("I1<T>", "T", "C2").WithLocation(14, 35), // (14,44): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("I1<T>", "T", "C2").WithLocation(14, 44 + op.Length - 1) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1<T> where T : class { abstract static I1<T> operator " + op + @"(I1<T> x, int y); } struct C1 { static I1<string> I1<string>.operator " + op + @"(I1<string> x, int y) => default; } struct C2 : I1<C2> { static I1<C2> I1<C2>.operator " + op + @"(I1<C2> x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (9,23): error CS0540: 'C1.I1<string>.operator %(I1<string>, int)': containing type does not implement interface 'I1<string>' // static I1<string> I1<string>.operator %(I1<string> x, int y) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<string>").WithArguments("C1.I1<string>.operator " + op + "(I1<string>, int)", "I1<string>").WithLocation(9, 23), // (12,8): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // struct C2 : I1<C2> Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 8), // (14,19): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 19), // (14,35): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, op).WithArguments("I1<T>", "T", "C2").WithLocation(14, 35), // (14,44): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "x").WithArguments("I1<T>", "T", "C2").WithLocation(14, 44 + op.Length - 1) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public int M01 { get; set; } } " + typeKeyword + @" C3 : I1 { static int M01 { get; set; } } " + typeKeyword + @" C4 : I1 { int I1.M01 { get; set; } } " + typeKeyword + @" C5 : I1 { public static long M01 { get; set; } } " + typeKeyword + @" C6 : I1 { static long I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,12): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 12), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'int'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,20): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static long I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 20) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract int M01 { get; set; } } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static int M01 { get; set; } } " + typeKeyword + @" C3 : I1 { int M01 { get; set; } } " + typeKeyword + @" C4 : I1 { static int I1.M01 { get; set; } } " + typeKeyword + @" C5 : I1 { public long M01 { get; set; } } " + typeKeyword + @" C6 : I1 { long I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,19): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 19), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'int'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,13): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // long I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 13) ); } [Fact] public void ImplementAbstractStaticProperty_03() { var source1 = @" public interface I1 { abstract static int M01 { get; set; } } interface I2 : I1 {} interface I3 : I1 { public virtual int M01 { get => 0; set{} } } interface I4 : I1 { static int M01 { get; set; } } interface I5 : I1 { int I1.M01 { get => 0; set{} } } interface I6 : I1 { static int I1.M01 { get => 0; set{} } } interface I7 : I1 { abstract static int M01 { get; set; } } interface I8 : I1 { abstract static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,24): warning CS0108: 'I3.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // public virtual int M01 { get => 0; set{} } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01", "I1.M01").WithLocation(12, 24), // (17,16): warning CS0108: 'I4.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // static int M01 { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01", "I1.M01").WithLocation(17, 16), // (22,12): error CS0539: 'I5.M01' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01").WithLocation(22, 12), // (27,19): error CS0106: The modifier 'static' is not valid for this item // static int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 19), // (27,19): error CS0539: 'I6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01").WithLocation(27, 19), // (32,25): warning CS0108: 'I7.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01", "I1.M01").WithLocation(32, 25), // (37,28): error CS0106: The modifier 'static' is not valid for this item // abstract static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 28), // (37,28): error CS0539: 'I8.M01' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01").WithLocation(37, 28) ); foreach (var m01 in compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers()) { Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } abstract static int M02 { get; set; } } "; var source2 = typeKeyword + @" Test: I1 { static int I1.M01 { get; set; } public static int M02 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,19): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 19) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,19): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 19), // (10,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 25), // (11,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int M02 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 25) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } "; var source2 = typeKeyword + @" Test1: I1 { public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.set' cannot implement interface member 'I1.M01.set' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.set", "I1.M01.set", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.get' cannot implement interface member 'I1.M01.get' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.get", "I1.M01.get", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.set' cannot implement interface member 'I1.M01.set' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.set", "I1.M01.set", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.get' cannot implement interface member 'I1.M01.get' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.get", "I1.M01.get", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12), // (9,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(9, 31), // (9,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(9, 36) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } "; var source2 = typeKeyword + @" Test1: I1 { static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,19): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 19) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,19): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 19), // (9,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(9, 31), // (9,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(9, 36) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C : I1 { public static int M01 { get => 0; set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.False(cM01Get.HasRuntimeSpecialName); Assert.True(cM01Get.HasSpecialName); Assert.Equal("System.Int32 C.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.False(cM01Set.HasRuntimeSpecialName); Assert.True(cM01Set.HasSpecialName); Assert.Equal("void C.M01.set", cM01Set.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticReadonlyProperty_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; } } " + typeKeyword + @" C : I1 { public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Null(m01.SetMethod); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C.M01.set", cM01Set.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C : I1 { static int I1.M01 { get => 0; set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.I1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.False(cM01Get.HasRuntimeSpecialName); Assert.True(cM01Get.HasSpecialName); Assert.Equal("System.Int32 C.I1.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.False(cM01Set.HasRuntimeSpecialName); Assert.True(cM01Set.HasSpecialName); Assert.Equal("void C.I1.M01.set", cM01Set.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<PropertySymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var cM01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.I1.M01 { get; set; }", cM01.ToTestDisplayString()); Assert.Same(cM01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(cM01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, cM01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, cM01.SetMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig specialname static int32 I1.get_M01 () cil managed { .override method int32 I1::get_M01() IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static void I1.set_M01 ( int32 'value' ) cil managed { .override method void I1::set_M01(int32) IL_0000: ret } .property instance int32 I1.M01() { .get int32 C1::I1.get_M01() .set void C1::I1.set_M01(int32) } .method public hidebysig specialname static int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname static void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 C1::get_M01() .set void C1::set_M01(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig specialname static int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname static void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 C2::get_M01() .set void C2::set_M01(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = (PropertySymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1.I1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.Same(c1M01.GetMethod, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c2.FindImplementationForInterfaceMember(m01.SetMethod)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c4.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c4.FindImplementationForInterfaceMember(m01.SetMethod)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (PropertySymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.Same(c2M01.GetMethod, c5.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c2M01.SetMethod, c5.FindImplementationForInterfaceMember(m01.SetMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticProperty_11() { // Ignore invalid metadata (non-abstract static virtual method). scenario1(); scenario2(); scenario3(); void scenario1() { var ilSource = @" .class interface public auto ansi abstract I1 { .method private hidebysig specialname static virtual int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static virtual void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,18): error CS0539: 'C1.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01").WithLocation(4, 18) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c.FindImplementationForInterfaceMember(m01)); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); } } void scenario2() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method private hidebysig specialname static virtual void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source2 = @" public class C1 : I1 { static int I1.M01 { get; } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, sourceSymbolValidator: validate2, symbolValidator: validate2, verify: Verification.Skipped).VerifyDiagnostics(); void validate2(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.I1.M01 { get; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.I1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(cM01.SetMethod); Assert.Null(c.FindImplementationForInterfaceMember(m01Set)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,29): error CS0550: 'C1.I1.M01.set' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("C1.I1.M01.set", "I1.M01").WithLocation(4, 29) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static int M01 { get; } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation5, sourceSymbolValidator: validate5, symbolValidator: validate5, verify: Verification.Skipped).VerifyDiagnostics(); void validate5(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } } var source6 = @" public class C1 : I1 { public static int M01 { set{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.get' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.get").WithLocation(2, 19) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); var source7 = @" public class C1 : I1 { static int I1.M01 { set{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.get' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.get").WithLocation(2, 19), // (4,18): error CS0551: Explicit interface implementation 'C1.I1.M01' is missing accessor 'I1.M01.get' // static int I1.M01 { set{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M01").WithArguments("C1.I1.M01", "I1.M01.get").WithLocation(4, 18), // (4,24): error CS0550: 'C1.I1.M01.set' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { set{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("C1.I1.M01.set", "I1.M01").WithLocation(4, 24) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); } void scenario3() { var ilSource = @" .class interface public auto ansi abstract I1 { .method private hidebysig specialname static virtual int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source2 = @" public class C1 : I1 { static int I1.M01 { set{} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, sourceSymbolValidator: validate2, symbolValidator: validate2, verify: Verification.Skipped).VerifyDiagnostics(); void validate2(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.I1.M01 { set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.I1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(cM01.GetMethod); Assert.Null(c.FindImplementationForInterfaceMember(m01Get)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,24): error CS0550: 'C1.I1.M01.get' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C1.I1.M01.get", "I1.M01").WithLocation(4, 24) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.SetMethod, c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static int M01 { set{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation5, sourceSymbolValidator: validate5, symbolValidator: validate5, verify: Verification.Skipped).VerifyDiagnostics(); void validate5(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } var source6 = @" public class C1 : I1 { public static int M01 { get; } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.set' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.set").WithLocation(2, 19) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); var source7 = @" public class C1 : I1 { static int I1.M01 { get; } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.set' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.set").WithLocation(2, 19), // (4,18): error CS0551: Explicit interface implementation 'C1.I1.M01' is missing accessor 'I1.M01.set' // static int I1.M01 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M01").WithArguments("C1.I1.M01", "I1.M01.set").WithLocation(4, 18), // (4,24): error CS0550: 'C1.I1.M01.get' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C1.I1.M01.get", "I1.M01").WithLocation(4, 24) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig specialname static int32 I1.get_M01 () cil managed { .override method int32 I1::get_M01() IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static void I1.set_M01 ( int32 'value' ) cil managed { .override method void I1::set_M01(int32) IL_0000: ret } .property instance int32 I1.M01() { .get int32 I2::I1.get_M01() .set void I2::I1.set_M01(int32) } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.SetMethod)); var i2M01 = i2.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, i2M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, i2M01.SetMethod.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticProperty_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static int M01 { get; set; } } class C1 { public static int M01 { get; set; } } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Get = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.GetMethod); var c2M01Set = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.SetMethod); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Get.MethodKind); Assert.False(c2M01Get.HasRuntimeSpecialName); Assert.False(c2M01Get.HasSpecialName); Assert.Equal("System.Int32 C2.I1.get_M01()", c2M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c2M01Get.ExplicitInterfaceImplementations.Single()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Set.MethodKind); Assert.False(c2M01Set.HasRuntimeSpecialName); Assert.False(c2M01Set.HasSpecialName); Assert.Equal("void C2.I1.set_M01(System.Int32 value)", c2M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c2M01Set.ExplicitInterfaceImplementations.Single()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c2M01); var c1M01 = module.GlobalNamespace.GetMember<PropertySymbol>("C1.M01"); var c1M01Get = c1M01.GetMethod; var c1M01Set = c1M01.SetMethod; Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c1M01Get.MethodKind); Assert.False(c1M01Get.HasRuntimeSpecialName); Assert.True(c1M01Get.HasSpecialName); Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c1M01Set.MethodKind); Assert.False(c1M01Set.HasRuntimeSpecialName); Assert.True(c1M01Set.HasSpecialName); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); } else { Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.PropertyGet, c2M01Get.MethodKind); Assert.False(c2M01Get.HasRuntimeSpecialName); Assert.True(c2M01Get.HasSpecialName); Assert.Same(c2M01.GetMethod, c2M01Get); Assert.Empty(c2M01Get.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.PropertySet, c2M01Set.MethodKind); Assert.False(c2M01Set.HasRuntimeSpecialName); Assert.True(c2M01Set.HasSpecialName); Assert.Same(c2M01.SetMethod, c2M01Set); Assert.Empty(c2M01Set.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.get_M01", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C1.M01.get"" IL_0005: ret } "); verifier.VerifyIL("C2.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.set"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticProperty_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void modopt(I1) set_M01 ( int32 modopt(I1) 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void modopt(I1) I1::set_M01(int32 modopt(I1)) } } .class interface public auto ansi abstract I2 { .method public hidebysig specialname abstract virtual static int32 modopt(I2) get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 modopt(I2) 'value' ) cil managed { } .property int32 modopt(I2) M01() { .get int32 modopt(I2) I2::get_M01() .set void I2::set_M01(int32 modopt(I2)) } } "; var source1 = @" class C1 : I1 { public static int M01 { get; set; } } class C2 : I1 { static int I1.M01 { get; set; } } class C3 : I2 { static int I2.M01 { get; set; } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = (PropertySymbol)c1.FindImplementationForInterfaceMember(m01); var c1M01Get = c1M01.GetMethod; var c1M01Set = c1M01.SetMethod; Assert.Equal("System.Int32 C1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Equal(MethodKind.PropertyGet, c1M01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", c1M01Get.ToTestDisplayString()); Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Same(c1M01Get, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Equal(MethodKind.PropertySet, c1M01Set.MethodKind); Assert.Equal("void C1.M01.set", c1M01Set.ToTestDisplayString()); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Same(m01.GetMethod, c1M01Get.ExplicitInterfaceImplementations.Single()); c1M01Set = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Set.MethodKind); Assert.Equal("void modopt(I1) C1.I1.set_M01(System.Int32 modopt(I1) value)", c1M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c1M01Set.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); } else { Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); Assert.Same(c1M01Set, c1.FindImplementationForInterfaceMember(m01.SetMethod)); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Get = c2M01.GetMethod; var c2M01Set = c2M01.SetMethod; Assert.Equal("System.Int32 C2.I1.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c2M01Get.MethodKind); Assert.Equal("System.Int32 C2.I1.M01.get", c2M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c2M01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Get, c2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c2M01Set.MethodKind); Assert.Equal("void modopt(I1) C2.I1.M01.set", c2M01Set.ToTestDisplayString()); Assert.Equal("System.Int32 modopt(I1) value", c2M01Set.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.SetMethod, c2M01Set.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Set, c2.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(c2M01, c2.GetMembers().OfType<PropertySymbol>().Single()); Assert.Equal(2, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var c3 = module.GlobalNamespace.GetTypeMember("C3"); m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c3M01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); var c3M01Get = c3M01.GetMethod; var c3M01Set = c3M01.SetMethod; Assert.Equal("System.Int32 modopt(I2) C3.I2.M01 { get; set; }", c3M01.ToTestDisplayString()); Assert.True(c3M01.IsStatic); Assert.False(c3M01.IsAbstract); Assert.False(c3M01.IsVirtual); Assert.Same(m01, c3M01.ExplicitInterfaceImplementations.Single()); Assert.True(c3M01Get.IsStatic); Assert.False(c3M01Get.IsAbstract); Assert.False(c3M01Get.IsVirtual); Assert.False(c3M01Get.IsMetadataVirtual()); Assert.False(c3M01Get.IsMetadataFinal); Assert.False(c3M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c3M01Get.MethodKind); Assert.Equal("System.Int32 modopt(I2) C3.I2.M01.get", c3M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c3M01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(c3M01Get, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.True(c3M01Set.IsStatic); Assert.False(c3M01Set.IsAbstract); Assert.False(c3M01Set.IsVirtual); Assert.False(c3M01Set.IsMetadataVirtual()); Assert.False(c3M01Set.IsMetadataFinal); Assert.False(c3M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c3M01Set.MethodKind); Assert.Equal("void C3.I2.M01.set", c3M01Set.ToTestDisplayString()); Assert.Equal("System.Int32 modopt(I2) value", c3M01Set.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.SetMethod, c3M01Set.ExplicitInterfaceImplementations.Single()); Assert.Same(c3M01Set, c3.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(c3M01, c3.GetMembers().OfType<PropertySymbol>().Single()); Assert.Equal(2, c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); } verifier.VerifyIL("C1.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.set"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStatiProperty_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static int M01 { get; set; } abstract static int M02 { get; set; } } public class C1 { public static int M01 { get; set; } } public class C2 : C1, I1 { static int I1.M02 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<PropertySymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<PropertySymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<PropertySymbol>("M01"); Assert.Equal("System.Int32 C1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); var c1M01Get = c1M01.GetMethod; Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); var c1M01Set = c1M01.SetMethod; Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01Get = c3.FindImplementationForInterfaceMember(m01.GetMethod); Assert.Equal("System.Int32 C2.I1.get_M01()", c2M01Get.ToTestDisplayString()); var c2M01Set = c3.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal("void C2.I1.set_M01(System.Int32 value)", c2M01Set.ToTestDisplayString()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c3.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<PropertySymbol>().Single(); var c2M02 = c3.BaseType().GetMember<PropertySymbol>("I1.M02"); Assert.Equal("System.Int32 C2.I1.M02 { get; set; }", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c2M02.GetMethod, c3.FindImplementationForInterfaceMember(m02.GetMethod)); Assert.Same(c2M02.SetMethod, c3.FindImplementationForInterfaceMember(m02.SetMethod)); } } [Fact] public void ImplementAbstractStaticProperty_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1 : I1 { public static int M01 { get; set; } } public class C2 : C1 { new public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.get_M01", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C2.M01.get"" IL_0005: ret } "); verifier.VerifyIL("C3.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.set"" IL_0006: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c2M01 = c3.BaseType().GetMember<PropertySymbol>("M01"); var c2M01Get = c2M01.GetMethod; var c2M01Set = c2M01.SetMethod; Assert.Equal("System.Int32 C2.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.Empty(c2M01Get.ExplicitInterfaceImplementations); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); Assert.Empty(c2M01Set.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); // Forwarding methods for accessors aren't tied to a property Assert.Null(c3M01); var c3M01Get = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.GetMethod); Assert.Equal("System.Int32 C3.I1.get_M01()", c3M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c3M01Get.ExplicitInterfaceImplementations.Single()); var c3M01Set = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal("void C3.I1.set_M01(System.Int32 value)", c3M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c3M01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c2M01Get, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c2M01Set, c3.FindImplementationForInterfaceMember(m01.SetMethod)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_19(bool genericFirst) { // An "ambiguity" in implicit/explicit implementation declared in generic base class. var generic = @" public static T M01 { get; set; } "; var nonGeneric = @" static int I1.M01 { get; set; } "; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<PropertySymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1<T>.I1.M01 { get; set; }", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_20(bool genericFirst) { // Same as ImplementAbstractStaticProperty_19 only interface is generic too. var generic = @" static T I1<T>.M01 { get; set; } "; var nonGeneric = @" public static int M01 { get; set; } "; var source1 = @" public interface I1<T> { abstract static T M01 { get; set; } } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<PropertySymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("T C1<T>.I1<T>.M01 { get; set; }", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public event System.Action M01; } " + typeKeyword + @" C3 : I1 { static event System.Action M01; } " + typeKeyword + @" C4 : I1 { event System.Action I1.M01 { add{} remove{}} } " + typeKeyword + @" C5 : I1 { public static event System.Action<int> M01; } " + typeKeyword + @" C6 : I1 { static event System.Action<int> I1.M01 { add{} remove{}} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,28): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.M01 { add{} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 28), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'Action'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "System.Action").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,40): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action<int> I1.M01 { add{} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 40) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract event System.Action M01; } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static event System.Action M01; } " + typeKeyword + @" C3 : I1 { event System.Action M01; } " + typeKeyword + @" C4 : I1 { static event System.Action I1.M01 { add{} remove{} } } " + typeKeyword + @" C5 : I1 { public event System.Action<int> M01; } " + typeKeyword + @" C6 : I1 { event System.Action<int> I1.M01 { add{} remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,35): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 35), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'Action'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "System.Action").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,33): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action<int> I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 33) ); } [Fact] public void ImplementAbstractStaticEvent_03() { var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract static event System.Action M01; } interface I2 : I1 {} interface I3 : I1 { public virtual event System.Action M01 { add{} remove{} } } interface I4 : I1 { static event System.Action M01; } interface I5 : I1 { event System.Action I1.M01 { add{} remove{} } } interface I6 : I1 { static event System.Action I1.M01 { add{} remove{} } } interface I7 : I1 { abstract static event System.Action M01; } interface I8 : I1 { abstract static event System.Action I1.M01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,40): warning CS0108: 'I3.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // public virtual event System.Action M01 { add{} remove{} } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01", "I1.M01").WithLocation(12, 40), // (17,32): warning CS0108: 'I4.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // static event System.Action M01; Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01", "I1.M01").WithLocation(17, 32), // (22,28): error CS0539: 'I5.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01").WithLocation(22, 28), // (27,35): error CS0106: The modifier 'static' is not valid for this item // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 35), // (27,35): error CS0539: 'I6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01").WithLocation(27, 35), // (32,41): warning CS0108: 'I7.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // abstract static event System.Action M01; Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01", "I1.M01").WithLocation(32, 41), // (37,44): error CS0106: The modifier 'static' is not valid for this item // abstract static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 44), // (37,44): error CS0539: 'I8.M01' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static event System.Action I1.M01; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01").WithLocation(37, 44) ); foreach (var m01 in compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers()) { Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; abstract static event System.Action M02; } "; var source2 = typeKeyword + @" Test: I1 { static event System.Action I1.M01 { add{} remove => throw null; } public static event System.Action M02; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,35): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static event System.Action I1.M01 { add{} remove => throw null; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 35), // (5,39): warning CS0067: The event 'Test.M02' is never used // public static event System.Action M02; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "M02").WithArguments("Test.M02").WithLocation(5, 39) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,35): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static event System.Action I1.M01 { add{} remove => throw null; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 35), // (5,39): warning CS0067: The event 'Test.M02' is never used // public static event System.Action M02; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "M02").WithArguments("Test.M02").WithLocation(5, 39), // (10,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 41), // (11,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action M02; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } "; var source2 = typeKeyword + @" Test1: I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.remove' cannot implement interface member 'I1.M01.remove' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.remove", "I1.M01.remove", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.add' cannot implement interface member 'I1.M01.add' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.add", "I1.M01.add", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.remove' cannot implement interface member 'I1.M01.remove' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.remove", "I1.M01.remove", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.add' cannot implement interface member 'I1.M01.add' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.add", "I1.M01.add", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12), // (9,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } "; var source2 = typeKeyword + @" Test1: I1 { static event System.Action I1.M01 { add => throw null; remove => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static event System.Action I1.M01 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 35) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static event System.Action I1.M01 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 35), // (9,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C : I1 { public static event System.Action M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; var m01Remove = m01.RemoveMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.False(cM01Add.HasRuntimeSpecialName); Assert.True(cM01Add.HasSpecialName); Assert.Equal("void C.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.False(cM01Remove.HasRuntimeSpecialName); Assert.True(cM01Remove.HasSpecialName); Assert.Equal("void C.M01.remove", cM01Remove.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Add.ExplicitInterfaceImplementations); Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C : I1 { static event System.Action I1.M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; var m01Remove = m01.RemoveMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C.I1.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.False(cM01Add.HasRuntimeSpecialName); Assert.True(cM01Add.HasSpecialName); Assert.Equal("void C.I1.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.False(cM01Remove.HasRuntimeSpecialName); Assert.True(cM01Remove.HasSpecialName); Assert.Equal("void C.I1.M01.remove", cM01Remove.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static event System.Action M01; } public class C1 { public static event System.Action M01 { add => throw null; remove {} } } public class C2 : C1, I1 { static event System.Action I1.M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<EventSymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var cM01 = (EventSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C2.I1.M01", cM01.ToTestDisplayString()); Assert.Same(cM01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(cM01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, cM01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, cM01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig specialname static void I1.add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::add_M01(class [mscorlib]System.Action) IL_0000: ret } .method private hidebysig specialname static void I1.remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::remove_M01(class [mscorlib]System.Action) IL_0000: ret } .event [mscorlib]System.Action I1.M01 { .addon void C1::I1.add_M01(class [mscorlib]System.Action) .removeon void C1::I1.remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void C1::add_M01(class [mscorlib]System.Action) .removeon void C1::remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig specialname static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void C2::add_M01(class [mscorlib]System.Action) .removeon void C2::remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c1M01 = (EventSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C1.I1.M01", c1M01.ToTestDisplayString()); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c2.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c4.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c4.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (EventSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C2.M01", c2M01.ToTestDisplayString()); Assert.Same(c2M01.AddMethod, c5.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c2M01.RemoveMethod, c5.FindImplementationForInterfaceMember(m01.RemoveMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticEvent_11() { // Ignore invalid metadata (non-abstract static virtual method). scenario1(); scenario2(); scenario3(); void scenario1() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname static virtual void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static virtual void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,34): error CS0539: 'C1.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c.FindImplementationForInterfaceMember(m01)); Assert.Null(c.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c.FindImplementationForInterfaceMember(m01.RemoveMethod)); } } void scenario2() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname static virtual void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { add {} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add {} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C1.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.Equal("void C1.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.Equal("void C1.M01.remove", cM01Remove.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.RemoveMethod)); if (module is PEModuleSymbol) { Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01Add.ExplicitInterfaceImplementations); } Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,46): error CS0550: 'C1.I1.M01.remove' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "remove").WithArguments("C1.I1.M01.remove", "I1.M01").WithLocation(4, 46) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static event System.Action M01 { add{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { add{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation5.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source6 = @" public class C1 : I1 { public static event System.Action M01 { remove{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.add' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.add").WithLocation(2, 19), // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source7 = @" public class C1 : I1 { static event System.Action I1.M01 { remove{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.add' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.add").WithLocation(2, 19), // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34), // (4,40): error CS0550: 'C1.I1.M01.remove' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "remove").WithArguments("C1.I1.M01.remove", "I1.M01").WithLocation(4, 40) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } void scenario3() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname static virtual void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { remove {} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add {} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var m01Remove = m01.RemoveMethod; Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C1.M01", cM01.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.Equal("void C1.M01.remove", cM01Remove.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.Equal("void C1.M01.add", cM01Add.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.AddMethod)); if (module is PEModuleSymbol) { Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Add.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,40): error CS0550: 'C1.I1.M01.add' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "add").WithArguments("C1.I1.M01.add", "I1.M01").WithLocation(4, 40) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static event System.Action M01 { remove{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation5.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); var source6 = @" public class C1 : I1 { public static event System.Action M01 { add{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.remove' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.remove").WithLocation(2, 19), // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source7 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.remove' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.remove").WithLocation(2, 19), // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34), // (4,40): error CS0550: 'C1.I1.M01.add' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "add").WithArguments("C1.I1.M01.add", "I1.M01").WithLocation(4, 40) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig specialname static void I1.add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::add_M01(class [mscorlib]System.Action) IL_0000: ret } .method private hidebysig specialname static void I1.remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::remove_M01(class [mscorlib]System.Action) IL_0000: ret } .event [mscorlib]System.Action I1.M01 { .addon void I2::I1.add_M01(class [mscorlib]System.Action) .removeon void I2::I1.remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.RemoveMethod)); var i2M01 = i2.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, i2M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, i2M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticEvent_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static event System.Action M01; } class C1 { public static event System.Action M01 { add => throw null; remove{} } } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Add = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.AddMethod); var c2M01Remove = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Add.MethodKind); Assert.False(c2M01Add.HasRuntimeSpecialName); Assert.False(c2M01Add.HasSpecialName); Assert.Equal("void C2.I1.add_M01(System.Action value)", c2M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c2M01Add.ExplicitInterfaceImplementations.Single()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Remove.MethodKind); Assert.False(c2M01Remove.HasRuntimeSpecialName); Assert.False(c2M01Remove.HasSpecialName); Assert.Equal("void C2.I1.remove_M01(System.Action value)", c2M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c2M01Remove.ExplicitInterfaceImplementations.Single()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c2M01); var c1M01 = module.GlobalNamespace.GetMember<EventSymbol>("C1.M01"); var c1M01Add = c1M01.AddMethod; var c1M01Remove = c1M01.RemoveMethod; Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c1M01Add.MethodKind); Assert.False(c1M01Add.HasRuntimeSpecialName); Assert.True(c1M01Add.HasSpecialName); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c1M01Remove.MethodKind); Assert.False(c1M01Remove.HasRuntimeSpecialName); Assert.True(c1M01Remove.HasSpecialName); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); } else { Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Equal("event System.Action C1.M01", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.EventAdd, c2M01Add.MethodKind); Assert.False(c2M01Add.HasRuntimeSpecialName); Assert.True(c2M01Add.HasSpecialName); Assert.Same(c2M01.AddMethod, c2M01Add); Assert.Empty(c2M01Add.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.EventRemove, c2M01Remove.MethodKind); Assert.False(c2M01Remove.HasRuntimeSpecialName); Assert.True(c2M01Remove.HasSpecialName); Assert.Same(c2M01.RemoveMethod, c2M01Remove); Assert.Empty(c2M01Remove.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C2.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.remove"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticEvent_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action`1<int32 modopt(I1)> 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action`1<int32 modopt(I1)> 'value' ) cil managed { } .event class [mscorlib]System.Action`1<int32 modopt(I1)> M01 { .addon void I1::add_M01(class [mscorlib]System.Action`1<int32 modopt(I1)>) .removeon void I1::remove_M01(class [mscorlib]System.Action`1<int32 modopt(I1)>) } } .class interface public auto ansi abstract I2 { .method public hidebysig specialname abstract virtual static void add_M02 ( class [mscorlib]System.Action modopt(I1) 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void modopt(I2) remove_M02 ( class [mscorlib]System.Action 'value' ) cil managed { } .event class [mscorlib]System.Action M02 { .addon void I2::add_M02(class [mscorlib]System.Action modopt(I1)) .removeon void modopt(I2) I2::remove_M02(class [mscorlib]System.Action) } } "; var source1 = @" class C1 : I1 { public static event System.Action<int> M01 { add => throw null; remove{} } } class C2 : I1 { static event System.Action<int> I1.M01 { add => throw null; remove{} } } #pragma warning disable CS0067 // The event 'C3.M02' is never used class C3 : I2 { public static event System.Action M02; } class C4 : I2 { static event System.Action I2.M02 { add => throw null; remove{} } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); var c1M01Add = c1M01.AddMethod; var c1M01Remove = c1M01.RemoveMethod; Assert.Equal("event System.Action<System.Int32> C1.M01", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Equal(MethodKind.EventAdd, c1M01Add.MethodKind); Assert.Equal("void C1.M01.add", c1M01Add.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32> value", c1M01Add.Parameters.Single().ToTestDisplayString()); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c1M01Remove.MethodKind); Assert.Equal("void C1.M01.remove", c1M01Remove.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32> value", c1M01Remove.Parameters.Single().ToTestDisplayString()); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { c1M01Add = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Add.MethodKind); Assert.Equal("void C1.I1.add_M01(System.Action<System.Int32 modopt(I1)> value)", c1M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c1M01Add.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); c1M01Remove = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Remove.MethodKind); Assert.Equal("void C1.I1.remove_M01(System.Action<System.Int32 modopt(I1)> value)", c1M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c1M01Remove.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); // Forwarding methods aren't tied to an event Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01Add, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01Remove, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Add = c2M01.AddMethod; var c2M01Remove = c2M01.RemoveMethod; Assert.Equal("event System.Action<System.Int32 modopt(I1)> C2.I1.M01", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c2M01Add.MethodKind); Assert.Equal("void C2.I1.M01.add", c2M01Add.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32 modopt(I1)> value", c2M01Add.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.AddMethod, c2M01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Add, c2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c2M01Remove.MethodKind); Assert.Equal("void C2.I1.M01.remove", c2M01Remove.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32 modopt(I1)> value", c2M01Remove.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c2M01Remove.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Remove, c2.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(c2M01, c2.GetMembers().OfType<EventSymbol>().Single()); Assert.Equal(2, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m02 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c3M02 = c3.GetMembers().OfType<EventSymbol>().Single(); var c3M02Add = c3M02.AddMethod; var c3M02Remove = c3M02.RemoveMethod; Assert.Equal("event System.Action C3.M02", c3M02.ToTestDisplayString()); Assert.Empty(c3M02.ExplicitInterfaceImplementations); Assert.True(c3M02.IsStatic); Assert.False(c3M02.IsAbstract); Assert.False(c3M02.IsVirtual); Assert.Equal(MethodKind.EventAdd, c3M02Add.MethodKind); Assert.Equal("void C3.M02.add", c3M02Add.ToTestDisplayString()); Assert.Equal("System.Action value", c3M02Add.Parameters.Single().ToTestDisplayString()); Assert.Empty(c3M02Add.ExplicitInterfaceImplementations); Assert.True(c3M02Add.IsStatic); Assert.False(c3M02Add.IsAbstract); Assert.False(c3M02Add.IsVirtual); Assert.False(c3M02Add.IsMetadataVirtual()); Assert.False(c3M02Add.IsMetadataFinal); Assert.False(c3M02Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c3M02Remove.MethodKind); Assert.Equal("void C3.M02.remove", c3M02Remove.ToTestDisplayString()); Assert.Equal("System.Void", c3M02Remove.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Empty(c3M02Remove.ExplicitInterfaceImplementations); Assert.True(c3M02Remove.IsStatic); Assert.False(c3M02Remove.IsAbstract); Assert.False(c3M02Remove.IsVirtual); Assert.False(c3M02Remove.IsMetadataVirtual()); Assert.False(c3M02Remove.IsMetadataFinal); Assert.False(c3M02Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { c3M02Add = (MethodSymbol)c3.FindImplementationForInterfaceMember(m02.AddMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c3M02Add.MethodKind); Assert.Equal("void C3.I2.add_M02(System.Action modopt(I1) value)", c3M02Add.ToTestDisplayString()); Assert.Same(m02.AddMethod, c3M02Add.ExplicitInterfaceImplementations.Single()); Assert.True(c3M02Add.IsStatic); Assert.False(c3M02Add.IsAbstract); Assert.False(c3M02Add.IsVirtual); Assert.False(c3M02Add.IsMetadataVirtual()); Assert.False(c3M02Add.IsMetadataFinal); Assert.False(c3M02Add.IsMetadataNewSlot()); c3M02Remove = (MethodSymbol)c3.FindImplementationForInterfaceMember(m02.RemoveMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c3M02Remove.MethodKind); Assert.Equal("void modopt(I2) C3.I2.remove_M02(System.Action value)", c3M02Remove.ToTestDisplayString()); Assert.Same(m02.RemoveMethod, c3M02Remove.ExplicitInterfaceImplementations.Single()); Assert.True(c3M02Remove.IsStatic); Assert.False(c3M02Remove.IsAbstract); Assert.False(c3M02Remove.IsVirtual); Assert.False(c3M02Remove.IsMetadataVirtual()); Assert.False(c3M02Remove.IsMetadataFinal); Assert.False(c3M02Remove.IsMetadataNewSlot()); // Forwarding methods aren't tied to an event Assert.Null(c3.FindImplementationForInterfaceMember(m02)); } else { Assert.Same(c3M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c3M02Add, c3.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.Same(c3M02Remove, c3.FindImplementationForInterfaceMember(m02.RemoveMethod)); } var c4 = module.GlobalNamespace.GetTypeMember("C4"); var c4M02 = (EventSymbol)c4.FindImplementationForInterfaceMember(m02); var c4M02Add = c4M02.AddMethod; var c4M02Remove = c4M02.RemoveMethod; Assert.Equal("event System.Action C4.I2.M02", c4M02.ToTestDisplayString()); // Signatures of accessors are lacking custom modifiers due to https://github.com/dotnet/roslyn/issues/53390. Assert.True(c4M02.IsStatic); Assert.False(c4M02.IsAbstract); Assert.False(c4M02.IsVirtual); Assert.Same(m02, c4M02.ExplicitInterfaceImplementations.Single()); Assert.True(c4M02Add.IsStatic); Assert.False(c4M02Add.IsAbstract); Assert.False(c4M02Add.IsVirtual); Assert.False(c4M02Add.IsMetadataVirtual()); Assert.False(c4M02Add.IsMetadataFinal); Assert.False(c4M02Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c4M02Add.MethodKind); Assert.Equal("void C4.I2.M02.add", c4M02Add.ToTestDisplayString()); Assert.Equal("System.Action value", c4M02Add.Parameters.Single().ToTestDisplayString()); Assert.Equal("System.Void", c4M02Add.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Same(m02.AddMethod, c4M02Add.ExplicitInterfaceImplementations.Single()); Assert.Same(c4M02Add, c4.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.True(c4M02Remove.IsStatic); Assert.False(c4M02Remove.IsAbstract); Assert.False(c4M02Remove.IsVirtual); Assert.False(c4M02Remove.IsMetadataVirtual()); Assert.False(c4M02Remove.IsMetadataFinal); Assert.False(c4M02Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c4M02Remove.MethodKind); Assert.Equal("void C4.I2.M02.remove", c4M02Remove.ToTestDisplayString()); Assert.Equal("System.Action value", c4M02Remove.Parameters.Single().ToTestDisplayString()); Assert.Equal("System.Void", c4M02Remove.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Same(m02.RemoveMethod, c4M02Remove.ExplicitInterfaceImplementations.Single()); Assert.Same(c4M02Remove, c4.FindImplementationForInterfaceMember(m02.RemoveMethod)); Assert.Same(c4M02, c4.GetMembers().OfType<EventSymbol>().Single()); Assert.Equal(2, c4.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); } verifier.VerifyIL("C1.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C1.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.remove"" IL_0006: ret } "); verifier.VerifyIL("C3.I2.add_M02", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C3.M02.add"" IL_0006: ret } "); verifier.VerifyIL("C3.I2.remove_M02", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C3.M02.remove"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticEvent_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static event System.Action M01; abstract static event System.Action M02; } public class C1 { public static event System.Action M01 { add => throw null; remove{} } } public class C2 : C1, I1 { static event System.Action I1.M02 { add => throw null; remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<EventSymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<EventSymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<EventSymbol>("M01"); Assert.Equal("event System.Action C1.M01", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); var c1M01Add = c1M01.AddMethod; Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); var c1M01Remove = c1M01.RemoveMethod; Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01Add = c3.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal("void C2.I1.add_M01(System.Action value)", c2M01Add.ToTestDisplayString()); var c2M01Remove = c3.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal("void C2.I1.remove_M01(System.Action value)", c2M01Remove.ToTestDisplayString()); // Forwarding methods for accessors aren't tied to an event Assert.Null(c3.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<EventSymbol>().Single(); var c2M02 = c3.BaseType().GetMember<EventSymbol>("I1.M02"); Assert.Equal("event System.Action C2.I1.M02", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c2M02.AddMethod, c3.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.Same(c2M02.RemoveMethod, c3.FindImplementationForInterfaceMember(m02.RemoveMethod)); } } [Fact] public void ImplementAbstractStaticEvent_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static event System.Action M01; } public class C1 : I1 { public static event System.Action M01 { add{} remove => throw null; } } public class C2 : C1 { new public static event System.Action M01 { add{} remove => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C3.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.remove"" IL_0006: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<EventSymbol>("M01"); var c2M01Add = c2M01.AddMethod; var c2M01Remove = c2M01.RemoveMethod; Assert.Equal("event System.Action C2.M01", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.Empty(c2M01Add.ExplicitInterfaceImplementations); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); Assert.Empty(c2M01Remove.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (EventSymbol)c3.FindImplementationForInterfaceMember(m01); // Forwarding methods for accessors aren't tied to an event Assert.Null(c3M01); var c3M01Add = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal("void C3.I1.add_M01(System.Action value)", c3M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c3M01Add.ExplicitInterfaceImplementations.Single()); var c3M01Remove = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal("void C3.I1.remove_M01(System.Action value)", c3M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c3M01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c2M01Add, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c2M01Remove, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_19(bool genericFirst) { // An "ambiguity" in implicit/explicit implementation declared in generic base class. var generic = @" public static event System.Action<T> M01 { add{} remove{} } "; var nonGeneric = @" static event System.Action<int> I1.M01 { add{} remove{} } "; var source1 = @" public interface I1 { abstract static event System.Action<int> M01; } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<EventSymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action<System.Int32> C1<T>.I1.M01", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_20(bool genericFirst) { // Same as ImplementAbstractStaticEvent_19 only interface is generic too. var generic = @" static event System.Action<T> I1<T>.M01 { add{} remove{} } "; var nonGeneric = @" public static event System.Action<int> M01 { add{} remove{} } "; var source1 = @" public interface I1<T> { abstract static event System.Action<T> M01; } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<EventSymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action<T> C1<T>.I1<T>.M01", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } private static string ConversionOperatorName(string op) => op switch { "implicit" => WellKnownMemberNames.ImplicitConversionName, "explicit" => WellKnownMemberNames.ExplicitConversionName, _ => throw TestExceptionUtilities.UnexpectedValue(op) }; [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = ConversionOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public " + op + @" operator int(C2 x) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static " + op + @" operator int(C3 x) => throw null; } " + typeKeyword + @" C4 : I1<C4> { " + op + @" I1<C4>.operator int(C4 x) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static " + op + @" operator long(C5 x) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static " + op + @" I1<C6>.operator long(C6 x) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static int " + opName + @"(C7 x) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static int I1<C8>." + opName + @"(C8 x) => throw null; } public interface I2<T> where T : I2<T> { abstract static int " + opName + @"(T x); } " + typeKeyword + @" C9 : I2<C9> { public static " + op + @" operator int(C9 x) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static " + op + @" I2<C10>.operator int(C10 x) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.explicit operator int(C1)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>." + op + " operator int(C1)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.explicit operator int(C2)'. 'C2.explicit operator int(C2)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>." + op + " operator int(C2)", "C2." + op + " operator int(C2)").WithLocation(12, 10), // (14,30): error CS0558: User-defined operator 'C2.explicit operator int(C2)' must be declared static and public // public explicit operator int(C2 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("C2." + op + " operator int(C2)").WithLocation(14, 30), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.explicit operator int(C3)'. 'C3.explicit operator int(C3)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>." + op + " operator int(C3)", "C3." + op + " operator int(C3)").WithLocation(18, 10), // (20,30): error CS0558: User-defined operator 'C3.explicit operator int(C3)' must be declared static and public // static explicit operator int(C3 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("C3." + op + " operator int(C3)").WithLocation(20, 30), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.explicit operator int(C4)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>." + op + " operator int(C4)").WithLocation(24, 10), // (26,30): error CS8930: Explicit implementation of a user-defined operator 'C4.explicit operator int(C4)' must be declared static // explicit I1<C4>.operator int(C4 x) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, "int").WithArguments("C4." + op + " operator int(C4)").WithLocation(26, 30), // (26,30): error CS0539: 'C4.explicit operator int(C4)' in explicit interface declaration is not found among members of the interface that can be implemented // explicit I1<C4>.operator int(C4 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C4." + op + " operator int(C4)").WithLocation(26, 30), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.explicit operator int(C5)'. 'C5.explicit operator long(C5)' cannot implement 'I1<C5>.explicit operator int(C5)' because it does not have the matching return type of 'int'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>." + op + " operator int(C5)", "C5." + op + " operator long(C5)", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.explicit operator int(C6)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>." + op + " operator int(C6)").WithLocation(36, 10), // (38,37): error CS0539: 'C6.explicit operator long(C6)' in explicit interface declaration is not found among members of the interface that can be implemented // static explicit I1<C6>.operator long(C6 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "long").WithArguments("C6." + op + " operator long(C6)").WithLocation(38, 37), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.explicit operator int(C7)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>." + op + " operator int(C7)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.explicit operator int(C8)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>." + op + " operator int(C8)").WithLocation(48, 10), // (50,23): error CS0539: 'C8.op_Explicit(C8)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C8>.op_Explicit(C8 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8)").WithLocation(50, 23), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_Explicit(C9)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_Explicit(C10)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10)").WithLocation(65, 11), // (67,38): error CS0539: 'C10.explicit operator int(C10)' in explicit interface declaration is not found among members of the interface that can be implemented // static explicit I2<C10>.operator int(C10 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C10." + op + " operator int(C10)").WithLocation(67, 38) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_03([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } interface I2<T> : I1<T> where T : I1<T> {} interface I3<T> : I1<T> where T : I1<T> { " + op + @" operator int(T x) => default; } interface I4<T> : I1<T> where T : I1<T> { static " + op + @" operator int(T x) => default; } interface I5<T> : I1<T> where T : I1<T> { " + op + @" I1<T>.operator int(T x) => default; } interface I6<T> : I1<T> where T : I1<T> { static " + op + @" I1<T>.operator int(T x) => default; } interface I7<T> : I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public interface I11<T> where T : I11<T> { abstract static " + op + @" operator int(T x); } interface I8<T> : I11<T> where T : I8<T> { " + op + @" operator int(T x) => default; } interface I9<T> : I11<T> where T : I9<T> { static " + op + @" operator int(T x) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static " + op + @" operator int(T x); } interface I12<T> : I11<T> where T : I12<T> { static " + op + @" I11<T>.operator int(T x) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static " + op + @" I11<T>.operator int(T x); } interface I14<T> : I1<T> where T : I1<T> { abstract static " + op + @" I1<T>.operator int(T x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,23): error CS0556: User-defined conversion must convert to or from the enclosing type // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(12, 23), // (12,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(12, 23), // (17,30): error CS0556: User-defined conversion must convert to or from the enclosing type // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(17, 30), // (17,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(17, 30), // (22,29): error CS8930: Explicit implementation of a user-defined operator 'I5<T>.implicit operator int(T)' must be declared static // implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, "int").WithArguments("I5<T>." + op + " operator int(T)").WithLocation(22, 29), // (22,29): error CS0539: 'I5<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I5<T>." + op + " operator int(T)").WithLocation(22, 29), // (27,36): error CS0539: 'I6<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I6<T>." + op + " operator int(T)").WithLocation(27, 36), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "int").WithLocation(32, 39), // (42,23): error CS0556: User-defined conversion must convert to or from the enclosing type // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(42, 23), // (42,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(42, 23), // (47,30): error CS0556: User-defined conversion must convert to or from the enclosing type // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(47, 30), // (47,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(47, 30), // (57,37): error CS0539: 'I12<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I11<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I12<T>." + op + " operator int(T)").WithLocation(57, 37), // (62,46): error CS0106: The modifier 'abstract' is not valid for this item // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(62, 46), // (62,46): error CS0501: 'I13<T>.implicit operator int(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "int").WithArguments("I13<T>." + op + " operator int(T)").WithLocation(62, 46), // (62,46): error CS0539: 'I13<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I13<T>." + op + " operator int(T)").WithLocation(62, 46), // (67,45): error CS0106: The modifier 'abstract' is not valid for this item // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(67, 45), // (67,45): error CS0501: 'I14<T>.implicit operator int(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "int").WithArguments("I14<T>." + op + " operator int(T)").WithLocation(67, 45), // (67,45): error CS0539: 'I14<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I14<T>." + op + " operator int(T)").WithLocation(67, 45) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_04([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I2<T> where T : I2<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1 : I2<Test1> { static " + op + @" I2<Test1>.operator int(Test1 x) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static " + op + @" operator int(Test2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,21): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static explicit I2<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I2<Test1>.").WithArguments("static abstract members in interfaces").WithLocation(4, 21) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,21): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static explicit I2<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I2<Test1>.").WithArguments("static abstract members in interfaces").WithLocation(4, 21), // (14,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(14, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_05([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static " + op + @" operator int(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.explicit operator int(Test1)' cannot implement interface member 'I1<Test1>.explicit operator int(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1." + op + " operator int(Test1)", "I1<Test1>." + op + " operator int(Test1)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.explicit operator int(Test1)' cannot implement interface member 'I1<Test1>.explicit operator int(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1." + op + " operator int(Test1)", "I1<Test1>." + op + " operator int(Test1)", "Test1").WithLocation(2, 12), // (9,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(9, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_06([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1 : I1<Test1> { static " + op + @" I1<Test1>.operator int(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,40): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static explicit I1<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 40) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,40): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static explicit I1<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 40), // (9,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(9, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_07([CombinatorialValues("implicit", "explicit")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); abstract static " + op + @" operator long(T x); } " + typeKeyword + @" C : I1<C> { public static " + op + @" operator long(C x) => default; public static " + op + @" operator int(C x) => default; } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = i1.GetMembers().OfType<MethodSymbol>().First(); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("System.Int32 C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } var m02 = i1.GetMembers().OfType<MethodSymbol>().ElementAt(1); var cM02 = (MethodSymbol)c.FindImplementationForInterfaceMember(m02); Assert.True(cM02.IsStatic); Assert.False(cM02.IsAbstract); Assert.False(cM02.IsVirtual); Assert.False(cM02.IsMetadataVirtual()); Assert.False(cM02.IsMetadataFinal); Assert.False(cM02.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, cM02.MethodKind); Assert.False(cM02.HasRuntimeSpecialName); Assert.True(cM02.HasSpecialName); Assert.Equal("System.Int64 C." + opName + "(C x)", cM02.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m02, cM02.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM02.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_08([CombinatorialValues("implicit", "explicit")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" interface I1<T> where T : I1<T> { abstract static " + op + @" operator C(T x); abstract static " + op + @" operator int(T x); } " + typeKeyword + @" C : I1<C> { static " + op + @" I1<C>.operator int(C x) => int.MaxValue; static " + op + @" I1<C>.operator C(C x) => default; } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal("default", node.ToString()); Assert.Equal("C", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<ConversionOperatorDeclarationSyntax>()); Assert.Equal("C C.I1<C>." + opName + "(C x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<MethodSymbol>().First(); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("C C.I1<C>." + opName + "(C x)", cM01.ToTestDisplayString()); Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); var m02 = c.Interfaces().Single().GetMembers().OfType<MethodSymbol>().ElementAt(1); var cM02 = (MethodSymbol)c.FindImplementationForInterfaceMember(m02); Assert.True(cM02.IsStatic); Assert.False(cM02.IsAbstract); Assert.False(cM02.IsVirtual); Assert.False(cM02.IsMetadataVirtual()); Assert.False(cM02.IsMetadataFinal); Assert.False(cM02.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM02.MethodKind); Assert.False(cM02.HasRuntimeSpecialName); Assert.False(cM02.HasSpecialName); Assert.Equal("System.Int32 C.I1<C>." + opName + "(C x)", cM02.ToTestDisplayString()); Assert.Equal(m02, cM02.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_09([CombinatorialValues("implicit", "explicit")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = ConversionOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.I1<C2>." + opName + "(C2 x)", cM01.ToTestDisplayString()); Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_10([CombinatorialValues("implicit", "explicit")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 " + opName + @" ( !T x ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements class I1`1<class C1> { .method private hidebysig static int32 'I1<C1>." + opName + @"' ( class C1 x ) cil managed { .override method int32 class I1`1<class C1>::" + opName + @"(!0) IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig static specialname int32 " + opName + @" ( class C1 x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2053 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: nop IL_0007: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements class I1`1<class C1> { .method public hidebysig static specialname int32 " + opName + @" ( class C1 x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1<C1> { } public class C5 : C2, I1<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Equal(MethodKind.Conversion, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2." + opName + "(C1 x)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.Conversion, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_11([CombinatorialValues("implicit", "explicit")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname virtual static int32 " + opName + @" ( !T x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } } "; var source1 = @" public class C1 : I1<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1<C1> { static " + op + @" I1<C1>.operator int(C1 x) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,37): error CS0539: 'C1.implicit operator int(C1)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I1<C1>.operator int(C1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C1." + op + " operator int(C1)").WithLocation(4, 37) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("System.Int32 I1<C1>." + opName + "(C1 x)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_12([CombinatorialValues("implicit", "explicit")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 " + opName + @" ( !T x ) cil managed { } } .class interface public auto ansi abstract I2`1<(class I1`1<!T>) T> implements class I1`1<!T> { .method private hidebysig static int32 'I1<!T>." + opName + @"' ( !T x ) cil managed { .override method int32 class I1`1<!T>::" + opName + @"(!0) IL_0000: ldc.i4.0 IL_0001: ret } } "; var source1 = @" public class C1 : I2<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1<C1>.explicit operator int(C1)' // public class C1 : I2<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C1>").WithArguments("C1", "I1<C1>." + op + " operator int(C1)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_13([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static " + op + @" operator C1<T>(T x); } public partial class C1<T> { public static " + op + @" operator C1<T>(T x) => default; } public class C2 : C1<C2>, I1<C2> { } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var i1 = c2.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.False(c2M01.HasSpecialName); Assert.Equal("C1<C2> C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.False(c1M01.HasRuntimeSpecialName); Assert.True(c1M01.HasSpecialName); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Conversion, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.True(c2M01.HasSpecialName); Assert.Equal("C1<C2> C1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1<C2>." + opName + "(C2)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""C1<C2> C1<C2>." + opName + @"(C2)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_14([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static " + op + @" operator int(C1 x) => default; } class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("System.Int32 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("System.Int32 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.Equal("System.Int32 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("System.Int32 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int C1." + opName + @"(C1)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_15([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static " + op + @" operator C1<T>(T x); abstract static " + op + @" operator T(int x); } public partial class C1<T> { public static " + op + @" operator C1<T>(T x) => default; } public class C2 : C1<C2>, I1<C2> { static " + op + @" I1<C2>.operator C2(int x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = ConversionOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().First(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C1<C2> C1<C2>." + opName + "(C2 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<C2> C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Equal(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().ElementAt(1); var c2M02 = c3.BaseType().GetMembers("I1<C2>." + opName).OfType<MethodSymbol>().First(); Assert.Equal("C2 C2.I1<C2>." + opName + "(System.Int32 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_18([CombinatorialValues("implicit", "explicit")] string op, bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static " + op + @" operator U(C1<T, U> x) => default; "; var nonGeneric = @" public static " + op + @" operator int(C1<T, U> x) => default; "; var source1 = @" public interface I1<T, U> where T : I1<T, U> { abstract static " + op + @" operator U(T x); } public class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>." + opName + "(C1<T, U> x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>." + opName + "(C1<T, U> x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_20([CombinatorialValues("implicit", "explicit")] string op, bool genericFirst) { // Same as ImplementAbstractStaticConversionOperator_18 only implementation is explicit in source. var generic = @" static " + op + @" I1<C1<T, U>, U>.operator U(C1<T, U> x) => default; "; var nonGeneric = @" public static " + op + @" operator int(C1<T, U> x) => default; "; var source1 = @" public interface I1<T, U> where T : I1<T, U> { abstract static " + op + @" operator U(T x); } public class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>.I1<C1<T, U>, U>." + opName + "(C1<T, U> x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class C1 : I1<C1> { static " + op + @" I1<C1>.operator int(C1 x) => default; } class C2 : I1<C2> { private static " + op + @" I1<C2>.operator int(C2 x) => default; } class C3 : I1<C3> { protected static " + op + @" I1<C3>.operator int(C3 x) => default; } class C4 : I1<C4> { internal static " + op + @" I1<C4>.operator int(C4 x) => default; } class C5 : I1<C5> { protected internal static " + op + @" I1<C5>.operator int(C5 x) => default; } class C6 : I1<C6> { private protected static " + op + @" I1<C6>.operator int(C6 x) => default; } class C7 : I1<C7> { public static " + op + @" I1<C7>.operator int(C7 x) => default; } class C9 : I1<C9> { async static " + op + @" I1<C9>.operator int(C9 x) => default; } class C10 : I1<C10> { unsafe static " + op + @" I1<C10>.operator int(C10 x) => default; } class C11 : I1<C11> { static readonly " + op + @" I1<C11>.operator int(C11 x) => default; } class C12 : I1<C12> { extern static " + op + @" I1<C12>.operator int(C12 x); } class C13 : I1<C13> { abstract static " + op + @" I1<C13>.operator int(C13 x) => default; } class C14 : I1<C14> { virtual static " + op + @" I1<C14>.operator int(C14 x) => default; } class C15 : I1<C15> { sealed static " + op + @" I1<C15>.operator int(C15 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.WRN_ExternMethodNoImplementation).Verify( // (16,45): error CS0106: The modifier 'private' is not valid for this item // private static explicit I1<C2>.operator int(C2 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("private").WithLocation(16, 45), // (22,47): error CS0106: The modifier 'protected' is not valid for this item // protected static explicit I1<C3>.operator int(C3 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("protected").WithLocation(22, 47), // (28,46): error CS0106: The modifier 'internal' is not valid for this item // internal static explicit I1<C4>.operator int(C4 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("internal").WithLocation(28, 46), // (34,56): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static explicit I1<C5>.operator int(C5 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("protected internal").WithLocation(34, 56), // (40,55): error CS0106: The modifier 'private protected' is not valid for this item // private protected static explicit I1<C6>.operator int(C6 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("private protected").WithLocation(40, 55), // (46,44): error CS0106: The modifier 'public' is not valid for this item // public static explicit I1<C7>.operator int(C7 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("public").WithLocation(46, 44), // (52,43): error CS0106: The modifier 'async' is not valid for this item // async static explicit I1<C9>.operator int(C9 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("async").WithLocation(52, 43), // (64,47): error CS0106: The modifier 'readonly' is not valid for this item // static readonly explicit I1<C11>.operator int(C11 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("readonly").WithLocation(64, 47), // (76,47): error CS0106: The modifier 'abstract' is not valid for this item // abstract static explicit I1<C13>.operator int(C13 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(76, 47), // (82,46): error CS0106: The modifier 'virtual' is not valid for this item // virtual static explicit I1<C14>.operator int(C14 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("virtual").WithLocation(82, 46), // (88,45): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit I1<C15>.operator int(C15 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(88, 45) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : struct, I1<T> { abstract static " + op + @" operator int(T x); } class C1 { static " + op + @" I1<int>.operator int(int x) => default; } class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,21): error CS0540: 'C1.I1<int>.implicit operator int(int)': containing type does not implement interface 'I1<int>' // static implicit I1<int>.operator int(int x) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<int>").WithArguments("C1.I1<int>." + op + " operator int(int)", "I1<int>").WithLocation(9, 21), // (9,21): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion from 'int' to 'I1<int>'. // static implicit I1<int>.operator int(int x) => default; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "I1<int>").WithArguments("I1<T>", "I1<int>", "T", "int").WithLocation(9, 21), // (12,7): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // class C2 : I1<C2> Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 7), // (14,21): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static implicit I1<C2>.operator int(C2 x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 21) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { string cast = (op == "explicit" ? "(int)" : ""); var source1 = @" interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); static int M02(I1<T> x) { return " + cast + @"x; } int M03(I1<T> y) { return " + cast + @"y; } } class Test<T> where T : I1<T> { static int MT1(I1<T> a) { return " + cast + @"a; } static void MT2() { _ = (System.Linq.Expressions.Expression<System.Func<T, int>>)((T b) => " + cast + @"b); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (8,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)x; Diagnostic(error, cast + "x").WithArguments("I1<T>", "int").WithLocation(8, 16), // (13,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)y; Diagnostic(error, cast + "y").WithArguments("I1<T>", "int").WithLocation(13, 16), // (21,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)a; Diagnostic(error, cast + "a").WithArguments("I1<T>", "int").WithLocation(21, 16), // (26,80): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Func<T, int>>)((T b) => (int)b); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, cast + "b").WithLocation(26, 80) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1 { abstract static implicit operator bool(I1 x); static void M02((int, C<I1>) x) { _ = x " + op + @" x; } void M03((int, C<I1>) y) { _ = y " + op + @" y; } } class Test { static void MT1((int, C<I1>) a) { _ = a " + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b " + op + @" b).ToString()); } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0552: 'I1.implicit operator bool(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator bool(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "bool").WithArguments("I1.implicit operator bool(I1)").WithLocation(4, 39), // (9,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = x == x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x " + op + " x").WithArguments("I1", "bool").WithLocation(9, 13), // (14,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = y == y; Diagnostic(ErrorCode.ERR_NoImplicitConv, "y " + op + " y").WithArguments("I1", "bool").WithLocation(14, 13), // (22,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = a == a; Diagnostic(ErrorCode.ERR_NoImplicitConv, "a " + op + " a").WithArguments("I1", "bool").WithLocation(22, 13), // (27,98): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(27, 98) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_03([CombinatorialValues("implicit", "explicit")] string op) { string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class Test { static int M02<T, U>(T x) where T : U where U : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int? M03<T, U>(T y) where T : U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"y; } static int? M04<T, U>(T? y) where T : struct, U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"y; } static int? M05<T, U>() where T : struct, U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"(T?)new T(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 23 (0x17) .maxstack 1 .locals init (int? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: newobj ""int?..ctor(int)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (T? V_0, int? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""int?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""int I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""int?..ctor(int)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 27 (0x1b) .maxstack 1 .locals init (int? V_0) IL_0000: nop IL_0001: call ""T System.Activator.CreateInstance<T>()"" IL_0006: constrained. ""T"" IL_000c: call ""int I1<T>." + metadataName + @"(T)"" IL_0011: newobj ""int?..ctor(int)"" IL_0016: stloc.0 IL_0017: br.s IL_0019 IL_0019: ldloc.0 IL_001a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""int I1<T>." + metadataName + @"(T)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""int I1<T>." + metadataName + @"(T)"" IL_000c: newobj ""int?..ctor(int)"" IL_0011: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (T? V_0, int? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""int?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""int I1<T>." + metadataName + @"(T)"" IL_0027: newobj ""int?..ctor(int)"" IL_002c: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 22 (0x16) .maxstack 1 IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: constrained. ""T"" IL_000b: call ""int I1<T>." + metadataName + @"(T)"" IL_0010: newobj ""int?..ctor(int)"" IL_0015: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().First(); Assert.Equal("return " + (needCast ? "(int)" : "") + @"x;", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return " + (needCast ? "(int)" : "") + @"x;') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 I1<T>." + metadataName + @"(T x)) (OperationKind.Conversion, Type: System.Int32" + (needCast ? "" : ", IsImplicit") + @") (Syntax: '" + (needCast ? "(int)" : "") + @"x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 I1<T>." + metadataName + @"(T x)) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool (T x); } class Test { static void M02<T, U>((int, C<T>) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_Implicit(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.0 IL_0032: pop IL_0033: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_Implicit(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.1 IL_0032: pop IL_0033: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_Implicit(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.0 IL_0031: pop IL_0032: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_Implicit(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.1 IL_0031: pop IL_0032: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_04([CombinatorialValues("implicit", "explicit")] string op) { bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = @" class Test { static int M02<T>(T x) where T : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,16): error CS8919: Target runtime doesn't support static abstract members in interfaces. // return (int)x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, (needCast ? "(int)" : "") + "x").WithLocation(6, 16) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(12, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool(T x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (21,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static implicit operator bool(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "bool").WithLocation(21, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_06([CombinatorialValues("implicit", "explicit")] string op) { bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = @" class Test { static int M02<T>(T x) where T : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,16): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // return x; Diagnostic(ErrorCode.ERR_FeatureInPreview, (needCast ? "(int)" : "") + "x").WithArguments("static abstract members in interfaces").WithLocation(6, 16) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(12, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool(T x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (21,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator bool(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "bool").WithArguments("abstract", "9.0", "preview").WithLocation(21, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_07([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_03 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } class Test { static T M02<T, U>(int x) where T : U where U : I1<T> { return " + (needCast ? "(T)" : "") + @"x; } static T? M03<T, U>(int y) where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"y; } static T? M04<T, U>(int? y) where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"y; } static T? M05<T, U>() where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"(T?)0; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(int)", @" { // Code size 23 (0x17) .maxstack 1 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: newobj ""T?..ctor(T)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (int? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool int?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly int int?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(int)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 23 (0x17) .maxstack 1 .locals init (T? V_0) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: newobj ""T?..ctor(T)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: newobj ""T?..ctor(T)"" IL_0011: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (int? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool int?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly int int?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""T I1<T>." + metadataName + @"(int)"" IL_0027: newobj ""T?..ctor(T)"" IL_002c: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: newobj ""T?..ctor(T)"" IL_0011: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().First(); Assert.Equal("return " + (needCast ? "(T)" : "") + @"x;", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return " + (needCast ? "(T)" : "") + @"x;') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: T I1<T>." + metadataName + @"(System.Int32 x)) (OperationKind.Conversion, Type: T" + (needCast ? "" : ", IsImplicit") + @") (Syntax: '" + (needCast ? "(T)" : "") + @"x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: T I1<T>." + metadataName + @"(System.Int32 x)) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_08([CombinatorialValues("implicit", "explicit")] string op) { // Don't look in interfaces of the effective base string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class C1<T> : I1<C1<T>> { static " + op + @" I1<C1<T>>.operator int(C1<T> x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int M03<T>(C1<T> y) where T : I1<C1<T>> { return " + (needCast ? "(int)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (16,16): error CS0030: Cannot convert type 'T' to 'int' // return (int)x; Diagnostic(error, (needCast ? "(int)" : "") + "x").WithArguments("T", "int").WithLocation(16, 16), // (21,16): error CS0030: Cannot convert type 'C1<T>' to 'int' // return (int)y; Diagnostic(error, (needCast ? "(int)" : "") + "y").WithArguments("C1<T>", "int").WithLocation(21, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_09([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_08 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } class C1<T> : I1<C1<T>> { static " + op + @" I1<C1<T>>.operator C1<T>(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1<T> { return " + (needCast ? "(T)" : "") + @"x; } static C1<T> M03<T>(int y) where T : I1<C1<T>> { return " + (needCast ? "(C1<T>)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (16,16): error CS0030: Cannot convert type 'int' to 'T' // return (T)x; Diagnostic(error, (needCast ? "(T)" : "") + "x").WithArguments("int", "T").WithLocation(16, 16), // (21,16): error CS0030: Cannot convert type 'int' to 'C1<T>' // return (C1<T>)y; Diagnostic(error, (needCast ? "(C1<T>)" : "") + "y").WithArguments("int", "C1<T>").WithLocation(21, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_10([CombinatorialValues("implicit", "explicit")] string op) { // Look in derived interfaces string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public interface I2<T> : I1<T> where T : I1<T> {} class Test { static int M02<T, U>(T x) where T : U where U : I2<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_11([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_10 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } public interface I2<T> : I1<T> where T : I1<T> {} class Test { static T M02<T, U>(int x) where T : U where U : I2<T> { return " + (needCast ? "(T)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_12([CombinatorialValues("implicit", "explicit")] string op) { // Ignore duplicate candidates string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T, U> where T : I1<T, U> where U : I1<T, U> { abstract static " + op + @" operator U(T x); } class Test { static U M02<T, U>(T x) where T : I1<T, U> where U : I1<T, U> { return " + (needCast ? "(U)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (U V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""U I1<T, U>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_13([CombinatorialValues("implicit", "explicit")] string op) { // Look in effective base string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public class C1<T> { public static " + op + @" operator int(C1<T> x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: call ""int C1<T>." + metadataName + @"(C1<T>)"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Fact] public void ConsumeAbstractConversionOperator_14() { // Same as ConsumeAbstractConversionOperator_13 only direction of conversion is flipped var source1 = @" public class C1<T> { public static explicit operator C1<T>(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1<T> { return (T)x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""C1<T> C1<T>.op_Explicit(int)"" IL_0007: unbox.any ""T"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_15([CombinatorialValues("implicit", "explicit")] string op) { // If there is a non-trivial class constraint, interfaces are not looked at. string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C1 : I1<C1> { public static " + op + @" operator int(C1 x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1, I1<C1> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: call ""int C1." + metadataName + @"(C1)"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Fact] public void ConsumeAbstractConversionOperator_16() { // Same as ConsumeAbstractConversionOperator_15 only direction of conversion is flipped var source1 = @" public interface I1<T> where T : I1<T> { abstract static explicit operator T(int x); } public class C1 : I1<C1> { public static explicit operator C1(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1, I1<C1> { return (T)x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""C1 C1.op_Explicit(int)"" IL_0007: unbox.any ""T"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_17([CombinatorialValues("implicit", "explicit")] string op) { // If there is a non-trivial class constraint, interfaces are not looked at. bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C1 { } class Test { static int M02<T, U>(T x) where T : U where U : C1, I1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int M03<T, U>(T y) where T : U where U : I1<T> { return " + (needCast ? "(int)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (15,16): error CS0030: Cannot convert type 'T' to 'int' // return (int)x; Diagnostic((op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv), (needCast ? "(int)" : "") + "x").WithArguments("T", "int").WithLocation(15, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_18([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_17 only direction of conversion is flipped bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } public class C1 { } class Test { static T M02<T, U>(int x) where T : U where U : C1, I1<T> { return " + (needCast ? "(T)" : "") + @"x; } static T M03<T, U>(int y) where T : U where U : I1<T> { return " + (needCast ? "(T)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (15,16): error CS0030: Cannot convert type 'int' to 'T' // return (T)x; Diagnostic((op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv), (needCast ? "(T)" : "") + "x").WithArguments("int", "T").WithLocation(15, 16) ); } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_01() { var source1 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } public class Derived : Base<int>, Interface<int, int> { } class YetAnother : Interface<int, int> { public static void Method(int i) { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var b = module.GlobalNamespace.GetTypeMember("Base"); var bI = b.Interfaces().Single(); var biMethods = bI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", biMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", biMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", biMethods[2].OriginalDefinition.ToTestDisplayString()); var bM1 = b.FindImplementationForInterfaceMember(biMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", bM1.ToTestDisplayString()); var bM2 = b.FindImplementationForInterfaceMember(biMethods[1]); Assert.Equal("void Base<T>.Method(T i)", bM2.ToTestDisplayString()); Assert.Same(bM2, b.FindImplementationForInterfaceMember(biMethods[2])); var bM1Impl = ((MethodSymbol)bM1).ExplicitInterfaceImplementations; var bM2Impl = ((MethodSymbol)bM2).ExplicitInterfaceImplementations; if (module is PEModuleSymbol) { Assert.Equal(biMethods[0], bM1Impl.Single()); Assert.Equal(2, bM2Impl.Length); Assert.Equal(biMethods[1], bM2Impl[0]); Assert.Equal(biMethods[2], bM2Impl[1]); } else { Assert.Empty(bM1Impl); Assert.Empty(bM2Impl); } var d = module.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Same(bM1, dM1.OriginalDefinition); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Same(bM2, dM2.OriginalDefinition); Assert.Same(bM2, d.FindImplementationForInterfaceMember(diMethods[2]).OriginalDefinition); } } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_02() { var source0 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); var source1 = @" public class Derived : Base<int>, Interface<int, int> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation0.EmitToImageReference() }); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var d = module.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", dM1.OriginalDefinition.ToTestDisplayString()); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Equal("void Base<T>.Method(T i)", dM2.OriginalDefinition.ToTestDisplayString()); Assert.Same(dM2, d.FindImplementationForInterfaceMember(diMethods[2])); var dM1Impl = ((MethodSymbol)dM1).ExplicitInterfaceImplementations; var dM2Impl = ((MethodSymbol)dM2).ExplicitInterfaceImplementations; Assert.Equal(diMethods[0], dM1Impl.Single()); Assert.Equal(2, dM2Impl.Length); Assert.Equal(diMethods[1], dM2Impl[0]); Assert.Equal(diMethods[2], dM2Impl[1]); } } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_03() { var source0 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateEmptyCompilation("").ToMetadataReference() }); compilation0.VerifyDiagnostics(); var source1 = @" public class Derived : Base<int>, Interface<int, int> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation0.ToMetadataReference() }); var d = compilation1.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.IsType<RetargetingNamedTypeSymbol>(dB.OriginalDefinition); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", dM1.OriginalDefinition.ToTestDisplayString()); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Equal("void Base<T>.Method(T i)", dM2.OriginalDefinition.ToTestDisplayString()); Assert.Equal(dM2, d.FindImplementationForInterfaceMember(diMethods[2])); var dM1Impl = ((MethodSymbol)dM1).ExplicitInterfaceImplementations; var dM2Impl = ((MethodSymbol)dM2).ExplicitInterfaceImplementations; Assert.Empty(dM1Impl); Assert.Empty(dM2Impl); } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_04() { var source2 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } class Other : Interface<int, int> { static void Interface<int, int>.Method(int i) { } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (9,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(9, 15), // (9,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(9, 15), // (11,37): warning CS0473: Explicit interface implementation 'Other.Interface<int, int>.Method(int)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // static void Interface<int, int>.Method(int i) { } Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Other.Interface<int, int>.Method(int)").WithLocation(11, 37) ); } [Fact] public void UnmanagedCallersOnly_01() { var source2 = @" using System.Runtime.InteropServices; public interface I1 { [UnmanagedCallersOnly] abstract static void M1(); [UnmanagedCallersOnly] abstract static int operator +(I1 x); [UnmanagedCallersOnly] abstract static int operator +(I1 x, I1 y); } public interface I2<T> where T : I2<T> { [UnmanagedCallersOnly] abstract static implicit operator int(T i); [UnmanagedCallersOnly] abstract static explicit operator T(int i); } "; var compilation2 = CreateCompilation(new[] { source2, UnmanagedCallersOnlyAttributeDefinition }, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static void M1(); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(6, 6), // (7,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static int operator +(I1 x); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 6), // (8,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static int operator +(I1 x, I1 y); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(8, 6), // (13,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static implicit operator int(T i); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(13, 6), // (14,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static explicit operator T(int i); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(14, 6) ); } [Fact] [WorkItem(54113, "https://github.com/dotnet/roslyn/issues/54113")] public void UnmanagedCallersOnly_02() { var ilSource = @" .class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72 69 74 65 64 00 ) .field public class [mscorlib]System.Type[] CallConvs .field public string EntryPoint .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void M1 () cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static int32 op_UnaryPlus ( class I1 x ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static int32 op_Addition ( class I1 x, class I1 y ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } } .class interface public auto ansi abstract I2`1<(class I2`1<!T>) T> { .method public hidebysig specialname abstract virtual static int32 op_Implicit ( !T i ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static !T op_Explicit ( int32 i ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } } "; var source1 = @" class Test { static void M02<T>(T x, T y) where T : I1 { T.M1(); _ = +x; _ = x + y; } static int M03<T>(T x) where T : I2<T> { _ = (T)x; return x; } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); // Conversions aren't flagged due to https://github.com/dotnet/roslyn/issues/54113. compilation1.VerifyDiagnostics( // (6,11): error CS0570: 'I1.M1()' is not supported by the language // T.M1(); Diagnostic(ErrorCode.ERR_BindToBogus, "M1").WithArguments("I1.M1()").WithLocation(6, 11), // (7,13): error CS0570: 'I1.operator +(I1)' is not supported by the language // _ = +x; Diagnostic(ErrorCode.ERR_BindToBogus, "+x").WithArguments("I1.operator +(I1)").WithLocation(7, 13), // (8,13): error CS0570: 'I1.operator +(I1, I1)' is not supported by the language // _ = x + y; Diagnostic(ErrorCode.ERR_BindToBogus, "x + y").WithArguments("I1.operator +(I1, I1)").WithLocation(8, 13) ); } [Fact] public void UnmanagedCallersOnly_03() { var source2 = @" using System.Runtime.InteropServices; public interface I1<T> where T : I1<T> { abstract static void M1(); abstract static int operator +(T x); abstract static int operator +(T x, T y); abstract static implicit operator int(T i); abstract static explicit operator T(int i); } class C : I1<C> { [UnmanagedCallersOnly] public static void M1() {} [UnmanagedCallersOnly] public static int operator +(C x) => 0; [UnmanagedCallersOnly] public static int operator +(C x, C y) => 0; [UnmanagedCallersOnly] public static implicit operator int(C i) => 0; [UnmanagedCallersOnly] public static explicit operator C(int i) => null; } "; var compilation2 = CreateCompilation(new[] { source2, UnmanagedCallersOnlyAttributeDefinition }, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (15,47): error CS8932: 'UnmanagedCallersOnly' method 'C.M1()' cannot implement interface member 'I1<C>.M1()' in type 'C' // [UnmanagedCallersOnly] public static void M1() {} Diagnostic(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, "M1").WithArguments("C.M1()", "I1<C>.M1()", "C").WithLocation(15, 47), // (16,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static int operator +(C x) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(16, 6), // (17,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static int operator +(C x, C y) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(17, 6), // (18,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static implicit operator int(C i) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(18, 6), // (19,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static explicit operator C(int i) => null; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(19, 6) ); } [Fact] public void UnmanagedCallersOnly_04() { var source2 = @" using System.Runtime.InteropServices; public interface I1<T> where T : I1<T> { abstract static void M1(); abstract static int operator +(T x); abstract static int operator +(T x, T y); abstract static implicit operator int(T i); abstract static explicit operator T(int i); } class C : I1<C> { [UnmanagedCallersOnly] static void I1<C>.M1() {} [UnmanagedCallersOnly] static int I1<C>.operator +(C x) => 0; [UnmanagedCallersOnly] static int I1<C>.operator +(C x, C y) => 0; [UnmanagedCallersOnly] static implicit I1<C>.operator int(C i) => 0; [UnmanagedCallersOnly] static explicit I1<C>.operator C(int i) => null; } "; var compilation2 = CreateCompilation(new[] { source2, UnmanagedCallersOnlyAttributeDefinition }, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (15,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static void I1<C>.M1() {} Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(15, 6), // (16,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static int I1<C>.operator +(C x) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(16, 6), // (17,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static int I1<C>.operator +(C x, C y) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(17, 6), // (18,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static implicit I1<C>.operator int(C i) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(18, 6), // (19,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static explicit I1<C>.operator C(int i) => null; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(19, 6) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class StaticAbstractMembersInInterfacesTests : CSharpTestBase { [Fact] public void MethodModifiers_01() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } private static void ValidateMethodModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<MethodSymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<MethodSymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<MethodSymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<MethodSymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<MethodSymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<MethodSymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<MethodSymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<MethodSymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<MethodSymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } [Fact] public void MethodModifiers_02() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_03() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_04() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_05() { var source1 = @" public interface I1 { abstract static void M01() ; virtual static void M02() ; sealed static void M03() ; override static void M04() ; abstract virtual static void M05() ; abstract sealed static void M06() ; abstract override static void M07() ; virtual sealed static void M08() ; virtual override static void M09() ; sealed override static void M10() ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static void M02() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 25), // (7,25): error CS0501: 'I1.M02()' must declare a body because it is not marked abstract, extern, or partial // virtual static void M02() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M02").WithArguments("I1.M02()").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (10,24): error CS0501: 'I1.M03()' must declare a body because it is not marked abstract, extern, or partial // sealed static void M03() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M03").WithArguments("I1.M03()").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static void M04() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 26), // (13,26): error CS0501: 'I1.M04()' must declare a body because it is not marked abstract, extern, or partial // override static void M04() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M04").WithArguments("I1.M04()").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (25,32): error CS0501: 'I1.M08()' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M08").WithArguments("I1.M08()").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static void M09() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 34), // (28,34): error CS0501: 'I1.M09()' must declare a body because it is not marked abstract, extern, or partial // virtual override static void M09() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M09").WithArguments("I1.M09()").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33), // (31,33): error CS0501: 'I1.M10()' must declare a body because it is not marked abstract, extern, or partial // sealed override static void M10() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M10").WithArguments("I1.M10()").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void MethodModifiers_06() { var source1 = @" public interface I1 { abstract static void M01() {} virtual static void M02() {} sealed static void M03() {} override static void M04() {} abstract virtual static void M05() {} abstract sealed static void M06() {} abstract override static void M07() {} virtual sealed static void M08() {} virtual override static void M09() {} sealed override static void M10() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static void M01() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (4,26): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static void M01() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static void M02() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static void M02() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static void M03() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static void M04() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static void M04() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (16,34): error CS0500: 'I1.M05()' cannot declare a body because it is marked abstract // abstract virtual static void M05() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M05").WithArguments("I1.M05()").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (19,33): error CS0500: 'I1.M06()' cannot declare a body because it is marked abstract // abstract sealed static void M06() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M06").WithArguments("I1.M06()").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static void M07() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static void M07() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (22,35): error CS0500: 'I1.M07()' cannot declare a body because it is marked abstract // abstract override static void M07() Diagnostic(ErrorCode.ERR_AbstractHasBody, "M07").WithArguments("I1.M07()").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static void M08() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static void M09() Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static void M09() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static void M09() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static void M10() Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static void M10() Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidateMethodModifiers_01(compilation1); } [Fact] public void SealedStaticConstructor_01() { var source1 = @" interface I1 { sealed static I1() {} } partial interface I2 { partial sealed static I2(); } partial interface I2 { partial static I2() {} } partial interface I3 { partial static I3(); } partial interface I3 { partial sealed static I3() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,19): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I1").WithArguments("sealed").WithLocation(4, 19), // (9,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I2(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(9, 5), // (9,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I2(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(9, 5), // (9,27): error CS0106: The modifier 'sealed' is not valid for this item // partial sealed static I2(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(9, 27), // (14,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I2() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(14, 5), // (14,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I2() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(14, 5), // (14,20): error CS0111: Type 'I2' already defines a member called 'I2' with the same parameter types // partial static I2() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I2").WithArguments("I2", "I2").WithLocation(14, 20), // (19,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I3(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(19, 5), // (19,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial static I3(); Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(19, 5), // (24,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(24, 5), // (24,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(24, 5), // (24,27): error CS0106: The modifier 'sealed' is not valid for this item // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(24, 27), // (24,27): error CS0111: Type 'I3' already defines a member called 'I3' with the same parameter types // partial sealed static I3() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I3").WithArguments("I3", "I3").WithLocation(24, 27) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); } [Fact] public void SealedStaticConstructor_02() { var source1 = @" partial interface I2 { sealed static partial I2(); } partial interface I2 { static partial I2() {} } partial interface I3 { static partial I3(); } partial interface I3 { sealed static partial I3() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,19): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // sealed static partial I2(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(4, 19), // (4,27): error CS0501: 'I2.I2()' must declare a body because it is not marked abstract, extern, or partial // sealed static partial I2(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I2").WithArguments("I2.I2()").WithLocation(4, 27), // (4,27): error CS0542: 'I2': member names cannot be the same as their enclosing type // sealed static partial I2(); Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I2").WithArguments("I2").WithLocation(4, 27), // (9,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I2() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(9, 12), // (9,20): error CS0542: 'I2': member names cannot be the same as their enclosing type // static partial I2() {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I2").WithArguments("I2").WithLocation(9, 20), // (9,20): error CS0111: Type 'I2' already defines a member called 'I2' with the same parameter types // static partial I2() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I2").WithArguments("I2", "I2").WithLocation(9, 20), // (9,20): error CS0161: 'I2.I2()': not all code paths return a value // static partial I2() {} Diagnostic(ErrorCode.ERR_ReturnExpected, "I2").WithArguments("I2.I2()").WithLocation(9, 20), // (14,12): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // static partial I3(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(14, 12), // (14,20): error CS0501: 'I3.I3()' must declare a body because it is not marked abstract, extern, or partial // static partial I3(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I3").WithArguments("I3.I3()").WithLocation(14, 20), // (14,20): error CS0542: 'I3': member names cannot be the same as their enclosing type // static partial I3(); Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I3").WithArguments("I3").WithLocation(14, 20), // (19,19): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(19, 19), // (19,27): error CS0542: 'I3': member names cannot be the same as their enclosing type // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "I3").WithArguments("I3").WithLocation(19, 27), // (19,27): error CS0111: Type 'I3' already defines a member called 'I3' with the same parameter types // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "I3").WithArguments("I3", "I3").WithLocation(19, 27), // (19,27): error CS0161: 'I3.I3()': not all code paths return a value // sealed static partial I3() {} Diagnostic(ErrorCode.ERR_ReturnExpected, "I3").WithArguments("I3.I3()").WithLocation(19, 27) ); } [Fact] public void AbstractStaticConstructor_01() { var source1 = @" interface I1 { abstract static I1(); } interface I2 { abstract static I2() {} } interface I3 { static I3(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "I1").WithArguments("abstract").WithLocation(4, 21), // (9,21): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I2() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("abstract").WithLocation(9, 21), // (14,12): error CS0501: 'I3.I3()' must declare a body because it is not marked abstract, extern, or partial // static I3(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "I3").WithArguments("I3.I3()").WithLocation(14, 12) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>(".cctor"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); } [Fact] public void PartialSealedStatic_01() { var source1 = @" partial interface I1 { sealed static partial void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Null(m01.PartialImplementationPart); } [Fact] public void PartialSealedStatic_02() { var source1 = @" partial interface I1 { sealed static partial void M01(); } partial interface I1 { sealed static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ValidatePartialSealedStatic_02(compilation1); } private static void ValidatePartialSealedStatic_02(CSharpCompilation compilation1) { compilation1.VerifyDiagnostics(); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialSealedStatic_03() { var source1 = @" partial interface I1 { static partial void M01(); } partial interface I1 { sealed static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ValidatePartialSealedStatic_02(compilation1); } [Fact] public void PartialSealedStatic_04() { var source1 = @" partial interface I1 { sealed static partial void M01(); } partial interface I1 { static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ValidatePartialSealedStatic_02(compilation1); } [Fact] public void PartialAbstractStatic_01() { var source1 = @" partial interface I1 { abstract static partial void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Null(m01.PartialImplementationPart); } [Fact] public void PartialAbstractStatic_02() { var source1 = @" partial interface I1 { abstract static partial void M01(); } partial interface I1 { abstract static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34), // (8,34): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(8, 34), // (8,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(8, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialAbstractStatic_03() { var source1 = @" partial interface I1 { abstract static partial void M01(); } partial interface I1 { static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(4, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PartialAbstractStatic_04() { var source1 = @" partial interface I1 { static partial void M01(); } partial interface I1 { abstract static partial void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,34): error CS0500: 'I1.M01()' cannot declare a body because it is marked abstract // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_AbstractHasBody, "M01").WithArguments("I1.M01()").WithLocation(8, 34), // (8,34): error CS0750: A partial method cannot have the 'abstract' modifier // abstract static partial void M01() {} Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M01").WithLocation(8, 34) ); var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("M01"); Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialDefinition()); Assert.Same(m01, m01.PartialImplementationPart.PartialDefinitionPart); m01 = m01.PartialImplementationPart; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.True(m01.IsPartialImplementation()); } [Fact] public void PrivateAbstractStatic_01() { var source1 = @" interface I1 { private abstract static void M01(); private abstract static bool P01 { get; } private abstract static event System.Action E01; private abstract static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS0621: 'I1.M01()': virtual or abstract members cannot be private // private abstract static void M01(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "M01").WithArguments("I1.M01()").WithLocation(4, 34), // (5,34): error CS0621: 'I1.P01': virtual or abstract members cannot be private // private abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "P01").WithArguments("I1.P01").WithLocation(5, 34), // (6,49): error CS0621: 'I1.E01': virtual or abstract members cannot be private // private abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_VirtualPrivate, "E01").WithArguments("I1.E01").WithLocation(6, 49), // (7,40): error CS0558: User-defined operator 'I1.operator +(I1)' must be declared static and public // private abstract static I1 operator+ (I1 x); Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 40) ); } [Fact] public void PropertyModifiers_01() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } private static void ValidatePropertyModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); { var m01 = i1.GetMember<PropertySymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<PropertySymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<PropertySymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<PropertySymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<PropertySymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<PropertySymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<PropertySymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<PropertySymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<PropertySymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<PropertySymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } { var m01 = i1.GetMember<PropertySymbol>("M01").GetMethod; Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<PropertySymbol>("M02").GetMethod; Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<PropertySymbol>("M03").GetMethod; Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<PropertySymbol>("M04").GetMethod; Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<PropertySymbol>("M05").GetMethod; Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<PropertySymbol>("M06").GetMethod; Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<PropertySymbol>("M07").GetMethod; Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<PropertySymbol>("M08").GetMethod; Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<PropertySymbol>("M09").GetMethod; Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<PropertySymbol>("M10").GetMethod; Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } } [Fact] public void PropertyModifiers_02() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 26), // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_03() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_04() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_05() { var source1 = @" public interface I1 { abstract static bool M01 { get ; } virtual static bool M02 { get ; } sealed static bool M03 { get ; } override static bool M04 { get ; } abstract virtual static bool M05 { get ; } abstract sealed static bool M06 { get ; } abstract override static bool M07 { get ; } virtual sealed static bool M08 { get ; } virtual override static bool M09 { get ; } sealed override static bool M10 { get ; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static bool M04 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void PropertyModifiers_06() { var source1 = @" public interface I1 { abstract static bool M01 { get => throw null; } virtual static bool M02 { get => throw null; } sealed static bool M03 { get => throw null; } override static bool M04 { get => throw null; } abstract virtual static bool M05 { get { throw null; } } abstract sealed static bool M06 { get => throw null; } abstract override static bool M07 { get => throw null; } virtual sealed static bool M08 { get => throw null; } virtual override static bool M09 { get => throw null; } sealed override static bool M10 { get => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 26), // (4,32): error CS0500: 'I1.M01.get' cannot declare a body because it is marked abstract // abstract static bool M01 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M01.get").WithLocation(4, 32), // (7,25): error CS0112: A static member cannot be marked as 'virtual' // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 25), // (7,25): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static bool M02 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 25), // (10,24): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static bool M03 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 24), // (13,26): error CS0106: The modifier 'override' is not valid for this item // override static bool M04 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 26), // (13,26): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static bool M04 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 26), // (16,34): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 34), // (16,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 34), // (16,40): error CS0500: 'I1.M05.get' cannot declare a body because it is marked abstract // abstract virtual static bool M05 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M05.get").WithLocation(16, 40), // (19,33): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 33), // (19,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 33), // (19,39): error CS0500: 'I1.M06.get' cannot declare a body because it is marked abstract // abstract sealed static bool M06 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M06.get").WithLocation(19, 39), // (22,35): error CS0106: The modifier 'override' is not valid for this item // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 35), // (22,41): error CS0500: 'I1.M07.get' cannot declare a body because it is marked abstract // abstract override static bool M07 { get Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("I1.M07.get").WithLocation(22, 41), // (25,32): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 32), // (25,32): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static bool M08 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 32), // (28,34): error CS0112: A static member cannot be marked as 'virtual' // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 34), // (28,34): error CS0106: The modifier 'override' is not valid for this item // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 34), // (28,34): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static bool M09 { get Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 34), // (31,33): error CS0106: The modifier 'override' is not valid for this item // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 33), // (31,33): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static bool M10 { get Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 33) ); ValidatePropertyModifiers_01(compilation1); } [Fact] public void EventModifiers_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event D M01 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 29), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static event D M03 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static event D M07 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static event D M10 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } private static void ValidateEventModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); { var m01 = i1.GetMember<EventSymbol>("M01"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<EventSymbol>("M02"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<EventSymbol>("M03"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<EventSymbol>("M04"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<EventSymbol>("M05"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<EventSymbol>("M06"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<EventSymbol>("M07"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<EventSymbol>("M08"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<EventSymbol>("M09"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<EventSymbol>("M10"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } foreach (var addAccessor in new[] { true, false }) { var m01 = getAccessor(i1.GetMember<EventSymbol>("M01"), addAccessor); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = getAccessor(i1.GetMember<EventSymbol>("M02"), addAccessor); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = getAccessor(i1.GetMember<EventSymbol>("M03"), addAccessor); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = getAccessor(i1.GetMember<EventSymbol>("M04"), addAccessor); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = getAccessor(i1.GetMember<EventSymbol>("M05"), addAccessor); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = getAccessor(i1.GetMember<EventSymbol>("M06"), addAccessor); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = getAccessor(i1.GetMember<EventSymbol>("M07"), addAccessor); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = getAccessor(i1.GetMember<EventSymbol>("M08"), addAccessor); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = getAccessor(i1.GetMember<EventSymbol>("M09"), addAccessor); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = getAccessor(i1.GetMember<EventSymbol>("M10"), addAccessor); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } static MethodSymbol getAccessor(EventSymbol e, bool addAccessor) { return addAccessor ? e.AddMethod : e.RemoveMethod; } } [Fact] public void EventModifiers_02() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(4, 29), // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static event D M03 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "9.0", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "9.0", "preview").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "9.0", "preview").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "9.0", "preview").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "9.0", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "9.0", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_03() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_04() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_05() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 ; virtual static event D M02 ; sealed static event D M03 ; override static event D M04 ; abstract virtual static event D M05 ; abstract sealed static event D M06 ; abstract override static event D M07 ; virtual sealed static event D M08 ; virtual override static event D M09 ; sealed override static event D M10 ; } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static event D M01 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 29), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (7,28): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual static event D M02 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("static", "7.3", "8.0").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static event D M03 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (13,29): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // override static event D M04 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M04").WithArguments("static", "7.3", "8.0").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static event D M05 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 37), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static event D M06 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 36), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static event D M07 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 38), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static event D M08 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (28,37): error CS8703: The modifier 'static' is not valid for this item in C# 7.3. Please use language version '8.0' or greater. // virtual override static event D M09 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M09").WithArguments("static", "7.3", "8.0").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static event D M10 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void EventModifiers_06() { var source1 = @"#pragma warning disable CS0067 // The event is never used public interface I1 { abstract static event D M01 { add {} remove {} } virtual static event D M02 { add {} remove {} } sealed static event D M03 { add {} remove {} } override static event D M04 { add {} remove {} } abstract virtual static event D M05 { add {} remove {} } abstract sealed static event D M06 { add {} remove {} } abstract override static event D M07 { add {} remove {} } virtual sealed static event D M08 { add {} remove {} } virtual override static event D M09 { add {} remove {} } sealed override static event D M10 { add {} remove {} } } public delegate void D(); "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,29): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "7.3", "preview").WithLocation(4, 29), // (4,33): error CS8712: 'I1.M01': abstract event cannot use event accessor syntax // abstract static event D M01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M01").WithLocation(4, 33), // (7,28): error CS0112: A static member cannot be marked as 'virtual' // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M02").WithArguments("virtual").WithLocation(7, 28), // (7,28): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static event D M02 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M02").WithArguments("default interface implementation", "8.0").WithLocation(7, 28), // (10,27): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static event D M03 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M03").WithArguments("sealed", "7.3", "preview").WithLocation(10, 27), // (13,29): error CS0106: The modifier 'override' is not valid for this item // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M04").WithArguments("override").WithLocation(13, 29), // (13,29): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static event D M04 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M04").WithArguments("default interface implementation", "8.0").WithLocation(13, 29), // (16,37): error CS0112: A static member cannot be marked as 'virtual' // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M05").WithArguments("virtual").WithLocation(16, 37), // (16,37): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M05").WithArguments("abstract", "7.3", "preview").WithLocation(16, 37), // (16,41): error CS8712: 'I1.M05': abstract event cannot use event accessor syntax // abstract virtual static event D M05 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M05").WithLocation(16, 41), // (19,36): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M06").WithArguments("sealed").WithLocation(19, 36), // (19,36): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M06").WithArguments("abstract", "7.3", "preview").WithLocation(19, 36), // (19,40): error CS8712: 'I1.M06': abstract event cannot use event accessor syntax // abstract sealed static event D M06 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M06").WithLocation(19, 40), // (22,38): error CS0106: The modifier 'override' is not valid for this item // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M07").WithArguments("override").WithLocation(22, 38), // (22,38): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M07").WithArguments("abstract", "7.3", "preview").WithLocation(22, 38), // (22,42): error CS8712: 'I1.M07': abstract event cannot use event accessor syntax // abstract override static event D M07 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.M07").WithLocation(22, 42), // (25,35): error CS0112: A static member cannot be marked as 'virtual' // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M08").WithArguments("virtual").WithLocation(25, 35), // (25,35): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static event D M08 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M08").WithArguments("sealed", "7.3", "preview").WithLocation(25, 35), // (28,37): error CS0112: A static member cannot be marked as 'virtual' // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M09").WithArguments("virtual").WithLocation(28, 37), // (28,37): error CS0106: The modifier 'override' is not valid for this item // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M09").WithArguments("override").WithLocation(28, 37), // (28,37): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static event D M09 { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M09").WithArguments("default interface implementation", "8.0").WithLocation(28, 37), // (31,36): error CS0106: The modifier 'override' is not valid for this item // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M10").WithArguments("override").WithLocation(31, 36), // (31,36): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static event D M10 { add {} remove {} } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M10").WithArguments("sealed", "7.3", "preview").WithLocation(31, 36) ); ValidateEventModifiers_01(compilation1); } [Fact] public void OperatorModifiers_01() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "9.0", "preview").WithLocation(10, 30), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "9.0", "preview").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "9.0", "preview").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "9.0", "preview").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "9.0", "preview").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } private static void ValidateOperatorModifiers_01(CSharpCompilation compilation1) { var i1 = compilation1.GetTypeByMetadataName("I1"); var m01 = i1.GetMember<MethodSymbol>("op_UnaryPlus"); Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); var m02 = i1.GetMember<MethodSymbol>("op_UnaryNegation"); Assert.False(m02.IsAbstract); Assert.False(m02.IsVirtual); Assert.False(m02.IsMetadataVirtual()); Assert.False(m02.IsSealed); Assert.True(m02.IsStatic); Assert.False(m02.IsExtern); Assert.False(m02.IsAsync); Assert.False(m02.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m02)); var m03 = i1.GetMember<MethodSymbol>("op_Increment"); Assert.False(m03.IsAbstract); Assert.False(m03.IsVirtual); Assert.False(m03.IsMetadataVirtual()); Assert.False(m03.IsSealed); Assert.True(m03.IsStatic); Assert.False(m03.IsExtern); Assert.False(m03.IsAsync); Assert.False(m03.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m03)); var m04 = i1.GetMember<MethodSymbol>("op_Decrement"); Assert.False(m04.IsAbstract); Assert.False(m04.IsVirtual); Assert.False(m04.IsMetadataVirtual()); Assert.False(m04.IsSealed); Assert.True(m04.IsStatic); Assert.False(m04.IsExtern); Assert.False(m04.IsAsync); Assert.False(m04.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m04)); var m05 = i1.GetMember<MethodSymbol>("op_LogicalNot"); Assert.True(m05.IsAbstract); Assert.False(m05.IsVirtual); Assert.True(m05.IsMetadataVirtual()); Assert.False(m05.IsSealed); Assert.True(m05.IsStatic); Assert.False(m05.IsExtern); Assert.False(m05.IsAsync); Assert.False(m05.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m05)); var m06 = i1.GetMember<MethodSymbol>("op_OnesComplement"); Assert.True(m06.IsAbstract); Assert.False(m06.IsVirtual); Assert.True(m06.IsMetadataVirtual()); Assert.False(m06.IsSealed); Assert.True(m06.IsStatic); Assert.False(m06.IsExtern); Assert.False(m06.IsAsync); Assert.False(m06.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m06)); var m07 = i1.GetMember<MethodSymbol>("op_Addition"); Assert.True(m07.IsAbstract); Assert.False(m07.IsVirtual); Assert.True(m07.IsMetadataVirtual()); Assert.False(m07.IsSealed); Assert.True(m07.IsStatic); Assert.False(m07.IsExtern); Assert.False(m07.IsAsync); Assert.False(m07.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m07)); var m08 = i1.GetMember<MethodSymbol>("op_Subtraction"); Assert.False(m08.IsAbstract); Assert.False(m08.IsVirtual); Assert.False(m08.IsMetadataVirtual()); Assert.False(m08.IsSealed); Assert.True(m08.IsStatic); Assert.False(m08.IsExtern); Assert.False(m08.IsAsync); Assert.False(m08.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m08)); var m09 = i1.GetMember<MethodSymbol>("op_Multiply"); Assert.False(m09.IsAbstract); Assert.False(m09.IsVirtual); Assert.False(m09.IsMetadataVirtual()); Assert.False(m09.IsSealed); Assert.True(m09.IsStatic); Assert.False(m09.IsExtern); Assert.False(m09.IsAsync); Assert.False(m09.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m09)); var m10 = i1.GetMember<MethodSymbol>("op_Division"); Assert.False(m10.IsAbstract); Assert.False(m10.IsVirtual); Assert.False(m10.IsMetadataVirtual()); Assert.False(m10.IsSealed); Assert.True(m10.IsStatic); Assert.False(m10.IsExtern); Assert.False(m10.IsAsync); Assert.False(m10.IsOverride); Assert.Null(i1.FindImplementationForInterfaceMember(m10)); } [Fact] public void OperatorModifiers_02() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(4, 32), // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "9.0", "preview").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "9.0", "preview").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "9.0", "preview").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "9.0", "preview").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "9.0", "preview").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "9.0", "preview").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_03() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_04() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_05() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) ; virtual static I1 operator- (I1 x) ; sealed static I1 operator++ (I1 x) ; override static I1 operator-- (I1 x) ; abstract virtual static I1 operator! (I1 x) ; abstract sealed static I1 operator~ (I1 x) ; abstract override static I1 operator+ (I1 x, I1 y) ; virtual sealed static I1 operator- (I1 x, I1 y) ; virtual override static I1 operator* (I1 x, I1 y) ; sealed override static I1 operator/ (I1 x, I1 y) ; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(7, 31), // (7,31): error CS0501: 'I1.operator -(I1)' must declare a body because it is not marked abstract, extern, or partial // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1)").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "7.3", "preview").WithLocation(10, 30), // (10,30): error CS0501: 'I1.operator ++(I1)' must declare a body because it is not marked abstract, extern, or partial // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "++").WithArguments("I1.operator ++(I1)").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "--").WithArguments("default interface implementation", "8.0").WithLocation(13, 32), // (13,32): error CS0501: 'I1.operator --(I1)' must declare a body because it is not marked abstract, extern, or partial // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "--").WithArguments("I1.operator --(I1)").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "7.3", "preview").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "7.3", "preview").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "7.3", "preview").WithLocation(25, 38), // (25,38): error CS0501: 'I1.operator -(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "-").WithArguments("I1.operator -(I1, I1)").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "*").WithArguments("default interface implementation", "8.0").WithLocation(28, 40), // (28,40): error CS0501: 'I1.operator *(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "*").WithArguments("I1.operator *(I1, I1)").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "7.3", "preview").WithLocation(31, 39), // (31,39): error CS0501: 'I1.operator /(I1, I1)' must declare a body because it is not marked abstract, extern, or partial // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "/").WithArguments("I1.operator /(I1, I1)").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_06() { var source1 = @" public interface I1 { abstract static I1 operator+ (I1 x) {throw null;} virtual static I1 operator- (I1 x) {throw null;} sealed static I1 operator++ (I1 x) {throw null;} override static I1 operator-- (I1 x) {throw null;} abstract virtual static I1 operator! (I1 x) {throw null;} abstract sealed static I1 operator~ (I1 x) {throw null;} abstract override static I1 operator+ (I1 x, I1 y) {throw null;} virtual sealed static I1 operator- (I1 x, I1 y) {throw null;} virtual override static I1 operator* (I1 x, I1 y) {throw null;} sealed override static I1 operator/ (I1 x, I1 y) {throw null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(4, 32), // (4,32): error CS0500: 'I1.operator +(I1)' cannot declare a body because it is marked abstract // abstract static I1 operator+ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1)").WithLocation(4, 32), // (7,31): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(7, 31), // (7,31): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual static I1 operator- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "-").WithArguments("default interface implementation", "8.0").WithLocation(7, 31), // (10,30): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed static I1 operator++ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "++").WithArguments("sealed", "7.3", "preview").WithLocation(10, 30), // (13,32): error CS0106: The modifier 'override' is not valid for this item // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "--").WithArguments("override").WithLocation(13, 32), // (13,32): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // override static I1 operator-- (I1 x) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "--").WithArguments("default interface implementation", "8.0").WithLocation(13, 32), // (16,40): error CS0106: The modifier 'virtual' is not valid for this item // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "!").WithArguments("virtual").WithLocation(16, 40), // (16,40): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!").WithArguments("abstract", "7.3", "preview").WithLocation(16, 40), // (16,40): error CS0500: 'I1.operator !(I1)' cannot declare a body because it is marked abstract // abstract virtual static I1 operator! (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "!").WithArguments("I1.operator !(I1)").WithLocation(16, 40), // (19,39): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_BadMemberFlag, "~").WithArguments("sealed").WithLocation(19, 39), // (19,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "~").WithArguments("abstract", "7.3", "preview").WithLocation(19, 39), // (19,39): error CS0500: 'I1.operator ~(I1)' cannot declare a body because it is marked abstract // abstract sealed static I1 operator~ (I1 x) Diagnostic(ErrorCode.ERR_AbstractHasBody, "~").WithArguments("I1.operator ~(I1)").WithLocation(19, 39), // (22,41): error CS0106: The modifier 'override' is not valid for this item // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("override").WithLocation(22, 41), // (22,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "+").WithArguments("abstract", "7.3", "preview").WithLocation(22, 41), // (22,41): error CS0500: 'I1.operator +(I1, I1)' cannot declare a body because it is marked abstract // abstract override static I1 operator+ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_AbstractHasBody, "+").WithArguments("I1.operator +(I1, I1)").WithLocation(22, 41), // (25,38): error CS0106: The modifier 'virtual' is not valid for this item // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "-").WithArguments("virtual").WithLocation(25, 38), // (25,38): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // virtual sealed static I1 operator- (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "-").WithArguments("sealed", "7.3", "preview").WithLocation(25, 38), // (28,40): error CS0106: The modifier 'virtual' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("virtual").WithLocation(28, 40), // (28,40): error CS0106: The modifier 'override' is not valid for this item // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "*").WithArguments("override").WithLocation(28, 40), // (28,40): error CS8370: Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater. // virtual override static I1 operator* (I1 x, I1 y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "*").WithArguments("default interface implementation", "8.0").WithLocation(28, 40), // (31,39): error CS0106: The modifier 'override' is not valid for this item // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_BadMemberFlag, "/").WithArguments("override").WithLocation(31, 39), // (31,39): error CS8703: The modifier 'sealed' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // sealed override static I1 operator/ (I1 x, I1 y) Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "/").WithArguments("sealed", "7.3", "preview").WithLocation(31, 39) ); ValidateOperatorModifiers_01(compilation1); } [Fact] public void OperatorModifiers_07() { var source1 = @" public interface I1 { abstract static bool operator== (I1 x, I1 y); abstract static bool operator!= (I1 x, I1 y) {return false;} } public interface I2 { sealed static bool operator== (I2 x, I2 y); sealed static bool operator!= (I2 x, I2 y) {return false;} } public interface I3 { abstract sealed static bool operator== (I3 x, I3 y); abstract sealed static bool operator!= (I3 x, I3 y) {return false;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool operator== (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "7.3", "preview").WithLocation(4, 34), // (6,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "7.3", "preview").WithLocation(6, 34), // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (18,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "7.3", "preview").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "7.3", "preview").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator== (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(4, 34), // (6,34): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(6, 34), // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (18,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,34): error CS0500: 'I1.operator !=(I1, I1)' cannot declare a body because it is marked abstract // abstract static bool operator!= (I1 x, I1 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I1.operator !=(I1, I1)").WithLocation(6, 34), // (11,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(11, 32), // (11,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator== (I2 x, I2 y); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "==").WithLocation(11, 32), // (13,32): error CS0106: The modifier 'sealed' is not valid for this item // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(13, 32), // (13,32): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static bool operator!= (I2 x, I2 y) {return false;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "!=").WithLocation(13, 32), // (18,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator== (I3 x, I3 y); Diagnostic(ErrorCode.ERR_BadMemberFlag, "==").WithArguments("sealed").WithLocation(18, 41), // (20,41): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "!=").WithArguments("sealed").WithLocation(20, 41), // (20,41): error CS0500: 'I3.operator !=(I3, I3)' cannot declare a body because it is marked abstract // abstract sealed static bool operator!= (I3 x, I3 y) {return false;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "!=").WithArguments("I3.operator !=(I3, I3)").WithLocation(20, 41) ); validate(); void validate() { foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I1").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I2").GetMembers()) { Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I3").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } } } [Fact] public void OperatorModifiers_08() { var source1 = @" public interface I1 { abstract static implicit operator int(I1 x); abstract static explicit operator I1(bool x) {return null;} } public interface I2 { sealed static implicit operator int(I2 x); sealed static explicit operator I2(bool x) {return null;} } public interface I3 { abstract sealed static implicit operator int(I3 x); abstract sealed static explicit operator I3(bool x) {return null;} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "7.3", "preview").WithLocation(4, 39), // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I1").WithArguments("abstract", "7.3", "preview").WithLocation(6, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "7.3", "preview").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 7.3. Please use language version 'preview' or greater. // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I3").WithArguments("abstract", "7.3", "preview").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(4, 39), // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I1").WithArguments("abstract", "9.0", "preview").WithLocation(6, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "I3").WithArguments("abstract", "9.0", "preview").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0552: 'I1.implicit operator int(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator int(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I1.implicit operator int(I1)").WithLocation(4, 39), // (6,39): error CS0500: 'I1.explicit operator I1(bool)' cannot declare a body because it is marked abstract // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (6,39): error CS0552: 'I1.explicit operator I1(bool)': user-defined conversions to or from an interface are not allowed // abstract static explicit operator I1(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I1").WithArguments("I1.explicit operator I1(bool)").WithLocation(6, 39), // (11,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(11, 37), // (11,37): error CS0552: 'I2.implicit operator int(I2)': user-defined conversions to or from an interface are not allowed // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I2.implicit operator int(I2)").WithLocation(11, 37), // (11,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static implicit operator int(I2 x); Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(11, 37), // (13,37): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I2").WithArguments("sealed").WithLocation(13, 37), // (13,37): error CS0552: 'I2.explicit operator I2(bool)': user-defined conversions to or from an interface are not allowed // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I2").WithArguments("I2.explicit operator I2(bool)").WithLocation(13, 37), // (13,37): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // sealed static explicit operator I2(bool x) {return null;} Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "I2").WithLocation(13, 37), // (18,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(18, 46), // (18,46): error CS0552: 'I3.implicit operator int(I3)': user-defined conversions to or from an interface are not allowed // abstract sealed static implicit operator int(I3 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "int").WithArguments("I3.implicit operator int(I3)").WithLocation(18, 46), // (20,46): error CS0106: The modifier 'sealed' is not valid for this item // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_BadMemberFlag, "I3").WithArguments("sealed").WithLocation(20, 46), // (20,46): error CS0500: 'I3.explicit operator I3(bool)' cannot declare a body because it is marked abstract // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_AbstractHasBody, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46), // (20,46): error CS0552: 'I3.explicit operator I3(bool)': user-defined conversions to or from an interface are not allowed // abstract sealed static explicit operator I3(bool x) {return null;} Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I3").WithArguments("I3.explicit operator I3(bool)").WithLocation(20, 46) ); validate(); void validate() { foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I1").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I2").GetMembers()) { Assert.False(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.False(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } foreach (MethodSymbol m01 in compilation1.GetTypeByMetadataName("I3").GetMembers()) { Assert.True(m01.IsAbstract); Assert.False(m01.IsVirtual); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsExtern); Assert.False(m01.IsAsync); Assert.False(m01.IsOverride); Assert.Null(m01.ContainingType.FindImplementationForInterfaceMember(m01)); } } } [Fact] public void FieldModifiers_01() { var source1 = @" public interface I1 { abstract static int F1; sealed static int F2; abstract int F3; sealed int F4; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,25): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract static int F1; Diagnostic(ErrorCode.ERR_AbstractField, "F1").WithLocation(4, 25), // (5,23): error CS0106: The modifier 'sealed' is not valid for this item // sealed static int F2; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F2").WithArguments("sealed").WithLocation(5, 23), // (6,18): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract int F3; Diagnostic(ErrorCode.ERR_AbstractField, "F3").WithLocation(6, 18), // (6,18): error CS0525: Interfaces cannot contain instance fields // abstract int F3; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F3").WithLocation(6, 18), // (7,16): error CS0106: The modifier 'sealed' is not valid for this item // sealed int F4; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F4").WithArguments("sealed").WithLocation(7, 16), // (7,16): error CS0525: Interfaces cannot contain instance fields // sealed int F4; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "F4").WithLocation(7, 16) ); } [Fact] public void ExternAbstractStatic_01() { var source1 = @" interface I1 { extern abstract static void M01(); extern abstract static bool P01 { get; } extern abstract static event System.Action E01; extern abstract static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0180: 'I1.M01()' cannot be both extern and abstract // extern abstract static void M01(); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M01").WithArguments("I1.M01()").WithLocation(4, 33), // (5,33): error CS0180: 'I1.P01' cannot be both extern and abstract // extern abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P01").WithArguments("I1.P01").WithLocation(5, 33), // (6,48): error CS0180: 'I1.E01' cannot be both extern and abstract // extern abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E01").WithArguments("I1.E01").WithLocation(6, 48), // (7,39): error CS0180: 'I1.operator +(I1)' cannot be both extern and abstract // extern abstract static I1 operator+ (I1 x); Diagnostic(ErrorCode.ERR_AbstractAndExtern, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 39) ); } [Fact] public void ExternAbstractStatic_02() { var source1 = @" interface I1 { extern abstract static void M01() {} extern abstract static bool P01 { get => false; } extern abstract static event System.Action E01 { add {} remove {} } extern abstract static I1 operator+ (I1 x) => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0180: 'I1.M01()' cannot be both extern and abstract // extern abstract static void M01() {} Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M01").WithArguments("I1.M01()").WithLocation(4, 33), // (5,33): error CS0180: 'I1.P01' cannot be both extern and abstract // extern abstract static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P01").WithArguments("I1.P01").WithLocation(5, 33), // (6,48): error CS0180: 'I1.E01' cannot be both extern and abstract // extern abstract static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E01").WithArguments("I1.E01").WithLocation(6, 48), // (6,52): error CS8712: 'I1.E01': abstract event cannot use event accessor syntax // extern abstract static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("I1.E01").WithLocation(6, 52), // (7,39): error CS0180: 'I1.operator +(I1)' cannot be both extern and abstract // extern abstract static I1 operator+ (I1 x) => null; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "+").WithArguments("I1.operator +(I1)").WithLocation(7, 39) ); } [Fact] public void ExternSealedStatic_01() { var source1 = @" #pragma warning disable CS0626 // Method, operator, or accessor is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. interface I1 { extern sealed static void M01(); extern sealed static bool P01 { get; } extern sealed static event System.Action E01; extern sealed static I1 operator+ (I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void AbstractStaticInClass_01() { var source1 = @" abstract class C1 { public abstract static void M01(); public abstract static bool P01 { get; } public abstract static event System.Action E01; public abstract static C1 operator+ (C1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static void M01(); Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M01").WithArguments("abstract").WithLocation(4, 33), // (5,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P01").WithArguments("abstract").WithLocation(5, 33), // (6,48): error CS0112: A static member cannot be marked as 'abstract' // public abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "E01").WithArguments("abstract").WithLocation(6, 48), // (7,39): error CS0106: The modifier 'abstract' is not valid for this item // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("abstract").WithLocation(7, 39), // (7,39): error CS0501: 'C1.operator +(C1)' must declare a body because it is not marked abstract, extern, or partial // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("C1.operator +(C1)").WithLocation(7, 39) ); } [Fact] public void SealedStaticInClass_01() { var source1 = @" class C1 { sealed static void M01() {} sealed static bool P01 { get => false; } sealed static event System.Action E01 { add {} remove {} } public sealed static C1 operator+ (C1 x) => null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0238: 'C1.M01()' cannot be sealed because it is not an override // sealed static void M01() {} Diagnostic(ErrorCode.ERR_SealedNonOverride, "M01").WithArguments("C1.M01()").WithLocation(4, 24), // (5,24): error CS0238: 'C1.P01' cannot be sealed because it is not an override // sealed static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_SealedNonOverride, "P01").WithArguments("C1.P01").WithLocation(5, 24), // (6,39): error CS0238: 'C1.E01' cannot be sealed because it is not an override // sealed static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_SealedNonOverride, "E01").WithArguments("C1.E01").WithLocation(6, 39), // (7,37): error CS0106: The modifier 'sealed' is not valid for this item // public sealed static C1 operator+ (C1 x) => null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("sealed").WithLocation(7, 37) ); } [Fact] public void AbstractStaticInStruct_01() { var source1 = @" struct C1 { public abstract static void M01(); public abstract static bool P01 { get; } public abstract static event System.Action E01; public abstract static C1 operator+ (C1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static void M01(); Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M01").WithArguments("abstract").WithLocation(4, 33), // (5,33): error CS0112: A static member cannot be marked as 'abstract' // public abstract static bool P01 { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P01").WithArguments("abstract").WithLocation(5, 33), // (6,48): error CS0112: A static member cannot be marked as 'abstract' // public abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "E01").WithArguments("abstract").WithLocation(6, 48), // (7,39): error CS0106: The modifier 'abstract' is not valid for this item // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("abstract").WithLocation(7, 39), // (7,39): error CS0501: 'C1.operator +(C1)' must declare a body because it is not marked abstract, extern, or partial // public abstract static C1 operator+ (C1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("C1.operator +(C1)").WithLocation(7, 39) ); } [Fact] public void SealedStaticInStruct_01() { var source1 = @" struct C1 { sealed static void M01() {} sealed static bool P01 { get => false; } sealed static event System.Action E01 { add {} remove {} } public sealed static C1 operator+ (C1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0238: 'C1.M01()' cannot be sealed because it is not an override // sealed static void M01() {} Diagnostic(ErrorCode.ERR_SealedNonOverride, "M01").WithArguments("C1.M01()").WithLocation(4, 24), // (5,24): error CS0238: 'C1.P01' cannot be sealed because it is not an override // sealed static bool P01 { get => false; } Diagnostic(ErrorCode.ERR_SealedNonOverride, "P01").WithArguments("C1.P01").WithLocation(5, 24), // (6,39): error CS0238: 'C1.E01' cannot be sealed because it is not an override // sealed static event System.Action E01 { add {} remove {} } Diagnostic(ErrorCode.ERR_SealedNonOverride, "E01").WithArguments("C1.E01").WithLocation(6, 39), // (7,37): error CS0106: The modifier 'sealed' is not valid for this item // public sealed static C1 operator+ (C1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "+").WithArguments("sealed").WithLocation(7, 37) ); } [Fact] public void DefineAbstractStaticMethod_01() { var source1 = @" interface I1 { abstract static void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); } } [Fact] public void DefineAbstractStaticMethod_02() { var source1 = @" interface I1 { abstract static void M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 26) ); } [Theory] [InlineData("I1", "+", "(I1 x)")] [InlineData("I1", "-", "(I1 x)")] [InlineData("I1", "!", "(I1 x)")] [InlineData("I1", "~", "(I1 x)")] [InlineData("I1", "++", "(I1 x)")] [InlineData("I1", "--", "(I1 x)")] [InlineData("I1", "+", "(I1 x, I1 y)")] [InlineData("I1", "-", "(I1 x, I1 y)")] [InlineData("I1", "*", "(I1 x, I1 y)")] [InlineData("I1", "/", "(I1 x, I1 y)")] [InlineData("I1", "%", "(I1 x, I1 y)")] [InlineData("I1", "&", "(I1 x, I1 y)")] [InlineData("I1", "|", "(I1 x, I1 y)")] [InlineData("I1", "^", "(I1 x, I1 y)")] [InlineData("I1", "<<", "(I1 x, int y)")] [InlineData("I1", ">>", "(I1 x, int y)")] public void DefineAbstractStaticOperator_01(string type, string op, string paramList) { var source1 = @" interface I1 { abstract static " + type + " operator " + op + " " + paramList + @"; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); } } [Fact] public void DefineAbstractStaticOperator_02() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); abstract static I1 operator > (I1 x, I1 y); abstract static I1 operator < (I1 x, I1 y); abstract static I1 operator >= (I1 x, I1 y); abstract static I1 operator <= (I1 x, I1 y); abstract static I1 operator == (I1 x, I1 y); abstract static I1 operator != (I1 x, I1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(8, count); } } [Theory] [InlineData("I1", "+", "(I1 x)")] [InlineData("I1", "-", "(I1 x)")] [InlineData("I1", "!", "(I1 x)")] [InlineData("I1", "~", "(I1 x)")] [InlineData("I1", "++", "(I1 x)")] [InlineData("I1", "--", "(I1 x)")] [InlineData("I1", "+", "(I1 x, I1 y)")] [InlineData("I1", "-", "(I1 x, I1 y)")] [InlineData("I1", "*", "(I1 x, I1 y)")] [InlineData("I1", "/", "(I1 x, I1 y)")] [InlineData("I1", "%", "(I1 x, I1 y)")] [InlineData("I1", "&", "(I1 x, I1 y)")] [InlineData("I1", "|", "(I1 x, I1 y)")] [InlineData("I1", "^", "(I1 x, I1 y)")] [InlineData("I1", "<<", "(I1 x, int y)")] [InlineData("I1", ">>", "(I1 x, int y)")] public void DefineAbstractStaticOperator_03(string type, string op, string paramList) { var source1 = @" interface I1 { abstract static " + type + " operator " + op + " " + paramList + @"; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator + (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 31 + type.Length) ); } [Fact] public void DefineAbstractStaticOperator_04() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); abstract static I1 operator > (I1 x, I1 y); abstract static I1 operator < (I1 x, I1 y); abstract static I1 operator >= (I1 x, I1 y); abstract static I1 operator <= (I1 x, I1 y); abstract static I1 operator == (I1 x, I1 y); abstract static I1 operator != (I1 x, I1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(4, 35), // (5,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(5, 35), // (6,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator > (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, ">").WithLocation(6, 33), // (7,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator < (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "<").WithLocation(7, 33), // (8,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator >= (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, ">=").WithLocation(8, 33), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator <= (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "<=").WithLocation(9, 33), // (10,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator == (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "==").WithLocation(10, 33), // (11,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator != (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "!=").WithLocation(11, 33) ); } [Fact] public void DefineAbstractStaticConversion_01() { var source1 = @" interface I1<T> where T : I1<T> { abstract static implicit operator int(T x); abstract static explicit operator T(int x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticConversion_03() { var source1 = @" interface I1<T> where T : I1<T> { abstract static implicit operator int(T x); abstract static explicit operator T(int x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 39), // (5,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator T(int x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T").WithLocation(5, 39) ); } [Fact] public void DefineAbstractStaticProperty_01() { var source1 = @" interface I1 { abstract static int P01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var p01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); Assert.True(p01.IsAbstract); Assert.False(p01.IsVirtual); Assert.False(p01.IsSealed); Assert.True(p01.IsStatic); Assert.False(p01.IsOverride); int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticProperty_02() { var source1 = @" interface I1 { abstract static int P01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(4, 31), // (4,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(4, 36) ); } [Fact] public void DefineAbstractStaticEvent_01() { var source1 = @" interface I1 { abstract static event System.Action E01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var e01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); Assert.True(e01.IsAbstract); Assert.False(e01.IsVirtual); Assert.False(e01.IsSealed); Assert.True(e01.IsStatic); Assert.False(e01.IsOverride); int count = 0; foreach (var m01 in module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>()) { Assert.False(m01.IsMetadataNewSlot()); Assert.True(m01.IsAbstract); Assert.True(m01.IsMetadataVirtual()); Assert.False(m01.IsMetadataFinal); Assert.False(m01.IsVirtual); Assert.False(m01.IsSealed); Assert.True(m01.IsStatic); Assert.False(m01.IsOverride); count++; } Assert.Equal(2, count); } } [Fact] public void DefineAbstractStaticEvent_02() { var source1 = @" interface I1 { abstract static event System.Action E01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation1.VerifyDiagnostics( // (4,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action E01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "E01").WithLocation(4, 41) ); } [Fact] public void ConstraintChecks_01() { var source1 = @" public interface I1 { abstract static void M01(); } public interface I2 : I1 { } public interface I3 : I2 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var source2 = @" class C1<T1> where T1 : I1 { void Test(C1<I2> x) { } } class C2 { void M<T2>() where T2 : I1 {} void Test(C2 x) { x.M<I2>(); } } class C3<T3> where T3 : I2 { void Test(C3<I2> x, C3<I3> y) { } } class C4 { void M<T4>() where T4 : I2 {} void Test(C4 x) { x.M<I2>(); x.M<I3>(); } } class C5<T5> where T5 : I3 { void Test(C5<I3> y) { } } class C6 { void M<T6>() where T6 : I3 {} void Test(C6 x) { x.M<I3>(); } } class C7<T7> where T7 : I1 { void Test(C7<I1> y) { } } class C8 { void M<T8>() where T8 : I1 {} void Test(C8 x) { x.M<I1>(); } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); var expected = new[] { // (4,22): error CS8920: The interface 'I2' cannot be used as type parameter 'T1' in the generic type or method 'C1<T1>'. The constraint interface 'I1' or its base interface has static abstract members. // void Test(C1<I2> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "x").WithArguments("C1<T1>", "I1", "T1", "I2").WithLocation(4, 22), // (15,11): error CS8920: The interface 'I2' cannot be used as type parameter 'T2' in the generic type or method 'C2.M<T2>()'. The constraint interface 'I1' or its base interface has static abstract members. // x.M<I2>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I2>").WithArguments("C2.M<T2>()", "I1", "T2", "I2").WithLocation(15, 11), // (21,22): error CS8920: The interface 'I2' cannot be used as type parameter 'T3' in the generic type or method 'C3<T3>'. The constraint interface 'I2' or its base interface has static abstract members. // void Test(C3<I2> x, C3<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "x").WithArguments("C3<T3>", "I2", "T3", "I2").WithLocation(21, 22), // (21,32): error CS8920: The interface 'I3' cannot be used as type parameter 'T3' in the generic type or method 'C3<T3>'. The constraint interface 'I2' or its base interface has static abstract members. // void Test(C3<I2> x, C3<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C3<T3>", "I2", "T3", "I3").WithLocation(21, 32), // (32,11): error CS8920: The interface 'I2' cannot be used as type parameter 'T4' in the generic type or method 'C4.M<T4>()'. The constraint interface 'I2' or its base interface has static abstract members. // x.M<I2>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I2>").WithArguments("C4.M<T4>()", "I2", "T4", "I2").WithLocation(32, 11), // (33,11): error CS8920: The interface 'I3' cannot be used as type parameter 'T4' in the generic type or method 'C4.M<T4>()'. The constraint interface 'I2' or its base interface has static abstract members. // x.M<I3>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I3>").WithArguments("C4.M<T4>()", "I2", "T4", "I3").WithLocation(33, 11), // (39,22): error CS8920: The interface 'I3' cannot be used as type parameter 'T5' in the generic type or method 'C5<T5>'. The constraint interface 'I3' or its base interface has static abstract members. // void Test(C5<I3> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C5<T5>", "I3", "T5", "I3").WithLocation(39, 22), // (50,11): error CS8920: The interface 'I3' cannot be used as type parameter 'T6' in the generic type or method 'C6.M<T6>()'. The constraint interface 'I3' or its base interface has static abstract members. // x.M<I3>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I3>").WithArguments("C6.M<T6>()", "I3", "T6", "I3").WithLocation(50, 11), // (56,22): error CS8920: The interface 'I1' cannot be used as type parameter 'T7' in the generic type or method 'C7<T7>'. The constraint interface 'I1' or its base interface has static abstract members. // void Test(C7<I1> y) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "y").WithArguments("C7<T7>", "I1", "T7", "I1").WithLocation(56, 22), // (67,11): error CS8920: The interface 'I1' cannot be used as type parameter 'T8' in the generic type or method 'C8.M<T8>()'. The constraint interface 'I1' or its base interface has static abstract members. // x.M<I1>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "M<I1>").WithArguments("C8.M<T8>()", "I1", "T8", "I1").WithLocation(67, 11) }; compilation2.VerifyDiagnostics(expected); compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.EmitToImageReference() }); compilation2.VerifyDiagnostics(expected); } [Fact] public void ConstraintChecks_02() { var source1 = @" public interface I1 { abstract static void M01(); } public class C : I1 { public static void M01() {} } public struct S : I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var source2 = @" class C1<T1> where T1 : I1 { void Test(C1<C> x, C1<S> y, C1<T1> z) { } } class C2 { public void M<T2>(C2 x) where T2 : I1 { x.M<T2>(x); } void Test(C2 x) { x.M<C>(x); x.M<S>(x); } } class C3<T3> where T3 : I1 { void Test(C1<T3> z) { } } class C4 { void M<T4>(C2 x) where T4 : I1 { x.M<T4>(x); } } class C5<T5> { internal virtual void M<U5>() where U5 : T5 { } } class C6 : C5<I1> { internal override void M<U6>() { base.M<U6>(); } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyEmitDiagnostics(); compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.EmitToImageReference() }); compilation2.VerifyEmitDiagnostics(); } [Fact] public void VarianceSafety_01() { var source1 = @" interface I2<out T1, in T2> { abstract static T1 P1 { get; } abstract static T2 P2 { get; } abstract static T1 P3 { set; } abstract static T2 P4 { set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,21): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.P2'. 'T2' is contravariant. // abstract static T2 P2 { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I2<T1, T2>.P2", "T2", "contravariant", "covariantly").WithLocation(5, 21), // (6,21): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.P3'. 'T1' is covariant. // abstract static T1 P3 { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I2<T1, T2>.P3", "T1", "covariant", "contravariantly").WithLocation(6, 21) ); } [Fact] public void VarianceSafety_02() { var source1 = @" interface I2<out T1, in T2> { abstract static T1 M1(); abstract static T2 M2(); abstract static void M3(T1 x); abstract static void M4(T2 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,21): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.M2()'. 'T2' is contravariant. // abstract static T2 M2(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T2").WithArguments("I2<T1, T2>.M2()", "T2", "contravariant", "covariantly").WithLocation(5, 21), // (6,29): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.M3(T1)'. 'T1' is covariant. // abstract static void M3(T1 x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T1").WithArguments("I2<T1, T2>.M3(T1)", "T1", "covariant", "contravariantly").WithLocation(6, 29) ); } [Fact] public void VarianceSafety_03() { var source1 = @" interface I2<out T1, in T2> { abstract static event System.Action<System.Func<T1>> E1; abstract static event System.Action<System.Func<T2>> E2; abstract static event System.Action<System.Action<T1>> E3; abstract static event System.Action<System.Action<T2>> E4; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (5,58): error CS1961: Invalid variance: The type parameter 'T2' must be covariantly valid on 'I2<T1, T2>.E2'. 'T2' is contravariant. // abstract static event System.Action<System.Func<T2>> E2; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E2").WithArguments("I2<T1, T2>.E2", "T2", "contravariant", "covariantly").WithLocation(5, 58), // (6,60): error CS1961: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.E3'. 'T1' is covariant. // abstract static event System.Action<System.Action<T1>> E3; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E3").WithArguments("I2<T1, T2>.E3", "T1", "covariant", "contravariantly").WithLocation(6, 60) ); } [Fact] public void VarianceSafety_04() { var source1 = @" interface I2<out T2> { abstract static int operator +(I2<T2> x); } interface I3<out T3> { abstract static int operator +(I3<T3> x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,36): error CS1961: Invalid variance: The type parameter 'T2' must be contravariantly valid on 'I2<T2>.operator +(I2<T2>)'. 'T2' is covariant. // abstract static int operator +(I2<T2> x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "I2<T2>").WithArguments("I2<T2>.operator +(I2<T2>)", "T2", "covariant", "contravariantly").WithLocation(4, 36), // (9,36): error CS1961: Invalid variance: The type parameter 'T3' must be contravariantly valid on 'I3<T3>.operator +(I3<T3>)'. 'T3' is covariant. // abstract static int operator +(I3<T3> x); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "I3<T3>").WithArguments("I3<T3>.operator +(I3<T3>)", "T3", "covariant", "contravariantly").WithLocation(9, 36) ); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("!")] [InlineData("~")] [InlineData("true")] [InlineData("false")] public void OperatorSignature_01(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x); } interface I13 { static abstract bool operator " + op + @"(I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,26): error CS0562: The parameter of a unary operator must be the containing type // static bool operator +(T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0562: The parameter of a unary operator must be the containing type // static bool operator +(T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T5 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T71 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T8 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T10 x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator false(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11)").WithLocation(47, 18), // (51,35): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator false(int x); Diagnostic(ErrorCode.ERR_BadAbstractUnaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [InlineData("++")] [InlineData("--")] public void OperatorSignature_02(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static T1 operator " + op + @"(T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static T2? operator " + op + @"(T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract T3 operator " + op + @"(T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract T4? operator " + op + @"(T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract T5 operator " + op + @"(T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract T71 operator " + op + @"(T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract T8 operator " + op + @"(T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract T10 operator " + op + @"(T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract int operator " + op + @"(int x); } interface I13 { static abstract I13 operator " + op + @"(I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0559: The parameter type for ++ or -- operator must be the containing type // static T1 operator ++(T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, op).WithLocation(4, 24), // (9,25): error CS0559: The parameter type for ++ or -- operator must be the containing type // static T2? operator ++(T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecSignature, op).WithLocation(9, 25), // (26,37): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T5 operator ++(T5 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(26, 37), // (32,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T71 operator ++(T71 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(32, 34), // (37,33): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T8 operator ++(T8 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(37, 33), // (44,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract T10 operator ++(T10 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(44, 34), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator --(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11)").WithLocation(47, 18), // (51,34): error CS8922: The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it. // static abstract int operator ++(int x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecSignature, op).WithLocation(51, 34) ); } [Theory] [InlineData("++")] [InlineData("--")] public void OperatorSignature_03(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static T1 operator " + op + @"(I1<T1> x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static T2? operator " + op + @"(I2<T2> x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract T3 operator " + op + @"(I3<T3> x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract T4? operator " + op + @"(I4<T4> x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract T5 operator " + op + @"(I6 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract T71 operator " + op + @"(I7<T71, T72> x); } interface I8<T8> where T8 : I9<T8> { static abstract T8 operator " + op + @"(I8<T8> x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract T10 operator " + op + @"(I10<T10> x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract int operator " + op + @"(I12 x); } interface I13<T13> where T13 : struct, I13<T13> { static abstract T13? operator " + op + @"(T13 x); } interface I14<T14> where T14 : struct, I14<T14> { static abstract T14 operator " + op + @"(T14? x); } interface I15<T151, T152> where T151 : I15<T151, T152> where T152 : I15<T151, T152> { static abstract T151 operator " + op + @"(T152 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,24): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // static T1 operator ++(I1<T1> x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecRetType, op).WithLocation(4, 24), // (9,25): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // static T2? operator ++(I2<T2> x) => throw null; Diagnostic(ErrorCode.ERR_BadIncDecRetType, op).WithLocation(9, 25), // (19,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T4? operator ++(I4<T4> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(19, 34), // (26,37): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T5 operator ++(I6 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(26, 37), // (32,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T71 operator ++(I7<T71, T72> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(32, 34), // (37,33): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T8 operator ++(I8<T8> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(37, 33), // (44,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T10 operator ++(I10<T10> x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(44, 34), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator ++(I10<T11>)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(I10<T11>)").WithLocation(47, 18), // (51,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract int operator ++(I12 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(51, 34), // (56,35): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T13? operator ++(T13 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(56, 35), // (61,34): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T14 operator ++(T14? x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(61, 34), // (66,35): error CS8923: The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter. // static abstract T151 operator ++(T152 x); Diagnostic(ErrorCode.ERR_BadAbstractIncDecRetType, op).WithLocation(66, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x, bool y) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x, bool y) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x, bool y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x, bool y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x, bool y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x, bool y); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x, bool y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x, bool y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x, bool y); } interface I13 { static abstract bool operator " + op + @"(I13 x, bool y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators)).Verify( // (4,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(T1 x, bool y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(T2? x, bool y) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T5 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T71 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T8 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(T10 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator /(T11, bool)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11, bool)").WithLocation(47, 18), // (51,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(int x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_05([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(bool y, T1 x) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(bool y, T2? x) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(bool y, T3 x); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(bool y, T4? x); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(bool y, T5 x); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(bool y, T71 x); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(bool y, T8 x); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(bool y, T10 x); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(bool y, int x); } interface I13 { static abstract bool operator " + op + @"(bool y, I13 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators)).Verify( // (4,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(bool y, T1 x) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0563: One of the parameters of a binary operator must be the containing type // static bool operator +(bool y, T2? x) => throw null; Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T5 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T71 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T8 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, T10 x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator <=(bool, T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(bool, T11)").WithLocation(47, 18), // (51,35): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // static abstract bool operator +(bool y, int x); Diagnostic(ErrorCode.ERR_BadAbstractBinaryOperatorSignature, op).WithLocation(51, 35) ); } [Theory] [InlineData("<<")] [InlineData(">>")] public void OperatorSignature_06(string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { static bool operator " + op + @"(T1 x, int y) => throw null; } interface I2<T2> where T2 : struct, I2<T2> { static bool operator " + op + @"(T2? x, int y) => throw null; } interface I3<T3> where T3 : I3<T3> { static abstract bool operator " + op + @"(T3 x, int y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract bool operator " + op + @"(T4? x, int y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract bool operator " + op + @"(T5 x, int y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract bool operator " + op + @"(T71 x, int y); } interface I8<T8> where T8 : I9<T8> { static abstract bool operator " + op + @"(T8 x, int y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract bool operator " + op + @"(T10 x, int y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract bool operator " + op + @"(int x, int y); } interface I13 { static abstract bool operator " + op + @"(I13 x, int y); } interface I14 { static abstract bool operator " + op + @"(I14 x, bool y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,26): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // static bool operator <<(T1 x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, op).WithLocation(4, 26), // (9,26): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // static bool operator <<(T2? x, int y) => throw null; Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, op).WithLocation(9, 26), // (26,39): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T5 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(26, 39), // (32,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T71 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(32, 35), // (37,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T8 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(37, 35), // (44,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(T10 x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(44, 35), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.operator >>(T11, int)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>.operator " + op + "(T11, int)").WithLocation(47, 18), // (51,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(int x, int y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(51, 35), // (61,35): error CS8925: The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int // static abstract bool operator <<(I14 x, bool y); Diagnostic(ErrorCode.ERR_BadAbstractShiftOperatorSignature, op).WithLocation(61, 35) ); } [Theory] [CombinatorialData] public void OperatorSignature_07([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { abstract static " + op + @" operator T1(T1 y); } interface I2<T2> where T2 : I2<T2> { abstract static " + op + @" operator dynamic(T2 y); } interface I3<T3> where T3 : I3<T3> { static abstract " + op + @" operator T3(bool y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract " + op + @" operator T4?(bool y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract " + op + @" operator T5 (bool y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract " + op + @" operator T71 (bool y); } interface I8<T8> where T8 : I9<T8> { static abstract " + op + @" operator T8(bool y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract " + op + @" operator T10(bool y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract " + op + @" operator int(bool y); } interface I13 { static abstract " + op + @" operator I13(bool y); } interface I14<T14> where T14 : I14<T14> { abstract static " + op + @" operator object(T14 y); } class C15 {} class C16 : C15 {} interface I17<T17> where T17 : C15, I17<T17> { abstract static " + op + @" operator C16(T17 y); } interface I18<T18> where T18 : C16, I18<T18> { abstract static " + op + @" operator C15(T18 y); } interface I19<T19_1, T19_2> where T19_1 : I19<T19_1, T19_2>, T19_2 { abstract static " + op + @" operator T19_1(T19_2 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0555: User-defined operator cannot convert a type to itself // abstract static explicit operator T1(T1 y); Diagnostic(ErrorCode.ERR_IdentityConversion, "T1").WithLocation(4, 39), // (9,39): error CS1964: 'I2<T2>.explicit operator dynamic(T2)': user-defined conversions to or from the dynamic type are not allowed // abstract static explicit operator dynamic(T2 y); Diagnostic(ErrorCode.ERR_BadDynamicConversion, "dynamic").WithArguments("I2<T2>." + op + " operator dynamic(T2)").WithLocation(9, 39), // (26,43): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T5 (bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T5").WithLocation(26, 43), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T71 (bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T71").WithLocation(32, 39), // (37,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T8(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T8").WithLocation(37, 39), // (44,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator T10(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "T10").WithLocation(44, 39), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.explicit operator T11(bool)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>." + op + " operator T11(bool)").WithLocation(47, 18), // (51,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator int(bool y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "int").WithLocation(51, 39), // (56,39): error CS0552: 'I13.explicit operator I13(bool)': user-defined conversions to or from an interface are not allowed // static abstract explicit operator I13(bool y); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I13").WithArguments("I13." + op + " operator I13(bool)").WithLocation(56, 39) ); } [Theory] [CombinatorialData] public void OperatorSignature_08([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" interface I1<T1> where T1 : I1<T1> { abstract static " + op + @" operator T1(T1 y); } interface I2<T2> where T2 : I2<T2> { abstract static " + op + @" operator T2(dynamic y); } interface I3<T3> where T3 : I3<T3> { static abstract " + op + @" operator bool(T3 y); } interface I4<T4> where T4 : struct, I4<T4> { static abstract " + op + @" operator bool(T4? y); } class C5<T5> where T5 : C5<T5>.I6 { public interface I6 { static abstract " + op + @" operator bool(T5 y); } } interface I7<T71, T72> where T72 : I7<T71, T72> where T71 : T72 { static abstract " + op + @" operator bool(T71 y); } interface I8<T8> where T8 : I9<T8> { static abstract " + op + @" operator bool(T8 y); } interface I9<T9> : I8<T9> where T9 : I9<T9> {} interface I10<T10> where T10 : C11<T10> { static abstract " + op + @" operator bool(T10 y); } class C11<T11> : I10<T11> where T11 : C11<T11> {} interface I12 { static abstract " + op + @" operator bool(int y); } interface I13 { static abstract " + op + @" operator bool(I13 y); } interface I14<T14> where T14 : I14<T14> { abstract static " + op + @" operator T14(object y); } class C15 {} class C16 : C15 {} interface I17<T17> where T17 : C15, I17<T17> { abstract static " + op + @" operator T17(C16 y); } interface I18<T18> where T18 : C16, I18<T18> { abstract static " + op + @" operator T18(C15 y); } interface I19<T19_1, T19_2> where T19_1 : I19<T19_1, T19_2>, T19_2 { abstract static " + op + @" operator T19_2(T19_1 y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0555: User-defined operator cannot convert a type to itself // abstract static explicit operator T1(T1 y); Diagnostic(ErrorCode.ERR_IdentityConversion, "T1").WithLocation(4, 39), // (9,39): error CS1964: 'I2<T2>.explicit operator T2(dynamic)': user-defined conversions to or from the dynamic type are not allowed // abstract static explicit operator T2(dynamic y); Diagnostic(ErrorCode.ERR_BadDynamicConversion, "T2").WithArguments("I2<T2>." + op + " operator T2(dynamic)").WithLocation(9, 39), // (26,43): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T5 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(26, 43), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T71 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(32, 39), // (37,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T8 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(37, 39), // (44,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(T10 y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(44, 39), // (47,18): error CS0535: 'C11<T11>' does not implement interface member 'I10<T11>.explicit operator bool(T11)' // class C11<T11> : I10<T11> where T11 : C11<T11> {} Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I10<T11>").WithArguments("C11<T11>", "I10<T11>." + op + " operator bool(T11)").WithLocation(47, 18), // (51,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // static abstract explicit operator bool(int y); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "bool").WithLocation(51, 39), // (56,39): error CS0552: 'I13.explicit operator bool(I13)': user-defined conversions to or from an interface are not allowed // static abstract explicit operator bool(I13 y); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "bool").WithArguments("I13." + op + " operator bool(I13)").WithLocation(56, 39) ); } [Fact] public void ConsumeAbstractStaticMethod_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { M01(); M04(); } void M03() { this.M01(); this.M04(); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { I1.M01(); x.M01(); I1.M04(); x.M04(); } static void MT2<T>() where T : I1 { T.M03(); T.M04(); T.M00(); T.M05(); _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.M01()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // M01(); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "M01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // this.M01(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // this.M04(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.M01(); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.M01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // x.M01(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // x.M04(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M03(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M04(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M00(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.M05()' is inaccessible due to its protection level // T.M05(); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 11), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.M01()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01()").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticMethod_02() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = nameof(M01); _ = nameof(M04); } void M03() { _ = nameof(this.M01); _ = nameof(this.M04); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = nameof(I1.M01); _ = nameof(x.M01); _ = nameof(I1.M04); _ = nameof(x.M04); } static void MT2<T>() where T : I1 { _ = nameof(T.M03); _ = nameof(T.M04); _ = nameof(T.M00); _ = nameof(T.M05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.M00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = nameof(T.M05); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticMethod_03() { var source1 = @" public interface I1 { abstract static void M01(); abstract static void M04(int x); } class Test { static void M02<T, U>() where T : U where U : I1 { T.M01(); } static string M03<T, U>() where T : U where U : I1 { return nameof(T.M01); } static async void M05<T, U>() where T : U where U : I1 { T.M04(await System.Threading.Tasks.Task.FromResult(1)); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 14 (0xe) .maxstack 0 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""void I1.M01()"" IL_000c: nop IL_000d: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""M01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 12 (0xc) .maxstack 0 IL_0000: constrained. ""T"" IL_0006: call ""void I1.M01()"" IL_000b: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""M01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("T.M01()", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IInvocationOperation (virtual void I1.M01()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'T.M01()') Instance Receiver: null Arguments(0) "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("void I1.M01()", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Equal("void I1.M01()", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "M01").Single().ToTestDisplayString()); Assert.Contains("void I1.M01()", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("M01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticMethod_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.M01(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.M01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_05() { var source1 = @" public interface I1 { abstract static I1 Select(System.Func<int, int> p); } class Test { static void M02<T>() where T : I1 { _ = from t in T select t + 1; _ = from t in I1 select t + 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); // https://github.com/dotnet/roslyn/issues/53796: Confirm whether we want to enable the 'from t in T' scenario. compilation1.VerifyDiagnostics( // (11,23): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = from t in T select t + 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(11, 23), // (12,26): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = from t in I1 select t + 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "select t + 1").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.M01(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.M01(); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.M01(); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_01(string prefixOp, string postfixOp) { var source1 = @" interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); abstract static I1<T> operator" + prefixOp + postfixOp + @" (I1<T> x); static void M02(I1<T> x) { _ = " + prefixOp + "x" + postfixOp + @"; } void M03(I1<T> y) { _ = " + prefixOp + "y" + postfixOp + @"; } } class Test<T> where T : I1<T> { static void MT1(I1<T> a) { _ = " + prefixOp + "a" + postfixOp + @"; } static void MT2() { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (" + prefixOp + "b" + postfixOp + @").ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "x" + postfixOp).WithLocation(8, 13), // (13,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "y" + postfixOp).WithLocation(13, 13), // (21,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = -a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, prefixOp + "a" + postfixOp).WithLocation(21, 13), (prefixOp + postfixOp).Length == 1 ? // (26,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (-b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, prefixOp + "b" + postfixOp).WithLocation(26, 78) : // (26,78): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b--).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, prefixOp + "b" + postfixOp).WithLocation(26, 78) ); } [Theory] [InlineData("+", "", "op_UnaryPlus", "Plus")] [InlineData("-", "", "op_UnaryNegation", "Minus")] [InlineData("!", "", "op_LogicalNot", "Not")] [InlineData("~", "", "op_OnesComplement", "BitwiseNegation")] [InlineData("++", "", "op_Increment", "Increment")] [InlineData("--", "", "op_Decrement", "Decrement")] [InlineData("", "++", "op_Increment", "Increment")] [InlineData("", "--", "op_Decrement", "Decrement")] public void ConsumeAbstractUnaryOperator_03(string prefixOp, string postfixOp, string metadataName, string opKind) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } class Test { static T M02<T, U>(T x) where T : U where U : I1<T> { return " + prefixOp + "x" + postfixOp + @"; } static T? M03<T, U>(T? y) where T : struct, U where U : I1<T> { return " + prefixOp + "y" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 21 (0x15) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: dup IL_000e: starg.s V_0 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: dup IL_002f: starg.s V_0 IL_0031: stloc.2 IL_0032: br.s IL_0034 IL_0034: ldloc.2 IL_0035: ret } "); break; case ("", "++"): case ("", "--"): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 21 (0x15) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: dup IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T)"" IL_000e: starg.s V_0 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: dup IL_0003: stloc.0 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: brtrue.s IL_0018 IL_000d: ldloca.s V_1 IL_000f: initobj ""T?"" IL_0015: ldloc.1 IL_0016: br.s IL_002f IL_0018: ldloca.s V_0 IL_001a: call ""readonly T T?.GetValueOrDefault()"" IL_001f: constrained. ""T"" IL_0025: call ""T I1<T>." + metadataName + @"(T)"" IL_002a: newobj ""T?..ctor(T)"" IL_002f: starg.s V_0 IL_0031: stloc.2 IL_0032: br.s IL_0034 IL_0034: ldloc.2 IL_0035: ret } "); break; default: verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); break; } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(T)"" IL_000c: dup IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0016 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: br.s IL_002d IL_0016: ldloca.s V_0 IL_0018: call ""readonly T T?.GetValueOrDefault()"" IL_001d: constrained. ""T"" IL_0023: call ""T I1<T>." + metadataName + @"(T)"" IL_0028: newobj ""T?..ctor(T)"" IL_002d: dup IL_002e: starg.s V_0 IL_0030: ret } "); break; case ("", "++"): case ("", "--"): verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: dup IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: starg.s V_0 IL_0030: ret } "); break; default: verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(T)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(T?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""T I1<T>." + metadataName + @"(T)"" IL_0027: newobj ""T?..ctor(T)"" IL_002c: ret } "); break; } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = postfixOp != "" ? (ExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().First() : tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().First(); Assert.Equal(prefixOp + "x" + postfixOp, node.ToString()); switch ((prefixOp, postfixOp)) { case ("++", ""): case ("--", ""): case ("", "++"): case ("", "--"): VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IIncrementOrDecrementOperation (" + (prefixOp != "" ? "Prefix" : "Postfix") + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x)) (OperationKind." + opKind + @", Type: T) (Syntax: '" + prefixOp + "x" + postfixOp + @"') Target: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); break; default: VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IUnaryOperation (UnaryOperatorKind." + opKind + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x)) (OperationKind.Unary, Type: T) (Syntax: '" + prefixOp + "x" + postfixOp + @"') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); break; } } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_04(string prefixOp, string postfixOp) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1<T> { _ = " + prefixOp + "x" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = -x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, prefixOp + "x" + postfixOp).WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator- (T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, prefixOp + postfixOp).WithLocation(12, 31) ); } [Theory] [InlineData("+", "")] [InlineData("-", "")] [InlineData("!", "")] [InlineData("~", "")] [InlineData("++", "")] [InlineData("--", "")] [InlineData("", "++")] [InlineData("", "--")] public void ConsumeAbstractUnaryOperator_06(string prefixOp, string postfixOp) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + prefixOp + postfixOp + @" (T x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1<T> { _ = " + prefixOp + "x" + postfixOp + @"; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = -x; Diagnostic(ErrorCode.ERR_FeatureInPreview, prefixOp + "x" + postfixOp).WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,31): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator- (T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, prefixOp + postfixOp).WithArguments("abstract", "9.0", "preview").WithLocation(12, 31) ); } [Fact] public void ConsumeAbstractTrueOperator_01() { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); static void M02(I1 x) { _ = x ? true : false; } void M03(I1 y) { _ = y ? true : false; } } class Test { static void MT1(I1 a) { _ = a ? true : false; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b ? true : false).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x").WithLocation(9, 13), // (14,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y").WithLocation(14, 13), // (22,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a ? true : false; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a").WithLocation(22, 13), // (27,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b ? true : false).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b").WithLocation(27, 78) ); } [Fact] public void ConsumeAbstractTrueOperator_03() { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator true (T x); abstract static bool operator false (T x); } class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>.op_True(T)"" IL_000d: brtrue.s IL_0011 IL_000f: br.s IL_0011 IL_0011: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""bool I1<T>.op_True(T)"" IL_000c: pop IL_000d: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalExpressionSyntax>().First(); Assert.Equal("x ? true : false", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IConditionalOperation (OperationKind.Conditional, Type: System.Boolean) (Syntax: 'x ? true : false') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean I1<T>.op_True(T x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') WhenTrue: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') WhenFalse: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') "); } [Fact] public void ConsumeAbstractTrueOperator_04() { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1 { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(12, 35), // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(13, 35) ); } [Fact] public void ConsumeAbstractTrueOperator_06() { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>(T x) where T : I1 { _ = x ? true : false; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x ? true : false; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(12, 35), // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); static void M02((int, C<I1>) x) { _ = x " + op + @" x; } void M03((int, C<I1>) y) { _ = y " + op + @" y; } } class Test { static void MT1((int, C<I1>) a) { _ = a " + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b " + op + @" b).ToString()); } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x == x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " x").WithLocation(9, 13), // (14,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y == y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " y").WithLocation(14, 13), // (22,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a == a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " a").WithLocation(22, 13), // (27,98): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(27, 98) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator true (T x); abstract static bool operator false (T x); } class Test { static void M02<T, U>((int, C<T>) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 55 (0x37) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0034 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_False(T)"" IL_002f: ldc.i4.0 IL_0030: ceq IL_0032: br.s IL_0035 IL_0034: ldc.i4.0 IL_0035: pop IL_0036: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_True(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.1 IL_0032: pop IL_0033: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 54 (0x36) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0033 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_False(T)"" IL_002e: ldc.i4.0 IL_002f: ceq IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: pop IL_0035: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_True(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.1 IL_0031: pop IL_0032: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1 { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (21,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(21, 35), // (22,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(22, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractTrueFalseOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1 { abstract static bool operator true (I1 x); abstract static bool operator false (I1 x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1 { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (21,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(21, 35), // (22,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(22, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" partial interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); static void M02(I1 x) { _ = x " + op + @" 1; } void M03(I1 y) { _ = y " + op + @" 2; } } class Test { static void MT1(I1 a) { _ = a " + op + @" 3; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + @" 4).ToString()); } } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator" + matchingOp + @" (I1 x, int y); } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x - 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " 1").WithLocation(8, 13), // (13,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y - 2; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " 2").WithLocation(13, 13), // (21,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a - 3; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " 3").WithLocation(21, 13), // (26,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b - 4).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b " + op + " 4").WithLocation(26, 78) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_01(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" static void M02(I1 x) { _ = x " + op + op + @" x; } void M03(I1 y) { _ = y " + op + op + @" y; } } class Test { static void MT1(I1 a) { _ = a " + op + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + op + @" b).ToString()); } static void MT3(I1 b, dynamic c) { _ = b " + op + op + @" c; } "; if (!success) { source1 += @" static void MT4<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<T, dynamic>>)((T d, dynamic e) => (d " + op + op + @" e).ToString()); } "; } source1 += @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); if (success) { Assert.False(binaryIsAbstract); Assert.False(op == "&" ? falseIsAbstract : trueIsAbstract); var binaryMetadataName = op == "&" ? "op_BitwiseAnd" : "op_BitwiseOr"; var unaryMetadataName = op == "&" ? "op_False" : "op_True"; var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.MT1(I1)", @" { // Code size 22 (0x16) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0009: brtrue.s IL_0015 IL_000b: ldloc.0 IL_000c: ldarg.0 IL_000d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0012: pop IL_0013: br.s IL_0015 IL_0015: ret } "); if (op == "&") { verifier.VerifyIL("Test.MT3(I1, dynamic)", @" { // Code size 97 (0x61) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""bool I1.op_False(I1)"" IL_0007: brtrue.s IL_0060 IL_0009: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_000e: brfalse.s IL_0012 IL_0010: br.s IL_0047 IL_0012: ldc.i4.8 IL_0013: ldc.i4.2 IL_0014: ldtoken ""Test"" IL_0019: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001e: ldc.i4.2 IL_001f: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0024: dup IL_0025: ldc.i4.0 IL_0026: ldc.i4.1 IL_0027: ldnull IL_0028: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002d: stelem.ref IL_002e: dup IL_002f: ldc.i4.1 IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0037: stelem.ref IL_0038: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0042: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0047: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_004c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Target"" IL_0051: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0056: ldarg.0 IL_0057: ldarg.1 IL_0058: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, I1, dynamic)"" IL_005d: pop IL_005e: br.s IL_0060 IL_0060: ret } "); } else { verifier.VerifyIL("Test.MT3(I1, dynamic)", @" { // Code size 98 (0x62) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""bool I1.op_True(I1)"" IL_0007: brtrue.s IL_0061 IL_0009: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_000e: brfalse.s IL_0012 IL_0010: br.s IL_0048 IL_0012: ldc.i4.8 IL_0013: ldc.i4.s 36 IL_0015: ldtoken ""Test"" IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001f: ldc.i4.2 IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0025: dup IL_0026: ldc.i4.0 IL_0027: ldc.i4.1 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: dup IL_0030: ldc.i4.1 IL_0031: ldc.i4.0 IL_0032: ldnull IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0038: stelem.ref IL_0039: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.BinaryOperation(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Linq.Expressions.ExpressionType, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003e: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0043: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_004d: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>>.Target"" IL_0052: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>> Test.<>o__2.<>p__0"" IL_0057: ldarg.0 IL_0058: ldarg.1 IL_0059: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, I1, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, I1, dynamic)"" IL_005e: pop IL_005f: br.s IL_0061 IL_0061: ret } "); } } else { var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); builder.AddRange( // (10,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x && x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + op + " x").WithLocation(10, 13), // (15,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y && y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + op + " y").WithLocation(15, 13), // (23,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a && a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + op + " a").WithLocation(23, 13), // (28,78): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b && b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "b " + op + op + " b").WithLocation(28, 78) ); if (op == "&" ? falseIsAbstract : trueIsAbstract) { builder.Add( // (33,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = b || c; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "b " + op + op + " c").WithLocation(33, 13) ); } builder.Add( // (38,98): error CS7083: Expression must be implicitly convertible to Boolean or its type 'T' must define operator 'true'. // _ = (System.Linq.Expressions.Expression<System.Action<T, dynamic>>)((T d, dynamic e) => (d || e).ToString()); Diagnostic(ErrorCode.ERR_InvalidDynamicCondition, "d").WithArguments("T", op == "&" ? "false" : "true").WithLocation(38, 98) ); compilation1.VerifyDiagnostics(builder.ToArrayAndFree()); } } [Theory] [CombinatorialData] public void ConsumeAbstractCompoundBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>")] string op) { var source1 = @" interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); static void M02(I1 x) { x " + op + @"= 1; } void M03(I1 y) { y " + op + @"= 2; } } interface I2<T> where T : I2<T> { abstract static T operator" + op + @" (T x, int y); } class Test { static void MT1(I1 a) { a " + op + @"= 3; } static void MT2<T>() where T : I2<T> { _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b " + op + @"= 4).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x /= 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + "= 1").WithLocation(8, 9), // (13,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // y /= 2; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + "= 2").WithLocation(13, 9), // (26,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // a /= 3; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + "= 3").WithLocation(26, 9), // (31,78): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action<T>>)((T b) => (b /= 4).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "b " + op + "= 4").WithLocation(31, 78) ); } private static string BinaryOperatorKind(string op) { switch (op) { case "+": return "Add"; case "-": return "Subtract"; case "*": return "Multiply"; case "/": return "Divide"; case "%": return "Remainder"; case "<<": return "LeftShift"; case ">>": return "RightShift"; case "&": return "And"; case "|": return "Or"; case "^": return "ExclusiveOr"; case "<": return "LessThan"; case "<=": return "LessThanOrEqual"; case "==": return "Equals"; case "!=": return "NotEquals"; case ">=": return "GreaterThanOrEqual"; case ">": return "GreaterThan"; } throw TestExceptionUtilities.UnexpectedValue(op); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); abstract static bool operator == (I1<T> x, I1<T> y); abstract static bool operator != (I1<T> x, I1<T> y); static void M02((int, I1<T>) x) { _ = x " + op + @" x; } void M03((int, I1<T>) y) { _ = y " + op + @" y; } } class Test { static void MT1<T>((int, I1<T>) a) where T : I1<T> { _ = a " + op + @" a; } static void MT2<T>() where T : I1<T> { _ = (System.Linq.Expressions.Expression<System.Action<(int, T)>>)(((int, T) b) => (b " + op + @" b).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = x == x; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x " + op + " x").WithLocation(12, 13), // (17,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = y == y; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "y " + op + " y").WithLocation(17, 13), // (25,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = a == a; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "a " + op + " a").WithLocation(25, 13), // (30,92): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, T)>>)(((int, T) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(30, 92) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_03([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>")] string op) { string metadataName = BinaryOperatorName(op); bool isShiftOperator = op is "<<" or ">>"; var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static T0 operator" + op + @" (T0 x, int a); } partial class Test { static void M03<T, U>(T x) where T : U where U : I1<T> { _ = x " + op + @" 1; } static void M05<T, U>(T? y) where T : struct, U where U : I1<T> { _ = y " + op + @" 1; } } "; if (!isShiftOperator) { source1 += @" public partial interface I1<T0> { abstract static T0 operator" + op + @" (int a, T0 x); abstract static T0 operator" + op + @" (I1<T0> x, T0 a); abstract static T0 operator" + op + @" (T0 x, I1<T0> a); } partial class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = 1 " + op + @" x; } static void M04<T, U>(T? y) where T : struct, U where U : I1<T> { _ = 1 " + op + @" y; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { _ = x " + op + @" y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { _ = x " + op + @" y; } } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldarg.0 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(int, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_000e IL_000c: br.s IL_0022 IL_000e: ldc.i4.1 IL_000f: ldloca.s V_0 IL_0011: call ""readonly T T?.GetValueOrDefault()"" IL_0016: constrained. ""T"" IL_001c: call ""T I1<T>." + metadataName + @"(int, T)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: pop IL_000f: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_000e IL_000c: br.s IL_0022 IL_000e: ldloca.s V_0 IL_0010: call ""readonly T T?.GetValueOrDefault()"" IL_0015: ldc.i4.1 IL_0016: constrained. ""T"" IL_001c: call ""T I1<T>." + metadataName + @"(T, int)"" IL_0021: pop IL_0022: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 32 (0x20) .maxstack 2 .locals init (T? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brfalse.s IL_001f IL_000b: ldc.i4.1 IL_000c: ldloca.s V_0 IL_000e: call ""readonly T T?.GetValueOrDefault()"" IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + metadataName + @"(int, T)"" IL_001e: pop IL_001f: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: pop IL_000e: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 32 (0x20) .maxstack 2 .locals init (T? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brfalse.s IL_001f IL_000b: ldloca.s V_0 IL_000d: call ""readonly T T?.GetValueOrDefault()"" IL_0012: ldc.i4.1 IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + metadataName + @"(T, int)"" IL_001e: pop IL_001f: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " 1").Single(); Assert.Equal("x " + op + " 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.Binary, Type: T) (Syntax: 'x " + op + @" 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractComparisonBinaryOperator_03([CombinatorialValues("<", ">", "<=", ">=", "==", "!=")] string op) { string metadataName = BinaryOperatorName(op); var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static bool operator" + op + @" (T0 x, int a); abstract static bool operator" + op + @" (int a, T0 x); abstract static bool operator" + op + @" (I1<T0> x, T0 a); abstract static bool operator" + op + @" (T0 x, I1<T0> a); } partial class Test { static void M02<T, U>(T x) where T : U where U : I1<T> { _ = 1 " + op + @" x; } static void M03<T, U>(T x) where T : U where U : I1<T> { _ = x " + op + @" 1; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { _ = x " + op + @" y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { _ = x " + op + @" y; } } "; string matchingOp = MatchingBinaryOperator(op); source1 += @" public partial interface I1<T0> { abstract static bool operator" + matchingOp + @" (T0 x, int a); abstract static bool operator" + matchingOp + @" (int a, T0 x); abstract static bool operator" + matchingOp + @" (I1<T0> x, T0 a); abstract static bool operator" + matchingOp + @" (T0 x, I1<T0> a); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldarg.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(int, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: pop IL_000f: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + metadataName + @"(T, int)"" IL_000e: pop IL_000f: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(int, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: pop IL_000e: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""bool I1<T>." + metadataName + @"(T, int)"" IL_000d: pop IL_000e: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " 1").Single(); Assert.Equal("x " + op + " 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @") (OperatorMethod: System.Boolean I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x " + op + @" 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractLiftedComparisonBinaryOperator_03([CombinatorialValues("<", ">", "<=", ">=", "==", "!=")] string op) { string metadataName = BinaryOperatorName(op); var source1 = @" public partial interface I1<T0> where T0 : I1<T0> { abstract static bool operator" + op + @" (T0 x, T0 a); } partial class Test { static void M04<T, U>(T? x, T? y) where T : struct, U where U : I1<T> { _ = x " + op + @" y; } } "; string matchingOp = MatchingBinaryOperator(op); source1 += @" public partial interface I1<T0> { abstract static bool operator" + matchingOp + @" (T0 x, T0 a); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op is "==" or "!=") { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 61 (0x3d) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool T?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: beq.s IL_0017 IL_0015: br.s IL_003c IL_0017: ldloca.s V_0 IL_0019: call ""readonly bool T?.HasValue.get"" IL_001e: brtrue.s IL_0022 IL_0020: br.s IL_003c IL_0022: ldloca.s V_0 IL_0024: call ""readonly T T?.GetValueOrDefault()"" IL_0029: ldloca.s V_1 IL_002b: call ""readonly T T?.GetValueOrDefault()"" IL_0030: constrained. ""T"" IL_0036: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_003b: pop IL_003c: ret } "); } else { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool T?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: and IL_0014: brtrue.s IL_0018 IL_0016: br.s IL_0032 IL_0018: ldloca.s V_0 IL_001a: call ""readonly T T?.GetValueOrDefault()"" IL_001f: ldloca.s V_1 IL_0021: call ""readonly T T?.GetValueOrDefault()"" IL_0026: constrained. ""T"" IL_002c: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_0031: pop IL_0032: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op is "==" or "!=") { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 56 (0x38) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: bne.un.s IL_0037 IL_0014: ldloca.s V_0 IL_0016: call ""readonly bool T?.HasValue.get"" IL_001b: brfalse.s IL_0037 IL_001d: ldloca.s V_0 IL_001f: call ""readonly T T?.GetValueOrDefault()"" IL_0024: ldloca.s V_1 IL_0026: call ""readonly T T?.GetValueOrDefault()"" IL_002b: constrained. ""T"" IL_0031: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_0036: pop IL_0037: ret } "); } else { verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 48 (0x30) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool T?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: and IL_0013: brfalse.s IL_002f IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: ldloca.s V_1 IL_001e: call ""readonly T T?.GetValueOrDefault()"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>." + metadataName + @"(T, T)"" IL_002e: pop IL_002f: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + " y").Single(); Assert.Equal("x " + op + " y", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + BinaryOperatorKind(op) + @", IsLifted) (OperatorMethod: System.Boolean I1<T>." + metadataName + @"(T x, T a)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x " + op + @" y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T?) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T?) (Syntax: 'y') "); } [Theory] [InlineData("&", true, true)] [InlineData("|", true, true)] [InlineData("&", true, false)] [InlineData("|", true, false)] [InlineData("&", false, true)] [InlineData("|", false, true)] public void ConsumeAbstractLogicalBinaryOperator_03(string op, bool binaryIsAbstract, bool unaryIsAbstract) { var binaryMetadataName = op == "&" ? "op_BitwiseAnd" : "op_BitwiseOr"; var unaryMetadataName = op == "&" ? "op_False" : "op_True"; var opKind = op == "&" ? "ConditionalAnd" : "ConditionalOr"; if (binaryIsAbstract && unaryIsAbstract) { consumeAbstract(op); } else { consumeMixed(op, binaryIsAbstract, unaryIsAbstract); } void consumeAbstract(string op) { var source1 = @" public interface I1<T0> where T0 : I1<T0> { abstract static T0 operator" + op + @" (T0 a, T0 x); abstract static bool operator true (T0 x); abstract static bool operator false (T0 x); } public interface I2<T0> where T0 : struct, I2<T0> { abstract static T0 operator" + op + @" (T0 a, T0 x); abstract static bool operator true (T0? x); abstract static bool operator false (T0? x); } class Test { static void M03<T, U>(T x, T y) where T : U where U : I1<T> { _ = x " + op + op + @" y; } static void M04<T, U>(T? x, T? y) where T : struct, U where U : I2<T> { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 34 (0x22) .maxstack 2 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: constrained. ""T"" IL_000a: call ""bool I1<T>." + unaryMetadataName + @"(T)"" IL_000f: brtrue.s IL_0021 IL_0011: ldloc.0 IL_0012: ldarg.1 IL_0013: constrained. ""T"" IL_0019: call ""T I1<T>." + binaryMetadataName + @"(T, T)"" IL_001e: pop IL_001f: br.s IL_0021 IL_0021: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 69 (0x45) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: constrained. ""T"" IL_000a: call ""bool I2<T>." + unaryMetadataName + @"(T?)"" IL_000f: brtrue.s IL_0044 IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldarg.1 IL_0014: stloc.2 IL_0015: ldloca.s V_1 IL_0017: call ""readonly bool T?.HasValue.get"" IL_001c: ldloca.s V_2 IL_001e: call ""readonly bool T?.HasValue.get"" IL_0023: and IL_0024: brtrue.s IL_0028 IL_0026: br.s IL_0042 IL_0028: ldloca.s V_1 IL_002a: call ""readonly T T?.GetValueOrDefault()"" IL_002f: ldloca.s V_2 IL_0031: call ""readonly T T?.GetValueOrDefault()"" IL_0036: constrained. ""T"" IL_003c: call ""T I2<T>." + binaryMetadataName + @"(T, T)"" IL_0041: pop IL_0042: br.s IL_0044 IL_0044: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 31 (0x1f) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I1<T>." + unaryMetadataName + @"(T)"" IL_000e: brtrue.s IL_001e IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: constrained. ""T"" IL_0018: call ""T I1<T>." + binaryMetadataName + @"(T, T)"" IL_001d: pop IL_001e: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 64 (0x40) .maxstack 2 .locals init (T? V_0, T? V_1, T? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: constrained. ""T"" IL_0009: call ""bool I2<T>." + unaryMetadataName + @"(T?)"" IL_000e: brtrue.s IL_003f IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: ldarg.1 IL_0013: stloc.2 IL_0014: ldloca.s V_1 IL_0016: call ""readonly bool T?.HasValue.get"" IL_001b: ldloca.s V_2 IL_001d: call ""readonly bool T?.HasValue.get"" IL_0022: and IL_0023: brfalse.s IL_003f IL_0025: ldloca.s V_1 IL_0027: call ""readonly T T?.GetValueOrDefault()"" IL_002c: ldloca.s V_2 IL_002e: call ""readonly T T?.GetValueOrDefault()"" IL_0033: constrained. ""T"" IL_0039: call ""T I2<T>." + binaryMetadataName + @"(T, T)"" IL_003e: pop IL_003f: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + op + " y").First(); Assert.Equal("x " + op + op + " y", node1.ToString()); VerifyOperationTreeForNode(compilation1, model, node1, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + opKind + @") (OperatorMethod: T I1<T>." + binaryMetadataName + @"(T a, T x)) (OperationKind.Binary, Type: T) (Syntax: 'x " + op + op + @" y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T) (Syntax: 'y') "); } void consumeMixed(string op, bool binaryIsAbstract, bool unaryIsAbstract) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 a, I1 x)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (unaryIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (unaryIsAbstract ? ";" : " => throw null;") + @" " + (unaryIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (unaryIsAbstract ? ";" : " => throw null;") + @" } class Test { static void M03<T, U>(T x, T y) where T : U where U : I1 { _ = x " + op + op + @" y; } static void M04<T, U>(T? x, T? y) where T : struct, U where U : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch (binaryIsAbstract, unaryIsAbstract) { case (true, false): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000e: brtrue.s IL_0025 IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: box ""T"" IL_0017: constrained. ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T?"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000e: brtrue.s IL_0025 IL_0010: ldloc.0 IL_0011: ldarg.1 IL_0012: box ""T?"" IL_0017: constrained. ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); break; case (false, true): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: constrained. ""T"" IL_000f: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldarg.1 IL_0018: box ""T"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 38 (0x26) .maxstack 2 .locals init (I1 V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T?"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: constrained. ""T"" IL_000f: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldarg.1 IL_0018: box ""T?"" IL_001d: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0022: pop IL_0023: br.s IL_0025 IL_0025: ret } "); break; default: Assert.True(false); break; } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); switch (binaryIsAbstract, unaryIsAbstract) { case (true, false): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000d: brtrue.s IL_0022 IL_000f: ldloc.0 IL_0010: ldarg.1 IL_0011: box ""T"" IL_0016: constrained. ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_000d: brtrue.s IL_0022 IL_000f: ldloc.0 IL_0010: ldarg.1 IL_0011: box ""T?"" IL_0016: constrained. ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); break; case (false, true): verifier.VerifyIL("Test.M03<T, U>(T, T)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: constrained. ""T"" IL_000e: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0013: brtrue.s IL_0022 IL_0015: ldloc.0 IL_0016: ldarg.1 IL_0017: box ""T"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?, T?)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (I1 V_0) IL_0000: ldarg.0 IL_0001: box ""T?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: constrained. ""T"" IL_000e: call ""bool I1." + unaryMetadataName + @"(I1)"" IL_0013: brtrue.s IL_0022 IL_0015: ldloc.0 IL_0016: ldarg.1 IL_0017: box ""T?"" IL_001c: call ""I1 I1." + binaryMetadataName + @"(I1, I1)"" IL_0021: pop IL_0022: ret } "); break; default: Assert.True(false); break; } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Where(n => n.ToString() == "x " + op + op + " y").First(); Assert.Equal("x " + op + op + " y", node1.ToString()); VerifyOperationTreeForNode(compilation1, model, node1, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IBinaryOperation (BinaryOperatorKind." + opKind + @") (OperatorMethod: I1 I1." + binaryMetadataName + @"(I1 a, I1 x)) (OperationKind.Binary, Type: I1) (Syntax: 'x " + op + op + @" y') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: I1, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: I1, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: T) (Syntax: 'y') "); } } [Theory] [InlineData("+", "op_Addition", "Add")] [InlineData("-", "op_Subtraction", "Subtract")] [InlineData("*", "op_Multiply", "Multiply")] [InlineData("/", "op_Division", "Divide")] [InlineData("%", "op_Modulus", "Remainder")] [InlineData("&", "op_BitwiseAnd", "And")] [InlineData("|", "op_BitwiseOr", "Or")] [InlineData("^", "op_ExclusiveOr", "ExclusiveOr")] [InlineData("<<", "op_LeftShift", "LeftShift")] [InlineData(">>", "op_RightShift", "RightShift")] public void ConsumeAbstractCompoundBinaryOperator_03(string op, string metadataName, string operatorKind) { bool isShiftOperator = op.Length == 2; var source1 = @" public interface I1<T0> where T0 : I1<T0> { "; if (!isShiftOperator) { source1 += @" abstract static int operator" + op + @" (int a, T0 x); abstract static I1<T0> operator" + op + @" (I1<T0> x, T0 a); abstract static T0 operator" + op + @" (T0 x, I1<T0> a); "; } source1 += @" abstract static T0 operator" + op + @" (T0 x, int a); } class Test { "; if (!isShiftOperator) { source1 += @" static void M02<T, U>(int a, T x) where T : U where U : I1<T> { a " + op + @"= x; } static void M04<T, U>(int? a, T? y) where T : struct, U where U : I1<T> { a " + op + @"= y; } static void M06<T, U>(I1<T> x, T y) where T : U where U : I1<T> { x " + op + @"= y; } static void M07<T, U>(T x, I1<T> y) where T : U where U : I1<T> { x " + op + @"= y; } "; } source1 += @" static void M03<T, U>(T x) where T : U where U : I1<T> { x " + op + @"= 1; } static void M05<T, U>(T? y) where T : struct, U where U : I1<T> { y " + op + @"= 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(int, T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""int I1<T>." + metadataName + @"(int, T)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?, T?)", @" { // Code size 66 (0x42) .maxstack 2 .locals init (int? V_0, T? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloca.s V_0 IL_0007: call ""readonly bool int?.HasValue.get"" IL_000c: ldloca.s V_1 IL_000e: call ""readonly bool T?.HasValue.get"" IL_0013: and IL_0014: brtrue.s IL_0021 IL_0016: ldloca.s V_2 IL_0018: initobj ""int?"" IL_001e: ldloc.2 IL_001f: br.s IL_003f IL_0021: ldloca.s V_0 IL_0023: call ""readonly int int?.GetValueOrDefault()"" IL_0028: ldloca.s V_1 IL_002a: call ""readonly T T?.GetValueOrDefault()"" IL_002f: constrained. ""T"" IL_0035: call ""int I1<T>." + metadataName + @"(int, T)"" IL_003a: newobj ""int?..ctor(int)"" IL_003f: starg.s V_0 IL_0041: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""I1<T> I1<T>." + metadataName + @"(I1<T>, T)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000e: starg.s V_0 IL_0010: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: constrained. ""T"" IL_0009: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000e: starg.s V_0 IL_0010: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 50 (0x32) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002f IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: ldc.i4.1 IL_001f: constrained. ""T"" IL_0025: call ""T I1<T>." + metadataName + @"(T, int)"" IL_002a: newobj ""T?..ctor(T)"" IL_002f: starg.s V_0 IL_0031: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (!isShiftOperator) { verifier.VerifyIL("Test.M02<T, U>(int, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(int, T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?, T?)", @" { // Code size 65 (0x41) .maxstack 2 .locals init (int? V_0, T? V_1, int? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""readonly bool int?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""readonly bool T?.HasValue.get"" IL_0012: and IL_0013: brtrue.s IL_0020 IL_0015: ldloca.s V_2 IL_0017: initobj ""int?"" IL_001d: ldloc.2 IL_001e: br.s IL_003e IL_0020: ldloca.s V_0 IL_0022: call ""readonly int int?.GetValueOrDefault()"" IL_0027: ldloca.s V_1 IL_0029: call ""readonly T T?.GetValueOrDefault()"" IL_002e: constrained. ""T"" IL_0034: call ""int I1<T>." + metadataName + @"(int, T)"" IL_0039: newobj ""int?..ctor(int)"" IL_003e: starg.s V_0 IL_0040: ret } "); verifier.VerifyIL("Test.M06<T, U>(I1<T>, T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""I1<T> I1<T>." + metadataName + @"(I1<T>, T)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M07<T, U>(T, I1<T>)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, I1<T>)"" IL_000d: starg.s V_0 IL_000f: ret } "); } verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(T, int)"" IL_000d: starg.s V_0 IL_000f: ret } "); verifier.VerifyIL("Test.M05<T, U>(T?)", @" { // Code size 49 (0x31) .maxstack 2 .locals init (T? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0016 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: br.s IL_002e IL_0016: ldloca.s V_0 IL_0018: call ""readonly T T?.GetValueOrDefault()"" IL_001d: ldc.i4.1 IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(T, int)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: starg.s V_0 IL_0030: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(n => n.ToString() == "x " + op + "= 1").Single(); Assert.Equal("x " + op + "= 1", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" ICompoundAssignmentOperation (BinaryOperatorKind." + operatorKind + @") (OperatorMethod: T I1<T>." + metadataName + @"(T x, System.Int32 a)) (OperationKind.CompoundAssignment, Type: T) (Syntax: 'x " + op + @"= 1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } class Test { static void M02<T, U>((int, T) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0011: bne.un.s IL_002c IL_0013: ldloc.0 IL_0014: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001f: constrained. ""T"" IL_0025: call ""bool I1<T>.op_Equality(T, T)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.0 IL_002d: pop IL_002e: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0011: bne.un.s IL_002c IL_0013: ldloc.0 IL_0014: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001f: constrained. ""T"" IL_0025: call ""bool I1<T>.op_Inequality(T, T)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.1 IL_002d: pop IL_002e: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0010: bne.un.s IL_002b IL_0012: ldloc.0 IL_0013: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001e: constrained. ""T"" IL_0024: call ""bool I1<T>.op_Equality(T, T)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, T>)", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (System.ValueTuple<int, T> V_0, System.ValueTuple<int, T> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, T>.Item1"" IL_0010: bne.un.s IL_002b IL_0012: ldloc.0 IL_0013: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""T System.ValueTuple<int, T>.Item2"" IL_001e: constrained. ""T"" IL_0024: call ""bool I1<T>.op_Inequality(T, T)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.1 IL_002c: pop IL_002d: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, T)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, T)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1 { _ = x " + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x - y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " y").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator- (I1 x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 32) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_04(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" } "; var source2 = @" class Test { static void M02<T>(T x, T y) where T : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); if (success) { compilation2.VerifyDiagnostics(); } else { compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x && y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + op + " y").WithLocation(6, 13) ); } var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); if (binaryIsAbstract) { builder.Add( // (12,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator& (I1 x, I1 y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 32) ); } if (trueIsAbstract) { builder.Add( // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "true").WithLocation(13, 35) ); } if (falseIsAbstract) { builder.Add( // (14,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "false").WithLocation(14, 35) ); } compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation).Verify(builder.ToArrayAndFree()); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("*")] [InlineData("/")] [InlineData("%")] [InlineData("&")] [InlineData("|")] [InlineData("^")] [InlineData("<<")] [InlineData(">>")] public void ConsumeAbstractCompoundBinaryOperator_04(string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + op + @" (T x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1<T> { x " + op + @"= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // x *= y; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + "= y").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator* (T x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(12, 31) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } "; var source2 = @" class Test { static void M02<T>((int, T) x) where T : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator == (T x, T y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "==").WithLocation(12, 35), // (13,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static bool operator != (T x, T y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "!=").WithLocation(13, 35) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperator_06([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator" + op + @" (I1 x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1 { _ = x " + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x - y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " y").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator- (I1 x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 32) ); } [Theory] [InlineData("&", true, false, false, false)] [InlineData("|", true, false, false, false)] [InlineData("&", false, false, true, false)] [InlineData("|", false, true, false, false)] [InlineData("&", true, false, true, false)] [InlineData("|", true, true, false, false)] [InlineData("&", false, true, false, true)] [InlineData("|", false, false, true, true)] public void ConsumeAbstractLogicalBinaryOperator_06(string op, bool binaryIsAbstract, bool trueIsAbstract, bool falseIsAbstract, bool success) { var source1 = @" public interface I1 { " + (binaryIsAbstract ? "abstract " : "") + @"static I1 operator" + op + @" (I1 x, I1 y)" + (binaryIsAbstract ? ";" : " => throw null;") + @" " + (trueIsAbstract ? "abstract " : "") + @"static bool operator true (I1 x)" + (trueIsAbstract ? ";" : " => throw null;") + @" " + (falseIsAbstract ? "abstract " : "") + @"static bool operator false (I1 x)" + (falseIsAbstract ? ";" : " => throw null;") + @" } "; var source2 = @" class Test { static void M02<T>(T x, T y) where T : I1 { _ = x " + op + op + @" y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreAppAndCSharp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); if (success) { compilation2.VerifyDiagnostics(); } else { compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x && y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + op + " y").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); } var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); if (binaryIsAbstract) { builder.Add( // (12,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator& (I1 x, I1 y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 32) ); } if (trueIsAbstract) { builder.Add( // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator true (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "true").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } if (falseIsAbstract) { builder.Add( // (14,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator false (I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "false").WithArguments("abstract", "9.0", "preview").WithLocation(14, 35) ); } compilation3.VerifyDiagnostics(builder.ToArrayAndFree()); } [Theory] [InlineData("+")] [InlineData("-")] [InlineData("*")] [InlineData("/")] [InlineData("%")] [InlineData("&")] [InlineData("|")] [InlineData("^")] [InlineData("<<")] [InlineData(">>")] public void ConsumeAbstractCompoundBinaryOperator_06(string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator" + op + @" (T x, int y); } "; var source2 = @" class Test { static void M02<T>(T x, int y) where T : I1<T> { x " + op + @"= y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // x <<= y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + "= y").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,31): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator<< (T x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(12, 31) ); } [Theory] [CombinatorialData] public void ConsumeAbstractBinaryOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static bool operator == (T x, T y); abstract static bool operator != (T x, T y); } "; var source2 = @" class Test { static void M02<T>((int, T) x) where T : I1<T> { _ = x " + op + @" x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (12,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator == (T x, T y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "==").WithArguments("abstract", "9.0", "preview").WithLocation(12, 35), // (13,35): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static bool operator != (T x, T y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "!=").WithArguments("abstract", "9.0", "preview").WithLocation(13, 35) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { _ = P01; _ = P04; } void M03() { _ = this.P01; _ = this.P04; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { _ = I1.P01; _ = x.P01; _ = I1.P04; _ = x.P04; } static void MT2<T>() where T : I1 { _ = T.P03; _ = T.P04; _ = T.P00; _ = T.P05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01.ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = P01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 13), // (14,13): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = this.P01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 13), // (15,13): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = this.P04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 13), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = I1.P01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 13), // (28,13): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = x.P01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 13), // (30,13): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = x.P04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 13), // (35,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 13), // (36,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 13), // (37,13): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = T.P00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 13), // (38,15): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = T.P05; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 15), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01.ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticPropertySet_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { P01 = 1; P04 = 1; } void M03() { this.P01 = 1; this.P04 = 1; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { I1.P01 = 1; x.P01 = 1; I1.P04 = 1; x.P04 = 1; } static void MT2<T>() where T : I1 { T.P03 = 1; T.P04 = 1; T.P00 = 1; T.P05 = 1; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 = 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 = 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 = 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 = 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 = 1; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 = 1").WithLocation(40, 71), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 = 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_01() { var source1 = @" interface I1 { abstract static int P01 { get; set;} static void M02() { P01 += 1; P04 += 1; } void M03() { this.P01 += 1; this.P04 += 1; } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { I1.P01 += 1; x.P01 += 1; I1.P04 += 1; x.P04 += 1; } static void MT2<T>() where T : I1 { T.P03 += 1; T.P04 += 1; T.P00 += 1; T.P05 += 1; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += 1; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 += 1; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 += 1; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 += 1").WithLocation(40, 71), // (40,71): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += 1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.P01").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticProperty_02() { var source1 = @" interface I1 { abstract static int P01 { get; set; } static void M02() { _ = nameof(P01); _ = nameof(P04); } void M03() { _ = nameof(this.P01); _ = nameof(this.P04); } static int P04 { get; set; } protected abstract static int P05 { get; set; } } class Test { static void MT1(I1 x) { _ = nameof(I1.P01); _ = nameof(x.P01); _ = nameof(I1.P04); _ = nameof(x.P04); } static void MT2<T>() where T : I1 { _ = nameof(T.P03); _ = nameof(T.P04); _ = nameof(T.P00); _ = nameof(T.P05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (14,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 20), // (15,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 20), // (28,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 20), // (30,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 20), // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = nameof(T.P05); Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""int I1.P01.get"" IL_000c: pop IL_000d: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: constrained. ""T"" IL_0006: call ""int I1.P01.get"" IL_000b: pop IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Right; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertySet_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 15 (0xf) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: constrained. ""T"" IL_0008: call ""void I1.P01.set"" IL_000d: nop IL_000e: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: constrained. ""T"" IL_0007: call ""void I1.P01.set"" IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertyCompound_03() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } class Test { static void M02<T, U>() where T : U where U : I1 { T.P01 += 1; } static string M03<T, U>() where T : U where U : I1 { return nameof(T.P01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: nop IL_0001: constrained. ""T"" IL_0007: call ""int I1.P01.get"" IL_000c: ldc.i4.1 IL_000d: add IL_000e: constrained. ""T"" IL_0014: call ""void I1.P01.set"" IL_0019: nop IL_001a: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""P01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: constrained. ""T"" IL_0006: call ""int I1.P01.get"" IL_000b: ldc.i4.1 IL_000c: add IL_000d: constrained. ""T"" IL_0013: call ""void I1.P01.set"" IL_0018: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""P01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.P01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IPropertyReferenceOperation: System.Int32 I1.P01 { get; set; } (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'T.P01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Equal("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "P01").Single().ToTestDisplayString()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("System.Int32 I1.P01 { get; set; }", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("P01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticPropertyGet_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = T.P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertySet_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 = 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_04() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9), // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += 1; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(12, 31), // (12,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(12, 36) ); } [Fact] public void ConsumeAbstractStaticPropertyGet_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = T.P01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = T.P01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = T.P01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 13), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticPropertySet_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 = 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 = 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 = 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticPropertyCompound_06() { var source1 = @" public interface I1 { abstract static int P01 { get; set; } } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += 1; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int P01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 25) ); } [Fact] public void ConsumeAbstractStaticEventAdd_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used interface I1 { abstract static event System.Action P01; static void M02() { P01 += null; P04 += null; } void M03() { this.P01 += null; this.P04 += null; } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { I1.P01 += null; x.P01 += null; I1.P04 += null; x.P04 += null; } static void MT2<T>() where T : I1 { T.P03 += null; T.P04 += null; T.P00 += null; T.P05 += null; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += null); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01 += null").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (14,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // this.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "this.P01 += null").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01 += null").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (28,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x.P01 += null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x.P01 += null").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 += null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 += null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 += null; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 += null); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 += null").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticEventRemove_01() { var source1 = @"#pragma warning disable CS0067 // The event is never used interface I1 { abstract static event System.Action P01; static void M02() { P01 -= null; P04 -= null; } void M03() { this.P01 -= null; this.P04 -= null; } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { I1.P01 -= null; x.P01 -= null; I1.P04 -= null; x.P04 -= null; } static void MT2<T>() where T : I1 { T.P03 -= null; T.P04 -= null; T.P00 -= null; T.P05 -= null; _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 -= null); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "P01 -= null").WithLocation(8, 9), // (14,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // this.P01 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 9), // (14,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // this.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "this.P01 -= null").WithLocation(14, 9), // (15,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // this.P04 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 9), // (27,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // I1.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.P01 -= null").WithLocation(27, 9), // (28,9): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // x.P01 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 9), // (28,9): error CS8926: A static abstract interface member can be accessed only on a type parameter. // x.P01 -= null; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "x.P01 -= null").WithLocation(28, 9), // (30,9): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // x.P04 -= null; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 9), // (35,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P03 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 9), // (36,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P04 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 9), // (37,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.P00 -= null; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 9), // (38,11): error CS0122: 'I1.P05' is inaccessible due to its protection level // T.P05 -= null; Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 11), // (40,71): error CS0832: An expression tree may not contain an assignment operator // _ = (System.Linq.Expressions.Expression<System.Action>)(() => T.P01 -= null); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "T.P01 -= null").WithLocation(40, 71) ); } [Fact] public void ConsumeAbstractStaticEvent_02() { var source1 = @" interface I1 { abstract static event System.Action P01; static void M02() { _ = nameof(P01); _ = nameof(P04); } void M03() { _ = nameof(this.P01); _ = nameof(this.P04); } static event System.Action P04; protected abstract static event System.Action P05; } class Test { static void MT1(I1 x) { _ = nameof(I1.P01); _ = nameof(x.P01); _ = nameof(I1.P04); _ = nameof(x.P04); } static void MT2<T>() where T : I1 { _ = nameof(T.P03); _ = nameof(T.P04); _ = nameof(T.P00); _ = nameof(T.P05); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (14,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P01").WithArguments("I1.P01").WithLocation(14, 20), // (15,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(this.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.P04").WithArguments("I1.P04").WithLocation(15, 20), // (28,20): error CS0176: Member 'I1.P01' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P01").WithArguments("I1.P01").WithLocation(28, 20), // (30,20): error CS0176: Member 'I1.P04' cannot be accessed with an instance reference; qualify it with a type name instead // _ = nameof(x.P04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.P04").WithArguments("I1.P04").WithLocation(30, 20), // (35,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 20), // (36,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 20), // (37,20): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = nameof(T.P00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 20), // (38,22): error CS0122: 'I1.P05' is inaccessible due to its protection level // _ = nameof(T.P05); Diagnostic(ErrorCode.ERR_BadAccess, "P05").WithArguments("I1.P05").WithLocation(38, 22) ); } [Fact] public void ConsumeAbstractStaticEvent_03() { var source1 = @" public interface I1 { abstract static event System.Action E01; } class Test { static void M02<T, U>() where T : U where U : I1 { T.E01 += null; T.E01 -= null; } static string M03<T, U>() where T : U where U : I1 { return nameof(T.E01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 28 (0x1c) .maxstack 1 IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: call ""void I1.E01.add"" IL_000d: nop IL_000e: ldnull IL_000f: constrained. ""T"" IL_0015: call ""void I1.E01.remove"" IL_001a: nop IL_001b: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""E01"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 25 (0x19) .maxstack 1 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: call ""void I1.E01.add"" IL_000c: ldnull IL_000d: constrained. ""T"" IL_0013: call ""void I1.E01.remove"" IL_0018: ret } "); verifier.VerifyIL("Test.M03<T, U>()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""E01"" IL_0005: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First().Left; Assert.Equal("T.E01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IEventReferenceOperation: event System.Action I1.E01 (Static) (OperationKind.EventReference, Type: System.Action) (Syntax: 'T.E01') Instance Receiver: null "); var m02 = compilation1.GetMember<MethodSymbol>("Test.M02"); Assert.Equal("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0], "E01").Single().ToTestDisplayString()); Assert.Equal("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0], "E01").Single().ToTestDisplayString()); Assert.Contains("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupSymbols(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Contains("event System.Action I1.E01", ((CSharpSemanticModel)model).LookupStaticMembers(node.SpanStart, m02.TypeParameters[0]).ToTestDisplayStrings()); Assert.Equal("event System.Action I1.E01", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "E01").Single().ToTestDisplayString()); Assert.Equal("event System.Action I1.E01", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol(), "E01").Single().ToTestDisplayString()); Assert.Contains("event System.Action I1.E01", model.LookupSymbols(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("event System.Action I1.E01", model.LookupStaticMembers(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol()).ToTestDisplayStrings()); Assert.Contains("E01", model.LookupNames(node.SpanStart, m02.TypeParameters[0].GetPublicSymbol())); } [Fact] public void ConsumeAbstractStaticEventAdd_04() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 += null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01 += null").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "P01").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventRemove_04() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8919: Target runtime doesn't support static abstract members in interfaces. // T.P01 -= null; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.P01 -= null").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "P01").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventAdd_06() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 += null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 += null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticEventRemove_06() { var source1 = @" public interface I1 { abstract static event System.Action P01; } "; var source2 = @" class Test { static void M02<T>() where T : I1 { T.P01 -= null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 -= null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,9): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // T.P01 -= null; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 9), // (12,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action P01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 41) ); } [Fact] public void ConsumeAbstractStaticIndexedProperty_03() { var ilSource = @" .class interface public auto ansi abstract I1 { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6d 00 00 ) // Methods .method public hidebysig specialname newslot abstract virtual static int32 get_Item ( int32 x ) cil managed { } // end of method I1::get_Item .method public hidebysig specialname newslot abstract virtual static void set_Item ( int32 x, int32 'value' ) cil managed { } // end of method I1::set_Item // Properties .property int32 Item( int32 x ) { .get int32 I1::get_Item(int32) .set void I1::set_Item(int32, int32) } } // end of class I1 "; var source1 = @" class Test { static void M02<T>() where T : I1 { T.Item[0] += 1; } static string M03<T>() where T : I1 { return nameof(T.Item); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.Item[0] += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(6, 9), // (11,23): error CS0119: 'T' is a type parameter, which is not valid in the given context // return nameof(T.Item); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(11, 23) ); var source2 = @" class Test { static void M02<T>() where T : I1 { T[0] += 1; } static void M03<T>() where T : I1 { T.set_Item(0, T.get_Item(0) + 1); } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,9): error CS0119: 'T' is a type, which is not valid in the given context // T[0] += 1; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(6, 9), // (11,11): error CS0571: 'I1.this[int].set': cannot explicitly call operator or accessor // T.set_Item(0, T.get_Item(0) + 1); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Item").WithArguments("I1.this[int].set").WithLocation(11, 11), // (11,25): error CS0571: 'I1.this[int].get': cannot explicitly call operator or accessor // T.set_Item(0, T.get_Item(0) + 1); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Item").WithArguments("I1.this[int].get").WithLocation(11, 25) ); } [Fact] public void ConsumeAbstractStaticIndexedProperty_04() { var ilSource = @" .class interface public auto ansi abstract I1 { // Methods .method public hidebysig specialname newslot abstract virtual static int32 get_Item ( int32 x ) cil managed { } // end of method I1::get_Item .method public hidebysig specialname newslot abstract virtual static void set_Item ( int32 x, int32 'value' ) cil managed { } // end of method I1::set_Item // Properties .property int32 Item( int32 x ) { .get int32 I1::get_Item(int32) .set void I1::set_Item(int32, int32) } } // end of class I1 "; var source1 = @" class Test { static void M02<T>() where T : I1 { T.Item[0] += 1; } static string M03<T>() where T : I1 { return nameof(T.Item); } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (6,11): error CS1545: Property, indexer, or event 'I1.Item[int]' is not supported by the language; try directly calling accessor methods 'I1.get_Item(int)' or 'I1.set_Item(int, int)' // T.Item[0] += 1; Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Item").WithArguments("I1.Item[int]", "I1.get_Item(int)", "I1.set_Item(int, int)").WithLocation(6, 11), // (11,25): error CS1545: Property, indexer, or event 'I1.Item[int]' is not supported by the language; try directly calling accessor methods 'I1.get_Item(int)' or 'I1.set_Item(int, int)' // return nameof(T.Item); Diagnostic(ErrorCode.ERR_BindToBogusProp2, "Item").WithArguments("I1.Item[int]", "I1.get_Item(int)", "I1.set_Item(int, int)").WithLocation(11, 25) ); var source2 = @" class Test { static void M02<T>() where T : I1 { T.set_Item(0, T.get_Item(0) + 1); } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation2, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T>()", @" { // Code size 29 (0x1d) .maxstack 3 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: ldc.i4.0 IL_0003: constrained. ""T"" IL_0009: call ""int I1.get_Item(int)"" IL_000e: ldc.i4.1 IL_000f: add IL_0010: constrained. ""T"" IL_0016: call ""void I1.set_Item(int, int)"" IL_001b: nop IL_001c: ret } "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = (System.Action)M01; _ = (System.Action)M04; } void M03() { _ = (System.Action)this.M01; _ = (System.Action)this.M04; } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = (System.Action)I1.M01; _ = (System.Action)x.M01; _ = (System.Action)I1.M04; _ = (System.Action)x.M04; } static void MT2<T>() where T : I1 { _ = (System.Action)T.M03; _ = (System.Action)T.M04; _ = (System.Action)T.M00; _ = (System.Action)T.M05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.Action)T.M01).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (System.Action)M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(System.Action)M01").WithLocation(8, 13), // (14,28): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)this.M01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 28), // (15,28): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)this.M04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 28), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (System.Action)I1.M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(System.Action)I1.M01").WithLocation(27, 13), // (28,28): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)x.M01; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 28), // (30,28): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = (System.Action)x.M04; Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 28), // (35,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 28), // (36,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 28), // (37,28): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (System.Action)T.M00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 28), // (38,30): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = (System.Action)T.M05; Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 30), // (40,87): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.Action)T.M01).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01").WithLocation(40, 87) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_03() { var source1 = @" public interface I1 { abstract static void M01(); } class Test { static System.Action M02<T, U>() where T : U where U : I1 { return T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 24 (0x18) .maxstack 2 .locals init (System.Action V_0) IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: ldftn ""void I1.M01()"" IL_000e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0012: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = (System.Action)T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "(System.Action)T.M01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToDelegate_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = (System.Action)T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,28): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 28) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,28): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (System.Action)T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 28), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_01() { var source1 = @" interface I1 { abstract static void M01(); static void M02() { _ = new System.Action(M01); _ = new System.Action(M04); } void M03() { _ = new System.Action(this.M01); _ = new System.Action(this.M04); } static void M04() {} protected abstract static void M05(); } class Test { static void MT1(I1 x) { _ = new System.Action(I1.M01); _ = new System.Action(x.M01); _ = new System.Action(I1.M04); _ = new System.Action(x.M04); } static void MT2<T>() where T : I1 { _ = new System.Action(T.M03); _ = new System.Action(T.M04); _ = new System.Action(T.M00); _ = new System.Action(T.M05); _ = (System.Linq.Expressions.Expression<System.Action>)(() => new System.Action(T.M01).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,31): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = new System.Action(M01); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "M01").WithLocation(8, 31), // (14,31): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(this.M01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M01").WithArguments("I1.M01()").WithLocation(14, 31), // (15,31): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(this.M04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.M04").WithArguments("I1.M04()").WithLocation(15, 31), // (27,31): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = new System.Action(I1.M01); Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "I1.M01").WithLocation(27, 31), // (28,31): error CS0176: Member 'I1.M01()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(x.M01); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M01").WithArguments("I1.M01()").WithLocation(28, 31), // (30,31): error CS0176: Member 'I1.M04()' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new System.Action(x.M04); Diagnostic(ErrorCode.ERR_ObjectProhibited, "x.M04").WithArguments("I1.M04()").WithLocation(30, 31), // (35,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M03); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 31), // (36,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M04); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 31), // (37,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = new System.Action(T.M00); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 31), // (38,33): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = new System.Action(T.M05); Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 33), // (40,89): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Action>)(() => new System.Action(T.M01).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, "T.M01").WithLocation(40, 89) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_03() { var source1 = @" public interface I1 { abstract static void M01(); } class Test { static System.Action M02<T, U>() where T : U where U : I1 { return new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 24 (0x18) .maxstack 2 .locals init (System.Action V_0) IL_0000: nop IL_0001: ldnull IL_0002: constrained. ""T"" IL_0008: ldftn ""void I1.M01()"" IL_000e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldnull IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0012: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "T.M01").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_DelegateCreation_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" class Test { static void M02<T>() where T : I1 { _ = new System.Action(T.M01); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = new System.Action(T.M01); Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_01() { var source1 = @" unsafe interface I1 { abstract static void M01(); static void M02() { _ = (delegate*<void>)&M01; _ = (delegate*<void>)&M04; } void M03() { _ = (delegate*<void>)&this.M01; _ = (delegate*<void>)&this.M04; } static void M04() {} protected abstract static void M05(); } unsafe class Test { static void MT1(I1 x) { _ = (delegate*<void>)&I1.M01; _ = (delegate*<void>)&x.M01; _ = (delegate*<void>)&I1.M04; _ = (delegate*<void>)&x.M04; } static void MT2<T>() where T : I1 { _ = (delegate*<void>)&T.M03; _ = (delegate*<void>)&T.M04; _ = (delegate*<void>)&T.M00; _ = (delegate*<void>)&T.M05; _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (delegate*<void>)&M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(delegate*<void>)&M01").WithLocation(8, 13), // (14,13): error CS8757: No overload for 'M01' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&this.M01; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&this.M01").WithArguments("M01", "delegate*<void>").WithLocation(14, 13), // (15,13): error CS8757: No overload for 'M04' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&this.M04; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&this.M04").WithArguments("M04", "delegate*<void>").WithLocation(15, 13), // (27,13): error CS8926: A static abstract interface member can be accessed only on a type parameter. // _ = (delegate*<void>)&I1.M01; Diagnostic(ErrorCode.ERR_BadAbstractStaticMemberAccess, "(delegate*<void>)&I1.M01").WithLocation(27, 13), // (28,13): error CS8757: No overload for 'M01' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&x.M01; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&x.M01").WithArguments("M01", "delegate*<void>").WithLocation(28, 13), // (30,13): error CS8757: No overload for 'M04' matches function pointer 'delegate*<void>' // _ = (delegate*<void>)&x.M04; Diagnostic(ErrorCode.ERR_MethFuncPtrMismatch, "(delegate*<void>)&x.M04").WithArguments("M04", "delegate*<void>").WithLocation(30, 13), // (35,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M03; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(35, 31), // (36,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M04; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(36, 31), // (37,31): error CS0119: 'T' is a type parameter, which is not valid in the given context // _ = (delegate*<void>)&T.M00; Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter").WithLocation(37, 31), // (38,33): error CS0122: 'I1.M05()' is inaccessible due to its protection level // _ = (delegate*<void>)&T.M05; Diagnostic(ErrorCode.ERR_BadAccess, "M05").WithArguments("I1.M05()").WithLocation(38, 33), // (40,88): error CS1944: An expression tree may not contain an unsafe pointer operation // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "(delegate*<void>)&T.M01").WithLocation(40, 88), // (40,106): error CS8810: '&' on method groups cannot be used in expression trees // _ = (System.Linq.Expressions.Expression<System.Action>)(() => ((System.IntPtr)((delegate*<void>)&T.M01)).ToString()); Diagnostic(ErrorCode.ERR_AddressOfMethodGroupInExpressionTree, "T.M01").WithLocation(40, 106) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_03() { var source1 = @" public interface I1 { abstract static void M01(); } unsafe class Test { static delegate*<void> M02<T, U>() where T : U where U : I1 { return &T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 18 (0x12) .maxstack 1 .locals init (delegate*<void> V_0) IL_0000: nop IL_0001: constrained. ""T"" IL_0007: ldftn ""void I1.M01()"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>()", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: constrained. ""T"" IL_0006: ldftn ""void I1.M01()"" IL_000c: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("T.M01", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" qualifier is important for this invocation, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IMethodReferenceOperation: void I1.M01() (IsVirtual) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'T.M01') Instance Receiver: null "); } [Fact] public void ConsumeAbstractStaticMethod_ConversionFunctionPointer_04() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" unsafe class Test { static void M02<T>() where T : I1 { _ = (delegate*<void>)&T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "(delegate*<void>)&T.M01").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (12,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(12, 26) ); } [Fact] public void ConsumeAbstractStaticMethod_ConversionToFunctionPointer_06() { var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = @" unsafe class Test { static void M02<T>() where T : I1 { _ = (delegate*<void>)&T.M01; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (6,31): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = (delegate*<void>)&T.M01; Diagnostic(ErrorCode.ERR_FeatureInPreview, "T").WithArguments("static abstract members in interfaces").WithLocation(6, 31), // (12,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(12, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public void M01() {} } " + typeKeyword + @" C3 : I1 { static void M01() {} } " + typeKeyword + @" C4 : I1 { void I1.M01() {} } " + typeKeyword + @" C5 : I1 { public static int M01() => throw null; } " + typeKeyword + @" C6 : I1 { static int I1.M01() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01()' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01()").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01()'. 'C2.M01()' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01()", "C2.M01()").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01()'. 'C3.M01()' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01()", "C3.M01()").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01()' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01()").WithLocation(24, 10), // (26,13): error CS0539: 'C4.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01()").WithLocation(26, 13), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01()'. 'C5.M01()' cannot implement 'I1.M01()' because it does not have the matching return type of 'void'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01()", "C5.M01()", "void").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01()' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01()").WithLocation(36, 10), // (38,19): error CS0539: 'C6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01()").WithLocation(38, 19) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract void M01(); } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static void M01() {} } " + typeKeyword + @" C3 : I1 { void M01() {} } " + typeKeyword + @" C4 : I1 { static void I1.M01() {} } " + typeKeyword + @" C5 : I1 { public int M01() => throw null; } " + typeKeyword + @" C6 : I1 { int I1.M01() => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01()' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01()").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01()'. 'C2.M01()' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01()", "C2.M01()").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01()'. 'C3.M01()' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01()", "C3.M01()").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01()' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01()").WithLocation(24, 10), // (26,20): error CS0539: 'C4.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01()").WithLocation(26, 20), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01()'. 'C5.M01()' cannot implement 'I1.M01()' because it does not have the matching return type of 'void'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01()", "C5.M01()", "void").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01()' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01()").WithLocation(36, 10), // (38,12): error CS0539: 'C6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01() => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01()").WithLocation(38, 12) ); } [Fact] public void ImplementAbstractStaticMethod_03() { var source1 = @" public interface I1 { abstract static void M01(); } interface I2 : I1 {} interface I3 : I1 { public virtual void M01() {} } interface I4 : I1 { static void M01() {} } interface I5 : I1 { void I1.M01() {} } interface I6 : I1 { static void I1.M01() {} } interface I7 : I1 { abstract static void M01(); } interface I8 : I1 { abstract static void I1.M01(); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,25): warning CS0108: 'I3.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // public virtual void M01() {} Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01()", "I1.M01()").WithLocation(12, 25), // (17,17): warning CS0108: 'I4.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // static void M01() {} Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01()", "I1.M01()").WithLocation(17, 17), // (22,13): error CS0539: 'I5.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01()").WithLocation(22, 13), // (27,20): error CS0106: The modifier 'static' is not valid for this item // static void I1.M01() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 20), // (27,20): error CS0539: 'I6.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01()").WithLocation(27, 20), // (32,26): warning CS0108: 'I7.M01()' hides inherited member 'I1.M01()'. Use the new keyword if hiding was intended. // abstract static void M01(); Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01()", "I1.M01()").WithLocation(32, 26), // (37,29): error CS0106: The modifier 'static' is not valid for this item // abstract static void I1.M01(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 29), // (37,29): error CS0539: 'I8.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static void I1.M01(); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01()").WithLocation(37, 29) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); abstract static void M02(); } "; var source2 = typeKeyword + @" Test: I1 { static void I1.M01() {} public static void M02() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,20): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 20) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,20): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 20), // (10,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M01(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 26), // (11,26): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static void M02(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = typeKeyword + @" Test1: I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01()' cannot implement interface member 'I1.M01()' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01()", "I1.M01()", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01()' cannot implement interface member 'I1.M01()' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01()", "I1.M01()", "Test1").WithLocation(2, 12), // (9,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } "; var source2 = typeKeyword + @" Test1: I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,20): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 20) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,20): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static void I1.M01() {} Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 20), // (9,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static void M01(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 26) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C : I1 { public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, cM01.MethodKind); Assert.Equal("void C.M01()", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static void M01(); } " + typeKeyword + @" C : I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.Equal("void C.I1.M01()", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticMethod_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static void M01(); } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C2.I1.M01()", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticMethod_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig static abstract virtual void M01 () cil managed { } // end of method I1::M01 } // end of class I1 .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static void I1.M01 () cil managed { .override method void I1::M01() .maxstack 8 IL_0000: ret } // end of method C1::I1.M01 .method public hidebysig static void M01 () cil managed { IL_0000: ret } // end of method C1::M01 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } // end of method C1::.ctor } // end of class C1 .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static void M01 () cil managed { IL_0000: ret } // end of method C2::M01 .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1.I1.M01()", c1M01.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); Assert.Equal("void C2.M01()", c5.FindImplementationForInterfaceMember(m01).ToTestDisplayString()); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticMethod_11() { // Ignore invalid metadata (non-abstract static virtual method). var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig virtual static void M01 () cil managed { IL_0000: ret } // end of method I1::M01 } // end of class I1 "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static void I1.M01() {} } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,19): error CS0539: 'C1.M01()' in explicit interface declaration is not found among members of the interface that can be implemented // static void I1.M01() {} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01()").WithLocation(4, 19) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Fact] public void ImplementAbstractStaticMethod_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void M01 () cil managed { } // end of method I1::M01 } // end of class I1 .class interface public auto ansi abstract I2 implements I1 { // Methods .method private hidebysig static void I1.M01 () cil managed { .override method void I1::M01() IL_0000: ret } // end of method I2::I1.M01 } // end of class I2 "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01()' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01()").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticMethod_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static void M01(); } class C1 { public static void M01() {} } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("void C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1.M01"); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Ordinary, c2M01.MethodKind); Assert.Equal("void C1.M01()", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C1.M01()"" IL_0005: ret } "); } [Fact] public void ImplementAbstractStaticMethod_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void modopt(I1) M01 () cil managed { } // end of method I1::M01 } // end of class I1 "; var source1 = @" class C1 : I1 { public static void M01() {} } class C2 : I1 { static void I1.M01() {} } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("void modopt(I1) C1.I1.M01()", c1M01.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1.M01"); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Ordinary, c1M01.MethodKind); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("void modopt(I1) C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C1.M01()"" IL_0005: ret } "); } [Fact] public void ImplementAbstractStaticMethod_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static void M01(); abstract static void M02(); } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static void I1.M02() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<MethodSymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>("M01"); Assert.Equal("void C1.M01()", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C2.I1.M01()", c2M01.ToTestDisplayString()); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<MethodSymbol>().Single(); var c2M02 = c3.BaseType().GetMember<MethodSymbol>("I1.M02"); Assert.Equal("void C2.I1.M02()", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Fact] public void ImplementAbstractStaticMethod_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static void M01(); } public class C1 : I1 { public static void M01() {} } public class C2 : C1 { new public static void M01() {} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.M01()", @" { // Code size 6 (0x6) .maxstack 0 IL_0000: call ""void C2.M01()"" IL_0005: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<MethodSymbol>("M01"); Assert.Equal("void C2.M01()", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("void C3.I1.M01()", c3M01.ToTestDisplayString()); Assert.Same(m01, c3M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_17(bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(System.Int32 x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(System.Int32 x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_18(bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(T x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.M01(T x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_19(bool genericFirst) { // Same as ImplementAbstractStaticMethod_17 only implementation is explicit in source. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" static void I1.M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.I1.M01(System.Int32 x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_20(bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implementation is explicit in source. var generic = @" static void I1<T>.M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("void C1<T>.I1<T>.M01(T x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_21(bool genericFirst) { // Same as ImplementAbstractStaticMethod_17 only implicit implementation is in an intermediate base. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1 { abstract static void M01(int x); } public class C1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T> : C1<T>, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C11<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "void C11<T>.I1.M01(System.Int32 x)" : "void C1<T>.M01(System.Int32 x)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticMethod_22(bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implicit implementation is in an intermediate base. var generic = @" public static void M01(T x) {} "; var nonGeneric = @" public static void M01(int x) {} "; var source1 = @" public interface I1<T> { abstract static void M01(T x); } public class C1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T> : C1<T>, I1<T> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C11<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "void C11<T>.I1<T>.M01(T x)" : "void C1<T>.M01(T x)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } private static string UnaryOperatorName(string op) => OperatorFacts.UnaryOperatorNameFromSyntaxKindIfAny(SyntaxFactory.ParseToken(op).Kind()); private static string BinaryOperatorName(string op) => op switch { ">>" => WellKnownMemberNames.RightShiftOperatorName, _ => OperatorFacts.BinaryOperatorNameFromSyntaxKindIfAny(SyntaxFactory.ParseToken(op).Kind()) }; [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = UnaryOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public C2 operator " + op + @"(C2 x) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static C3 operator " + op + @"(C3 x) => throw null; } " + typeKeyword + @" C4 : I1<C4> { C4 I1<C4>.operator " + op + @"(C4 x) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static int operator " + op + @" (C5 x) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static int I1<C6>.operator " + op + @" (C6 x) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static C7 " + opName + @"(C7 x) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static C8 I1<C8>." + opName + @"(C8 x) => throw null; } public interface I2<T> where T : I2<T> { abstract static T " + opName + @"(T x); } " + typeKeyword + @" C9 : I2<C9> { public static C9 operator " + op + @"(C9 x) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static C10 I2<C10>.operator " + op + @"(C10 x) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_BadIncDecRetType or (int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.operator +(C1)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>.operator " + op + "(C1)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.operator +(C2)'. 'C2.operator +(C2)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>.operator " + op + "(C2)", "C2.operator " + op + "(C2)").WithLocation(12, 10), // (14,24): error CS0558: User-defined operator 'C2.operator +(C2)' must be declared static and public // public C2 operator +(C2 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C2.operator " + op + "(C2)").WithLocation(14, 24), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.operator +(C3)'. 'C3.operator +(C3)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>.operator " + op + "(C3)", "C3.operator " + op + "(C3)").WithLocation(18, 10), // (20,24): error CS0558: User-defined operator 'C3.operator +(C3)' must be declared static and public // static C3 operator +(C3 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C3.operator " + op + "(C3)").WithLocation(20, 24), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.operator +(C4)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>.operator " + op + "(C4)").WithLocation(24, 10), // (26,24): error CS8930: Explicit implementation of a user-defined operator 'C4.operator +(C4)' must be declared static // C4 I1<C4>.operator +(C4 x) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("C4.operator " + op + "(C4)").WithLocation(26, 24), // (26,24): error CS0539: 'C4.operator +(C4)' in explicit interface declaration is not found among members of the interface that can be implemented // C4 I1<C4>.operator +(C4 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C4.operator " + op + "(C4)").WithLocation(26, 24), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.operator +(C5)'. 'C5.operator +(C5)' cannot implement 'I1<C5>.operator +(C5)' because it does not have the matching return type of 'C5'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>.operator " + op + "(C5)", "C5.operator " + op + "(C5)", "C5").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.operator +(C6)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>.operator " + op + "(C6)").WithLocation(36, 10), // (38,32): error CS0539: 'C6.operator +(C6)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C6>.operator + (C6 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C6.operator " + op + "(C6)").WithLocation(38, 32), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.operator +(C7)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>.operator " + op + "(C7)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.operator +(C8)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>.operator " + op + "(C8)").WithLocation(48, 10), // (50,22): error CS0539: 'C8.op_UnaryPlus(C8)' in explicit interface declaration is not found among members of the interface that can be implemented // static C8 I1<C8>.op_UnaryPlus(C8 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8)").WithLocation(50, 22), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_UnaryPlus(C9)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_UnaryPlus(C10)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10)").WithLocation(65, 11), // (67,33): error CS0539: 'C10.operator +(C10)' in explicit interface declaration is not found among members of the interface that can be implemented // static C10 I2<C10>.operator +(C10 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C10.operator " + op + "(C10)").WithLocation(67, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = BinaryOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public C2 operator " + op + @"(C2 x, int y) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static C3 operator " + op + @"(C3 x, int y) => throw null; } " + typeKeyword + @" C4 : I1<C4> { C4 I1<C4>.operator " + op + @"(C4 x, int y) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static int operator " + op + @" (C5 x, int y) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static int I1<C6>.operator " + op + @" (C6 x, int y) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static C7 " + opName + @"(C7 x, int y) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static C8 I1<C8>." + opName + @"(C8 x, int y) => throw null; } public interface I2<T> where T : I2<T> { abstract static T " + opName + @"(T x, int y); } " + typeKeyword + @" C9 : I2<C9> { public static C9 operator " + op + @"(C9 x, int y) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static C10 I2<C10>.operator " + op + @"(C10 x, int y) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.operator >>(C1, int)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>.operator " + op + "(C1, int)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.operator >>(C2, int)'. 'C2.operator >>(C2, int)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>.operator " + op + "(C2, int)", "C2.operator " + op + "(C2, int)").WithLocation(12, 10), // (14,24): error CS0558: User-defined operator 'C2.operator >>(C2, int)' must be declared static and public // public C2 operator >>(C2 x, int y) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C2.operator " + op + "(C2, int)").WithLocation(14, 24), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.operator >>(C3, int)'. 'C3.operator >>(C3, int)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>.operator " + op + "(C3, int)", "C3.operator " + op + "(C3, int)").WithLocation(18, 10), // (20,24): error CS0558: User-defined operator 'C3.operator >>(C3, int)' must be declared static and public // static C3 operator >>(C3 x, int y) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("C3.operator " + op + "(C3, int)").WithLocation(20, 24), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.operator >>(C4, int)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>.operator " + op + "(C4, int)").WithLocation(24, 10), // (26,24): error CS8930: Explicit implementation of a user-defined operator 'C4.operator >>(C4, int)' must be declared static // C4 I1<C4>.operator >>(C4 x, int y) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("C4.operator " + op + "(C4, int)").WithLocation(26, 24), // (26,24): error CS0539: 'C4.operator >>(C4, int)' in explicit interface declaration is not found among members of the interface that can be implemented // C4 I1<C4>.operator >>(C4 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C4.operator " + op + "(C4, int)").WithLocation(26, 24), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.operator >>(C5, int)'. 'C5.operator >>(C5, int)' cannot implement 'I1<C5>.operator >>(C5, int)' because it does not have the matching return type of 'C5'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>.operator " + op + "(C5, int)", "C5.operator " + op + "(C5, int)", "C5").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.operator >>(C6, int)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>.operator " + op + "(C6, int)").WithLocation(36, 10), // (38,32): error CS0539: 'C6.operator >>(C6, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C6>.operator >> (C6 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C6.operator " + op + "(C6, int)").WithLocation(38, 32), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.operator >>(C7, int)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>.operator " + op + "(C7, int)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.operator >>(C8, int)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>.operator " + op + "(C8, int)").WithLocation(48, 10), // (50,22): error CS0539: 'C8.op_RightShift(C8, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static C8 I1<C8>.op_RightShift(C8 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8, int)").WithLocation(50, 22), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_RightShift(C9, int)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9, int)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_RightShift(C10, int)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10, int)").WithLocation(65, 11), // (67,33): error CS0539: 'C10.operator >>(C10, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static C10 I2<C10>.operator >>(C10 x, int y) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C10.operator " + op + "(C10, int)").WithLocation(67, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_03([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } interface I2 : I1 {} interface I3 : I1 { I1 operator " + op + @"(I1 x) => default; } interface I4 : I1 { static I1 operator " + op + @"(I1 x) => default; } interface I5 : I1 { I1 I1.operator " + op + @"(I1 x) => default; } interface I6 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } interface I7 : I1 { abstract static I1 operator " + op + @"(I1 x); } public interface I11<T> where T : I11<T> { abstract static T operator " + op + @"(T x); } interface I8<T> : I11<T> where T : I8<T> { T operator " + op + @"(T x) => default; } interface I9<T> : I11<T> where T : I9<T> { static T operator " + op + @"(T x) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static T operator " + op + @"(T x); } interface I12<T> : I11<T> where T : I12<T> { static T I11<T>.operator " + op + @"(T x) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static T I11<T>.operator " + op + @"(T x); } interface I14 : I1 { abstract static I1 I1.operator " + op + @"(I1 x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); ErrorCode badSignatureError = op.Length != 2 ? ErrorCode.ERR_BadUnaryOperatorSignature : ErrorCode.ERR_BadIncDecSignature; ErrorCode badAbstractSignatureError = op.Length != 2 ? ErrorCode.ERR_BadAbstractUnaryOperatorSignature : ErrorCode.ERR_BadAbstractIncDecSignature; compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (12,17): error CS0558: User-defined operator 'I3.operator +(I1)' must be declared static and public // I1 operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I3.operator " + op + "(I1)").WithLocation(12, 17), // (12,17): error CS0562: The parameter of a unary operator must be the containing type // I1 operator +(I1 x) => default; Diagnostic(badSignatureError, op).WithLocation(12, 17), // (17,24): error CS0562: The parameter of a unary operator must be the containing type // static I1 operator +(I1 x) => default; Diagnostic(badSignatureError, op).WithLocation(17, 24), // (22,20): error CS8930: Explicit implementation of a user-defined operator 'I5.operator +(I1)' must be declared static // I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("I5.operator " + op + "(I1)").WithLocation(22, 20), // (22,20): error CS0539: 'I5.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I5.operator " + op + "(I1)").WithLocation(22, 20), // (27,27): error CS0539: 'I6.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I6.operator " + op + "(I1)").WithLocation(27, 27), // (32,33): error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it. // abstract static I1 operator +(I1 x); Diagnostic(badAbstractSignatureError, op).WithLocation(32, 33), // (42,16): error CS0558: User-defined operator 'I8<T>.operator +(T)' must be declared static and public // T operator +(T x) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I8<T>.operator " + op + "(T)").WithLocation(42, 16), // (42,16): error CS0562: The parameter of a unary operator must be the containing type // T operator +(T x) => default; Diagnostic(badSignatureError, op).WithLocation(42, 16), // (47,23): error CS0562: The parameter of a unary operator must be the containing type // static T operator +(T x) => default; Diagnostic(badSignatureError, op).WithLocation(47, 23), // (57,30): error CS0539: 'I12<T>.operator +(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static T I11<T>.operator +(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I12<T>.operator " + op + "(T)").WithLocation(57, 30), // (62,39): error CS0106: The modifier 'abstract' is not valid for this item // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(62, 39), // (62,39): error CS0501: 'I13<T>.operator +(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I13<T>.operator " + op + "(T)").WithLocation(62, 39), // (62,39): error CS0539: 'I13<T>.operator +(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static T I11<T>.operator +(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I13<T>.operator " + op + "(T)").WithLocation(62, 39), // (67,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(67, 36), // (67,36): error CS0501: 'I14.operator +(I1)' must declare a body because it is not marked abstract, extern, or partial // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I14.operator " + op + "(I1)").WithLocation(67, 36), // (67,36): error CS0539: 'I14.operator +(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static I1 I1.operator +(I1 x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I14.operator " + op + "(I1)").WithLocation(67, 36) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_03([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } interface I2 : I1 {} interface I3 : I1 { I1 operator " + op + @"(I1 x, int y) => default; } interface I4 : I1 { static I1 operator " + op + @"(I1 x, int y) => default; } interface I5 : I1 { I1 I1.operator " + op + @"(I1 x, int y) => default; } interface I6 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } interface I7 : I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public interface I11<T> where T : I11<T> { abstract static T operator " + op + @"(T x, int y); } interface I8<T> : I11<T> where T : I8<T> { T operator " + op + @"(T x, int y) => default; } interface I9<T> : I11<T> where T : I9<T> { static T operator " + op + @"(T x, int y) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static T operator " + op + @"(T x, int y); } interface I12<T> : I11<T> where T : I12<T> { static T I11<T>.operator " + op + @"(T x, int y) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static T I11<T>.operator " + op + @"(T x, int y); } interface I14 : I1 { abstract static I1 I1.operator " + op + @"(I1 x, int y); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); bool isShift = op == "<<" || op == ">>"; ErrorCode badSignatureError = isShift ? ErrorCode.ERR_BadShiftOperatorSignature : ErrorCode.ERR_BadBinaryOperatorSignature; ErrorCode badAbstractSignatureError = isShift ? ErrorCode.ERR_BadAbstractShiftOperatorSignature : ErrorCode.ERR_BadAbstractBinaryOperatorSignature; var expected = new[] { // (12,17): error CS0563: One of the parameters of a binary operator must be the containing type // I1 operator |(I1 x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(12, 17), // (17,24): error CS0563: One of the parameters of a binary operator must be the containing type // static I1 operator |(I1 x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(17, 24), // (22,20): error CS8930: Explicit implementation of a user-defined operator 'I5.operator |(I1, int)' must be declared static // I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, op).WithArguments("I5.operator " + op + "(I1, int)").WithLocation(22, 20), // (22,20): error CS0539: 'I5.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I5.operator " + op + "(I1, int)").WithLocation(22, 20), // (27,27): error CS0539: 'I6.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I6.operator " + op + "(I1, int)").WithLocation(27, 27), // (32,33): error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it. // abstract static I1 operator |(I1 x, int y); Diagnostic(badAbstractSignatureError, op).WithLocation(32, 33), // (42,16): error CS0563: One of the parameters of a binary operator must be the containing type // T operator |(T x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(42, 16), // (47,23): error CS0563: One of the parameters of a binary operator must be the containing type // static T operator |(T x, int y) => default; Diagnostic(badSignatureError, op).WithLocation(47, 23), // (57,30): error CS0539: 'I12<T>.operator |(T, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static T I11<T>.operator |(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I12<T>.operator " + op + "(T, int)").WithLocation(57, 30), // (62,39): error CS0106: The modifier 'abstract' is not valid for this item // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(62, 39), // (62,39): error CS0501: 'I13<T>.operator |(T, int)' must declare a body because it is not marked abstract, extern, or partial // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I13<T>.operator " + op + "(T, int)").WithLocation(62, 39), // (62,39): error CS0539: 'I13<T>.operator |(T, int)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static T I11<T>.operator |(T x, int y); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I13<T>.operator " + op + "(T, int)").WithLocation(62, 39), // (67,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(67, 36), // (67,36): error CS0501: 'I14.operator |(I1, int)' must declare a body because it is not marked abstract, extern, or partial // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, op).WithArguments("I14.operator " + op + "(I1, int)").WithLocation(67, 36), // (67,36): error CS0539: 'I14.operator |(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static I1 I1.operator |(I1 x, int y); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("I14.operator " + op + "(I1, int)").WithLocation(67, 36) }; if (op is "==" or "!=") { expected = expected.Concat( new[] { // (12,17): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // I1 operator ==(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(12, 17), // (17,24): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static I1 operator ==(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(17, 24), // (42,16): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // T operator ==(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(42, 16), // (47,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static T operator ==(T x, int y) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, op).WithLocation(47, 23), } ).ToArray(); } else { expected = expected.Concat( new[] { // (12,17): error CS0558: User-defined operator 'I3.operator |(I1, int)' must be declared static and public // I1 operator |(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I3.operator " + op + "(I1, int)").WithLocation(12, 17), // (42,16): error CS0558: User-defined operator 'I8<T>.operator |(T, int)' must be declared static and public // T operator |(T x, int y) => default; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, op).WithArguments("I8<T>.operator " + op + "(T, int)").WithLocation(42, 16) } ).ToArray(); } compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify(expected); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_04([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public interface I2<T> where T : I2<T> { abstract static T operator " + op + @"(T x); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static Test2 operator " + op + @"(Test2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15), // (14,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator +(I1 x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(14, 33), // (19,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator +(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(19, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_04([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public interface I2<T> where T : I2<T> { abstract static T operator " + op + @"(T x, int y); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static Test2 operator " + op + @"(Test2 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (4,15): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I1.").WithArguments("static abstract members in interfaces").WithLocation(4, 15), // (14,33): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static I1 operator +(I1 x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(14, 33), // (19,32): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static T operator +(T x, int y); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, op).WithArguments("abstract", "9.0", "preview").WithLocation(19, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_05([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static Test1 operator " + op + @"(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (2,12): error CS8929: 'Test1.operator +(Test1)' cannot implement interface member 'I1<Test1>.operator +(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1)", "I1<Test1>.operator " + op + "(Test1)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (2,12): error CS8929: 'Test1.operator +(Test1)' cannot implement interface member 'I1<Test1>.operator +(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1)", "I1<Test1>.operator " + op + "(Test1)", "Test1").WithLocation(2, 12), // (9,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator +(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_05([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static Test1 operator " + op + @"(Test1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (2,12): error CS8929: 'Test1.operator >>(Test1, int)' cannot implement interface member 'I1<Test1>.operator >>(Test1, int)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1, int)", "I1<Test1>.operator " + op + "(Test1, int)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.WRN_EqualityOpWithoutEquals or (int)ErrorCode.WRN_EqualityOpWithoutGetHashCode)).Verify( // (2,12): error CS8929: 'Test1.operator >>(Test1, int)' cannot implement interface member 'I1<Test1>.operator >>(Test1, int)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1.operator " + op + "(Test1, int)", "I1<Test1>.operator " + op + "(Test1, int)", "Test1").WithLocation(2, 12), // (9,32): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static T operator >>(T x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 32) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_06([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OperatorNeedsMatch or (int)ErrorCode.ERR_OpTFRetType)).Verify( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator +(I1 x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_06([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } "; var source2 = typeKeyword + @" Test1: I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (4,27): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static I1 I1.operator +(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(4, 27), // (9,33): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static I1 operator +(I1 x, int y); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, op).WithLocation(9, 33) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_07([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x); } " + typeKeyword + @" C : I1<C> { public static C operator " + op + @"(C x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("C C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_07([CombinatorialValues("true", "false")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static bool operator " + op + @"(T x); } partial " + typeKeyword + @" C : I1<C> { public static bool operator " + op + @"(C x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1<T> where T : I1<T> { abstract static bool operator " + matchingOp + @"(T x); } partial " + typeKeyword + @" C { public static bool operator " + matchingOp + @"(C x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("System.Boolean C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_07([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, int y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() partial " + typeKeyword + @" C : I1<C> { public static C operator " + op + @"(C x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + matchingOp + @"(T x, int y); } partial " + typeKeyword + @" C { public static C operator " + matchingOp + @"(C x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.Equal(matchingOp is null ? 1 : 2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("C C." + opName + "(C x, System.Int32 y)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_08([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } " + typeKeyword + @" C : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal("default", node.ToString()); Assert.Equal("I1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("I1 C.I1." + opName + "(I1 x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("I1 C.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_08([CombinatorialValues("true", "false")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1 { abstract static bool operator " + op + @"(I1 x); } partial " + typeKeyword + @" C : I1 { static bool I1.operator " + op + @"(I1 x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1 { abstract static bool operator " + matchingOp + @"(I1 x); } partial " + typeKeyword + @" C { static bool I1.operator " + matchingOp + @"(I1 x) => default; } "; var opName = UnaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", node.ToString()); Assert.Equal("System.Boolean", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("System.Boolean C.I1." + opName + "(I1 x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers(opName).OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("System.Boolean C.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_08([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public partial interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } partial " + typeKeyword + @" C : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator " + matchingOp + @"(I1 x, int y); } partial " + typeKeyword + @" C { static I1 I1.operator " + matchingOp + @"(I1 x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", node.ToString()); Assert.Equal("I1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<OperatorDeclarationSyntax>()); Assert.Equal("I1 C.I1." + opName + "(I1 x, System.Int32 y)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers(opName).OfType<MethodSymbol>().Single(); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(matchingOp is null ? 1 : 2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("I1 C.I1." + opName + "(I1 x, System.Int32 y)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_09([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public class C2 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_09([CombinatorialValues("true", "false")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public partial interface I1 { abstract static bool operator " + op + @"(I1 x); } public partial class C2 : I1 { static bool I1.operator " + op + @"(I1 x) => default; } "; string matchingOp = op == "true" ? "false" : "true"; source1 += @" public partial interface I1 { abstract static bool operator " + matchingOp + @"(I1 x); } public partial class C2 { static bool I1.operator " + matchingOp + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Boolean C2.I1." + opName + "(I1 x)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_09([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public partial interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } public partial class C2 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1 { abstract static I1 operator " + matchingOp + @"(I1 x, int y); } public partial class C2 { static I1 I1.operator " + matchingOp + @"(I1 x, int y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2.I1." + opName + "(I1 x, System.Int32 y)", cM01.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_10([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x) cil managed { .override method class I1 I1::" + opName + @"(class I1) IL_0000: ldnull IL_0001: ret } .method public hidebysig static specialname class I1 " + opName + @" (class I1 x) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static specialname class I1 " + opName + @" (class I1 x) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Equal(MethodKind.UserDefinedOperator, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C1.I1." + opName + "(I1 x)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2." + opName + "(I1 x)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_10([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x, int32 y) cil managed { .override method class I1 I1::" + opName + @"(class I1, int32) IL_0000: ldnull IL_0001: ret } .method public hidebysig static specialname class I1 " + opName + @" (class I1 x, int32 y) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig static specialname class I1 " + opName + @" (class I1 x, int32 y) cil managed { IL_0000: ldnull IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } // end of method C2::.ctor } // end of class C2 "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Equal(MethodKind.UserDefinedOperator, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C1.I1." + opName + "(I1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("I1 C2." + opName + "(I1 x, System.Int32 y)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_11([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname virtual static class I1 " + opName + @" ( class I1 x ) cil managed { IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,27): error CS0539: 'C1.operator ~(I1)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator ~(I1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C1.operator " + op + "(I1)").WithLocation(4, 27) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("I1 I1." + opName + "(I1 x)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_11([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,27): error CS0539: 'C1.operator <(I1, int)' in explicit interface declaration is not found among members of the interface that can be implemented // static I1 I1.operator <(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, op).WithArguments("C1.operator " + op + "(I1, int)").WithLocation(4, 27) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("I1 I1." + opName + "(I1 x, System.Int32 y)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_12([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x ) cil managed { } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x) cil managed { .override method class I1 I1::" + opName + @"(class I1) IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.operator ~(I1)' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.operator " + op + "(I1)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_12([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static class I1 " + opName + @" ( class I1 x, int32 y ) cil managed { } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig static class I1 I1." + opName + @" (class I1 x, int32 y) cil managed { .override method class I1 I1::" + opName + @"(class I1, int32) IL_0000: ldnull IL_0001: ret } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.operator /(I1, int)' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.operator " + op + "(I1, int)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.UserDefinedOperator, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_13([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public class C2 : C1, I1<C2> { } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); } public partial class C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var i1 = c2.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.False(c2M01.HasSpecialName); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.False(c1M01.HasRuntimeSpecialName); Assert.True(c1M01.HasSpecialName); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.True(c2M01.HasSpecialName); Assert.Equal("C2 C1." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1<C2>." + opName + "(C2, C1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C2 C1." + opName + @"(C2, C1)"" IL_0007: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_14([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static !T modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static C1 operator " + op + @"(C1 x) => default; } class C2 : I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("C1 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("C1 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("C1 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("C2 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""C1 C1." + opName + @"(C1)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryTrueFalseOperator_14([CombinatorialValues("true", "false")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = UnaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static bool modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static bool operator " + op + @"(C1 x) => default; public static bool operator " + (op == "true" ? "false" : "true") + @"(C1 x) => default; } class C2 : I1<C2> { static bool I1<C2>.operator " + op + @"(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("System.Boolean modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("System.Boolean C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("System.Boolean C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("System.Boolean modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""bool C1." + opName + @"(C1)"" IL_0006: ret } "); } private static string MatchingBinaryOperator(string op) { return op switch { "<" => ">", ">" => "<", "<=" => ">=", ">=" => "<=", "==" => "!=", "!=" => "==", _ => null }; } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_14([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = BinaryOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static !T modopt(I1`1) " + opName + @" ( !T x, int32 y ) cil managed { } } "; string matchingOp = MatchingBinaryOperator(op); string additionalMethods = ""; if (matchingOp is object) { additionalMethods = @" public static C1 operator " + matchingOp + @"(C1 x, int y) => default; "; } var source1 = @" #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() class C1 : I1<C1> { public static C1 operator " + op + @"(C1 x, int y) => default; " + additionalMethods + @" } class C2 : I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x, int y) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("C1 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("C1 C1." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.UserDefinedOperator, c1M01.MethodKind); Assert.Equal("C1 C1." + opName + "(C1 x, System.Int32 y)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("C2 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x, System.Int32 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1, int)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C1 C1." + opName + @"(C1, int)"" IL_0007: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticUnaryOperator_15([CombinatorialValues("+", "-", "!", "~", "++", "--")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } public partial class C2 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; var opName = UnaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M02 = c3.BaseType().GetMembers("I1." + opName).OfType<MethodSymbol>().Single(); Assert.Equal("I1 C2.I1." + opName + "(I1 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Fact] public void ImplementAbstractStaticUnaryTrueFalseOperator_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static bool operator true(I1 x); abstract static bool operator false(I1 x); } public partial class C2 : I1 { static bool I1.operator true(I1 x) => default; static bool I1.operator false(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("op_True").OfType<MethodSymbol>().Single(); var m02 = c3.Interfaces().Single().GetMembers("op_False").OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMembers("I1.op_True").OfType<MethodSymbol>().Single(); Assert.Equal("System.Boolean C2.I1.op_True(I1 x)", c2M01.ToTestDisplayString()); Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); var c2M02 = c3.BaseType().GetMembers("I1.op_False").OfType<MethodSymbol>().Single(); Assert.Equal("System.Boolean C2.I1.op_False(I1 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_15([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); abstract static T operator " + op + @"(T x, C2 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public partial class C2 : C1, I1<C2> { static C2 I1<C2>.operator " + op + @"(C2 x, C2 y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); abstract static T operator " + matchingOp + @"(T x, C2 y); } public partial class C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } public partial class C2 { static C2 I1<C2>.operator " + matchingOp + @"(C2 x, C2 y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().First(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C2 C1." + opName + "(C2 x, C1 y)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().ElementAt(1); var c2M02 = c3.BaseType().GetMembers("I1<C2>." + opName).OfType<MethodSymbol>().First(); Assert.Equal("C2 C2.I1<C2>." + opName + "(C2 x, C2 y)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_16([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op) { // A new implicit implementation is properly considered. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static T operator " + op + @"(T x, C1 y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1 : I1<C2> { public static C2 operator " + op + @"(C2 x, C1 y) => default; } public partial class C2 : C1 { public static C2 operator " + op + @"(C2 x, C1 y) => default; } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T> { abstract static T operator " + matchingOp + @"(T x, C1 y); } public partial class C1 : I1<C2> { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } public partial class C2 : C1 { public static C2 operator " + matchingOp + @"(C2 x, C1 y) => default; } "; } var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = BinaryOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1<C2>." + opName + "(C2, C1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C2 C2." + opName + @"(C2, C1)"" IL_0007: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C2 C2." + opName + "(C2 x, C1 y)", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C2 C3.I1<C2>." + opName + "(C2 x, C1 y)", c3M01.ToTestDisplayString()); Assert.Equal(m01, c3M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_18([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, U y) => default; "; var nonGeneric = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, int y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> { public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, U y) => default; public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, int y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>." + opName + "(C1<T, U> x, U y)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>." + opName + "(C1<T, U> x, U y)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_20([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // Same as ImplementAbstractStaticBinaryOperator_18 only implementation is explicit in source. var generic = @" static C1<T, U> I1<C1<T, U>, U>.operator " + op + @"(C1<T, U> x, U y) => default; "; var nonGeneric = @" public static C1<T, U> operator " + op + @"(C1<T, U> x, int y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> : I1<C1<T, U>, U> { public static C1<T, U> operator " + matchingOp + @"(C1<T, U> x, int y) => default; static C1<T, U> I1<C1<T, U>, U>.operator " + matchingOp + @"(C1<T, U> x, U y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<T, U> C1<T, U>.I1<C1<T, U>, U>." + opName + "(C1<T, U> x, U y)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticBinaryOperator_22([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<", ">", "<=", ">=", "==", "!=")] string op, bool genericFirst) { // Same as ImplementAbstractStaticMethod_18 only implicit implementation is in an intermediate base. var generic = @" public static C11<T, U> operator " + op + @"(C11<T, U> x, C1<T, U> y) => default; "; var nonGeneric = @" public static C11<T, U> operator " + op + @"(C11<T, int> x, C1<T, U> y) => default; "; var source1 = @" public partial interface I1<T, U> where T : I1<T, U> { abstract static T operator " + op + @"(T x, U y); } #pragma warning disable CS0660, CS0661 // 'C1' defines operator == or operator != but does not override Object.Equals(object o)/Object.GetHashCode() public partial class C1<T, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } public class C11<T, U> : C1<T, U>, I1<C11<T, U>, C1<T, U>> { } "; string matchingOp = MatchingBinaryOperator(op); if (matchingOp is object) { source1 += @" public partial interface I1<T, U> { abstract static T operator " + matchingOp + @"(T x, U y); } public partial class C1<T, U> { public static C11<T, U> operator " + matchingOp + @"(C11<T, U> x, C1<T, U> y) => default; public static C11<T, U> operator " + matchingOp + @"(C11<T, int> x, C1<T, U> y) => default; } "; } var opName = BinaryOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C11<int, int>, I1<C11<int, int>, C1<int, int>> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); var expectedDisplay = m01.ContainingModule is PEModuleSymbol ? "C11<T, U> C11<T, U>.I1<C11<T, U>, C1<T, U>>." + opName + "(C11<T, U> x, C1<T, U> y)" : "C11<T, U> C1<T, U>." + opName + "(C11<T, U> x, C1<T, U> y)"; Assert.Equal(expectedDisplay, c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal(expectedDisplay, baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x); } class C1 : I1 { static I1 I1.operator " + op + @"(I1 x) => default; } class C2 : I1 { private static I1 I1.operator " + op + @"(I1 x) => default; } class C3 : I1 { protected static I1 I1.operator " + op + @"(I1 x) => default; } class C4 : I1 { internal static I1 I1.operator " + op + @"(I1 x) => default; } class C5 : I1 { protected internal static I1 I1.operator " + op + @"(I1 x) => default; } class C6 : I1 { private protected static I1 I1.operator " + op + @"(I1 x) => default; } class C7 : I1 { public static I1 I1.operator " + op + @"(I1 x) => default; } class C8 : I1 { static partial I1 I1.operator " + op + @"(I1 x) => default; } class C9 : I1 { async static I1 I1.operator " + op + @"(I1 x) => default; } class C10 : I1 { unsafe static I1 I1.operator " + op + @"(I1 x) => default; } class C11 : I1 { static readonly I1 I1.operator " + op + @"(I1 x) => default; } class C12 : I1 { extern static I1 I1.operator " + op + @"(I1 x); } class C13 : I1 { abstract static I1 I1.operator " + op + @"(I1 x) => default; } class C14 : I1 { virtual static I1 I1.operator " + op + @"(I1 x) => default; } class C15 : I1 { sealed static I1 I1.operator " + op + @"(I1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.WRN_ExternMethodNoImplementation or (int)ErrorCode.ERR_OpTFRetType or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (16,35): error CS0106: The modifier 'private' is not valid for this item // private static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private").WithLocation(16, 35), // (22,37): error CS0106: The modifier 'protected' is not valid for this item // protected static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected").WithLocation(22, 37), // (28,36): error CS0106: The modifier 'internal' is not valid for this item // internal static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("internal").WithLocation(28, 36), // (34,46): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected internal").WithLocation(34, 46), // (40,45): error CS0106: The modifier 'private protected' is not valid for this item // private protected static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private protected").WithLocation(40, 45), // (46,34): error CS0106: The modifier 'public' is not valid for this item // public static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("public").WithLocation(46, 34), // (52,12): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // static partial I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(52, 12), // (58,33): error CS0106: The modifier 'async' is not valid for this item // async static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("async").WithLocation(58, 33), // (70,36): error CS0106: The modifier 'readonly' is not valid for this item // static readonly I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("readonly").WithLocation(70, 36), // (82,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(82, 36), // (88,35): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("virtual").WithLocation(88, 35), // (94,34): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1 I1.operator !(I1 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("sealed").WithLocation(94, 34) ); } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1 { abstract static I1 operator " + op + @"(I1 x, int y); } struct C1 : I1 { static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C2 : I1 { private static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C3 : I1 { protected static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C4 : I1 { internal static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C5 : I1 { protected internal static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C6 : I1 { private protected static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C7 : I1 { public static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C8 : I1 { static partial I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C9 : I1 { async static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C10 : I1 { unsafe static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C11 : I1 { static readonly I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C12 : I1 { extern static I1 I1.operator " + op + @"(I1 x, int y); } struct C13 : I1 { abstract static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C14 : I1 { virtual static I1 I1.operator " + op + @"(I1 x, int y) => default; } struct C15 : I1 { sealed static I1 I1.operator " + op + @"(I1 x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.WRN_ExternMethodNoImplementation or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (16,35): error CS0106: The modifier 'private' is not valid for this item // private static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private").WithLocation(16, 35), // (22,37): error CS0106: The modifier 'protected' is not valid for this item // protected static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected").WithLocation(22, 37), // (28,36): error CS0106: The modifier 'internal' is not valid for this item // internal static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("internal").WithLocation(28, 36), // (34,46): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("protected internal").WithLocation(34, 46), // (40,45): error CS0106: The modifier 'private protected' is not valid for this item // private protected static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("private protected").WithLocation(40, 45), // (46,34): error CS0106: The modifier 'public' is not valid for this item // public static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("public").WithLocation(46, 34), // (52,12): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // static partial I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(52, 12), // (58,33): error CS0106: The modifier 'async' is not valid for this item // async static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("async").WithLocation(58, 33), // (70,36): error CS0106: The modifier 'readonly' is not valid for this item // static readonly I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("readonly").WithLocation(70, 36), // (82,36): error CS0106: The modifier 'abstract' is not valid for this item // abstract static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("abstract").WithLocation(82, 36), // (88,35): error CS0106: The modifier 'virtual' is not valid for this item // virtual static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("virtual").WithLocation(88, 35), // (94,34): error CS0106: The modifier 'sealed' is not valid for this item // sealed static I1 I1.operator ^(I1 x, int y) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, op).WithArguments("sealed").WithLocation(94, 34) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsUnaryOperator_01([CombinatorialValues("+", "-", "!", "~", "++", "--", "true", "false")] string op) { var source1 = @" public interface I1<T> where T : struct { abstract static I1<T> operator " + op + @"(I1<T> x); } class C1 { static I1<int> I1<int>.operator " + op + @"(I1<int> x) => default; } class C2 : I1<C2> { static I1<C2> I1<C2>.operator " + op + @"(I1<C2> x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not ((int)ErrorCode.ERR_OpTFRetType or (int)ErrorCode.ERR_OperatorNeedsMatch)).Verify( // (9,20): error CS0540: 'C1.I1<int>.operator -(I1<int>)': containing type does not implement interface 'I1<int>' // static I1<int> I1<int>.operator -(I1<int> x) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<int>").WithArguments("C1.I1<int>.operator " + op + "(I1<int>)", "I1<int>").WithLocation(9, 20), // (12,7): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // class C2 : I1<C2> Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 7), // (14,19): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 19), // (14,35): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, op).WithArguments("I1<T>", "T", "C2").WithLocation(14, 35), // (14,44): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator -(I1<C2> x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("I1<T>", "T", "C2").WithLocation(14, 44 + op.Length - 1) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsBinaryOperator_01([CombinatorialValues("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", ">", "<=", ">=", "==", "!=")] string op) { var source1 = @" public interface I1<T> where T : class { abstract static I1<T> operator " + op + @"(I1<T> x, int y); } struct C1 { static I1<string> I1<string>.operator " + op + @"(I1<string> x, int y) => default; } struct C2 : I1<C2> { static I1<C2> I1<C2>.operator " + op + @"(I1<C2> x, int y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (9,23): error CS0540: 'C1.I1<string>.operator %(I1<string>, int)': containing type does not implement interface 'I1<string>' // static I1<string> I1<string>.operator %(I1<string> x, int y) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<string>").WithArguments("C1.I1<string>.operator " + op + "(I1<string>, int)", "I1<string>").WithLocation(9, 23), // (12,8): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // struct C2 : I1<C2> Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 8), // (14,19): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 19), // (14,35): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, op).WithArguments("I1<T>", "T", "C2").WithLocation(14, 35), // (14,44): error CS0452: The type 'C2' must be a reference type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static I1<C2> I1<C2>.operator %(I1<C2> x, int y) => default; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "x").WithArguments("I1<T>", "T", "C2").WithLocation(14, 44 + op.Length - 1) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public int M01 { get; set; } } " + typeKeyword + @" C3 : I1 { static int M01 { get; set; } } " + typeKeyword + @" C4 : I1 { int I1.M01 { get; set; } } " + typeKeyword + @" C5 : I1 { public static long M01 { get; set; } } " + typeKeyword + @" C6 : I1 { static long I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,12): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 12), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'int'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,20): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static long I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 20) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract int M01 { get; set; } } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static int M01 { get; set; } } " + typeKeyword + @" C3 : I1 { int M01 { get; set; } } " + typeKeyword + @" C4 : I1 { static int I1.M01 { get; set; } } " + typeKeyword + @" C5 : I1 { public long M01 { get; set; } } " + typeKeyword + @" C6 : I1 { long I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,19): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 19), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'int'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,13): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // long I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 13) ); } [Fact] public void ImplementAbstractStaticProperty_03() { var source1 = @" public interface I1 { abstract static int M01 { get; set; } } interface I2 : I1 {} interface I3 : I1 { public virtual int M01 { get => 0; set{} } } interface I4 : I1 { static int M01 { get; set; } } interface I5 : I1 { int I1.M01 { get => 0; set{} } } interface I6 : I1 { static int I1.M01 { get => 0; set{} } } interface I7 : I1 { abstract static int M01 { get; set; } } interface I8 : I1 { abstract static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,24): warning CS0108: 'I3.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // public virtual int M01 { get => 0; set{} } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01", "I1.M01").WithLocation(12, 24), // (17,16): warning CS0108: 'I4.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // static int M01 { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01", "I1.M01").WithLocation(17, 16), // (22,12): error CS0539: 'I5.M01' in explicit interface declaration is not found among members of the interface that can be implemented // int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01").WithLocation(22, 12), // (27,19): error CS0106: The modifier 'static' is not valid for this item // static int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 19), // (27,19): error CS0539: 'I6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get => 0; set{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01").WithLocation(27, 19), // (32,25): warning CS0108: 'I7.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01", "I1.M01").WithLocation(32, 25), // (37,28): error CS0106: The modifier 'static' is not valid for this item // abstract static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 28), // (37,28): error CS0539: 'I8.M01' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01").WithLocation(37, 28) ); foreach (var m01 in compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers()) { Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } abstract static int M02 { get; set; } } "; var source2 = typeKeyword + @" Test: I1 { static int I1.M01 { get; set; } public static int M02 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,19): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 19) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,19): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 19), // (10,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 25), // (11,25): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static int M02 { get; set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 25) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } "; var source2 = typeKeyword + @" Test1: I1 { public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.set' cannot implement interface member 'I1.M01.set' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.set", "I1.M01.set", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.get' cannot implement interface member 'I1.M01.get' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.get", "I1.M01.get", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.set' cannot implement interface member 'I1.M01.set' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.set", "I1.M01.set", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.get' cannot implement interface member 'I1.M01.get' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.get", "I1.M01.get", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12), // (9,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(9, 31), // (9,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(9, 36) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } "; var source2 = typeKeyword + @" Test1: I1 { static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,19): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 19) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,19): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 19), // (9,31): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "get").WithLocation(9, 31), // (9,36): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static int M01 { get; set; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "set").WithLocation(9, 36) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C : I1 { public static int M01 { get => 0; set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.False(cM01Get.HasRuntimeSpecialName); Assert.True(cM01Get.HasSpecialName); Assert.Equal("System.Int32 C.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.False(cM01Set.HasRuntimeSpecialName); Assert.True(cM01Set.HasSpecialName); Assert.Equal("void C.M01.set", cM01Set.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticReadonlyProperty_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; } } " + typeKeyword + @" C : I1 { public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Null(m01.SetMethod); var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C.M01.set", cM01Set.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } " + typeKeyword + @" C : I1 { static int I1.M01 { get => 0; set {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C.I1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.False(cM01Get.HasRuntimeSpecialName); Assert.True(cM01Get.HasSpecialName); Assert.Equal("System.Int32 C.I1.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.False(cM01Set.HasRuntimeSpecialName); Assert.True(cM01Set.HasSpecialName); Assert.Equal("void C.I1.M01.set", cM01Set.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1 { public static void M01() {} } public class C2 : C1, I1 { static int I1.M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<PropertySymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var cM01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.I1.M01 { get; set; }", cM01.ToTestDisplayString()); Assert.Same(cM01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(cM01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, cM01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, cM01.SetMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig specialname static int32 I1.get_M01 () cil managed { .override method int32 I1::get_M01() IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static void I1.set_M01 ( int32 'value' ) cil managed { .override method void I1::set_M01(int32) IL_0000: ret } .property instance int32 I1.M01() { .get int32 C1::I1.get_M01() .set void C1::I1.set_M01(int32) } .method public hidebysig specialname static int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname static void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 C1::get_M01() .set void C1::set_M01(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig specialname static int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname static void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 C2::get_M01() .set void C2::set_M01(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = (PropertySymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1.I1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.Same(c1M01.GetMethod, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c2.FindImplementationForInterfaceMember(m01.SetMethod)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c4.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c4.FindImplementationForInterfaceMember(m01.SetMethod)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (PropertySymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.Same(c2M01.GetMethod, c5.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c2M01.SetMethod, c5.FindImplementationForInterfaceMember(m01.SetMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticProperty_11() { // Ignore invalid metadata (non-abstract static virtual method). scenario1(); scenario2(); scenario3(); void scenario1() { var ilSource = @" .class interface public auto ansi abstract I1 { .method private hidebysig specialname static virtual int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static virtual void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,18): error CS0539: 'C1.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01").WithLocation(4, 18) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c.FindImplementationForInterfaceMember(m01)); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); } } void scenario2() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method private hidebysig specialname static virtual void set_M01 ( int32 'value' ) cil managed { IL_0000: ret } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source2 = @" public class C1 : I1 { static int I1.M01 { get; } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, sourceSymbolValidator: validate2, symbolValidator: validate2, verify: Verification.Skipped).VerifyDiagnostics(); void validate2(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.I1.M01 { get; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.I1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(cM01.SetMethod); Assert.Null(c.FindImplementationForInterfaceMember(m01Set)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,29): error CS0550: 'C1.I1.M01.set' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("C1.I1.M01.set", "I1.M01").WithLocation(4, 29) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static int M01 { get; } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation5, sourceSymbolValidator: validate5, symbolValidator: validate5, verify: Verification.Skipped).VerifyDiagnostics(); void validate5(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; }", cM01.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.Same(cM01Get, c.FindImplementationForInterfaceMember(m01Get)); Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.SetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Get, cM01Get.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } } var source6 = @" public class C1 : I1 { public static int M01 { set{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.get' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.get").WithLocation(2, 19) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); var source7 = @" public class C1 : I1 { static int I1.M01 { set{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.get' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.get").WithLocation(2, 19), // (4,18): error CS0551: Explicit interface implementation 'C1.I1.M01' is missing accessor 'I1.M01.get' // static int I1.M01 { set{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M01").WithArguments("C1.I1.M01", "I1.M01.get").WithLocation(4, 18), // (4,24): error CS0550: 'C1.I1.M01.set' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { set{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("C1.I1.M01.set", "I1.M01").WithLocation(4, 24) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); } void scenario3() { var ilSource = @" .class interface public auto ansi abstract I1 { .method private hidebysig specialname static virtual int32 get_M01 () cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.SetMethod)); var source2 = @" public class C1 : I1 { static int I1.M01 { set{} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation2, sourceSymbolValidator: validate2, symbolValidator: validate2, verify: Verification.Skipped).VerifyDiagnostics(); void validate2(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Get = m01.GetMethod; var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.I1.M01 { set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.I1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(cM01.GetMethod); Assert.Null(c.FindImplementationForInterfaceMember(m01Get)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } var source3 = @" public class C1 : I1 { public static int M01 { get; set; } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); var cM01Get = cM01.GetMethod; Assert.True(cM01Get.IsStatic); Assert.False(cM01Get.IsAbstract); Assert.False(cM01Get.IsVirtual); Assert.False(cM01Get.IsMetadataVirtual()); Assert.False(cM01Get.IsMetadataFinal); Assert.False(cM01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, cM01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", cM01Get.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } Assert.Empty(cM01Get.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static int I1.M01 { get; set; } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,24): error CS0550: 'C1.I1.M01.get' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C1.I1.M01.get", "I1.M01").WithLocation(4, 24) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.SetMethod, c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, c1M01.SetMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static int M01 { set{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation5, sourceSymbolValidator: validate5, symbolValidator: validate5, verify: Verification.Skipped).VerifyDiagnostics(); void validate5(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var m01Set = m01.SetMethod; Assert.Equal(1, c.GetMembers().OfType<PropertySymbol>().Count()); Assert.Equal(1, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (PropertySymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { set; }", cM01.ToTestDisplayString()); var cM01Set = cM01.SetMethod; Assert.Same(cM01Set, c.FindImplementationForInterfaceMember(m01Set)); Assert.True(cM01Set.IsStatic); Assert.False(cM01Set.IsAbstract); Assert.False(cM01Set.IsVirtual); Assert.False(cM01Set.IsMetadataVirtual()); Assert.False(cM01Set.IsMetadataFinal); Assert.False(cM01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, cM01Set.MethodKind); Assert.Equal("void C1.M01.set", cM01Set.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.GetMethod)); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Set, cM01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Set.ExplicitInterfaceImplementations); } } var source6 = @" public class C1 : I1 { public static int M01 { get; } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.set' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.set").WithLocation(2, 19) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); var source7 = @" public class C1 : I1 { static int I1.M01 { get; } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.set' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.set").WithLocation(2, 19), // (4,18): error CS0551: Explicit interface implementation 'C1.I1.M01' is missing accessor 'I1.M01.set' // static int I1.M01 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "M01").WithArguments("C1.I1.M01", "I1.M01.set").WithLocation(4, 18), // (4,24): error CS0550: 'C1.I1.M01.get' adds an accessor not found in interface member 'I1.M01' // static int I1.M01 { get; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C1.I1.M01.get", "I1.M01").WithLocation(4, 24) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); c1M01 = c1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, c1M01.GetMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticProperty_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void I1::set_M01(int32) } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig specialname static int32 I1.get_M01 () cil managed { .override method int32 I1::get_M01() IL_0000: ldc.i4.0 IL_0001: ret } .method private hidebysig specialname static void I1.set_M01 ( int32 'value' ) cil managed { .override method void I1::set_M01(int32) IL_0000: ret } .property instance int32 I1.M01() { .get int32 I2::I1.get_M01() .set void I2::I1.set_M01(int32) } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<PropertySymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.SetMethod)); var i2M01 = i2.GetMembers().OfType<PropertySymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.GetMethod, i2M01.GetMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.SetMethod, i2M01.SetMethod.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticProperty_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static int M01 { get; set; } } class C1 { public static int M01 { get; set; } } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<PropertySymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Get = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.GetMethod); var c2M01Set = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.SetMethod); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Get.MethodKind); Assert.False(c2M01Get.HasRuntimeSpecialName); Assert.False(c2M01Get.HasSpecialName); Assert.Equal("System.Int32 C2.I1.get_M01()", c2M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c2M01Get.ExplicitInterfaceImplementations.Single()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Set.MethodKind); Assert.False(c2M01Set.HasRuntimeSpecialName); Assert.False(c2M01Set.HasSpecialName); Assert.Equal("void C2.I1.set_M01(System.Int32 value)", c2M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c2M01Set.ExplicitInterfaceImplementations.Single()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c2M01); var c1M01 = module.GlobalNamespace.GetMember<PropertySymbol>("C1.M01"); var c1M01Get = c1M01.GetMethod; var c1M01Set = c1M01.SetMethod; Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c1M01Get.MethodKind); Assert.False(c1M01Get.HasRuntimeSpecialName); Assert.True(c1M01Get.HasSpecialName); Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c1M01Set.MethodKind); Assert.False(c1M01Set.HasRuntimeSpecialName); Assert.True(c1M01Set.HasSpecialName); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); } else { Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Equal("System.Int32 C1.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.PropertyGet, c2M01Get.MethodKind); Assert.False(c2M01Get.HasRuntimeSpecialName); Assert.True(c2M01Get.HasSpecialName); Assert.Same(c2M01.GetMethod, c2M01Get); Assert.Empty(c2M01Get.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.PropertySet, c2M01Set.MethodKind); Assert.False(c2M01Set.HasRuntimeSpecialName); Assert.True(c2M01Set.HasSpecialName); Assert.Same(c2M01.SetMethod, c2M01Set); Assert.Empty(c2M01Set.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.get_M01", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C1.M01.get"" IL_0005: ret } "); verifier.VerifyIL("C2.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.set"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticProperty_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static int32 get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void modopt(I1) set_M01 ( int32 modopt(I1) 'value' ) cil managed { } .property int32 M01() { .get int32 I1::get_M01() .set void modopt(I1) I1::set_M01(int32 modopt(I1)) } } .class interface public auto ansi abstract I2 { .method public hidebysig specialname abstract virtual static int32 modopt(I2) get_M01 () cil managed { } .method public hidebysig specialname abstract virtual static void set_M01 ( int32 modopt(I2) 'value' ) cil managed { } .property int32 modopt(I2) M01() { .get int32 modopt(I2) I2::get_M01() .set void I2::set_M01(int32 modopt(I2)) } } "; var source1 = @" class C1 : I1 { public static int M01 { get; set; } } class C2 : I1 { static int I1.M01 { get; set; } } class C3 : I2 { static int I2.M01 { get; set; } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c1M01 = (PropertySymbol)c1.FindImplementationForInterfaceMember(m01); var c1M01Get = c1M01.GetMethod; var c1M01Set = c1M01.SetMethod; Assert.Equal("System.Int32 C1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Equal(MethodKind.PropertyGet, c1M01Get.MethodKind); Assert.Equal("System.Int32 C1.M01.get", c1M01Get.ToTestDisplayString()); Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Same(c1M01Get, c1.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Equal(MethodKind.PropertySet, c1M01Set.MethodKind); Assert.Equal("void C1.M01.set", c1M01Set.ToTestDisplayString()); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Same(m01.GetMethod, c1M01Get.ExplicitInterfaceImplementations.Single()); c1M01Set = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Set.MethodKind); Assert.Equal("void modopt(I1) C1.I1.set_M01(System.Int32 modopt(I1) value)", c1M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c1M01Set.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); } else { Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); Assert.Same(c1M01Set, c1.FindImplementationForInterfaceMember(m01.SetMethod)); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Get = c2M01.GetMethod; var c2M01Set = c2M01.SetMethod; Assert.Equal("System.Int32 C2.I1.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c2M01Get.MethodKind); Assert.Equal("System.Int32 C2.I1.M01.get", c2M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c2M01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Get, c2.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c2M01Set.MethodKind); Assert.Equal("void modopt(I1) C2.I1.M01.set", c2M01Set.ToTestDisplayString()); Assert.Equal("System.Int32 modopt(I1) value", c2M01Set.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.SetMethod, c2M01Set.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Set, c2.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(c2M01, c2.GetMembers().OfType<PropertySymbol>().Single()); Assert.Equal(2, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var c3 = module.GlobalNamespace.GetTypeMember("C3"); m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c3M01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); var c3M01Get = c3M01.GetMethod; var c3M01Set = c3M01.SetMethod; Assert.Equal("System.Int32 modopt(I2) C3.I2.M01 { get; set; }", c3M01.ToTestDisplayString()); Assert.True(c3M01.IsStatic); Assert.False(c3M01.IsAbstract); Assert.False(c3M01.IsVirtual); Assert.Same(m01, c3M01.ExplicitInterfaceImplementations.Single()); Assert.True(c3M01Get.IsStatic); Assert.False(c3M01Get.IsAbstract); Assert.False(c3M01Get.IsVirtual); Assert.False(c3M01Get.IsMetadataVirtual()); Assert.False(c3M01Get.IsMetadataFinal); Assert.False(c3M01Get.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertyGet, c3M01Get.MethodKind); Assert.Equal("System.Int32 modopt(I2) C3.I2.M01.get", c3M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c3M01Get.ExplicitInterfaceImplementations.Single()); Assert.Same(c3M01Get, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.True(c3M01Set.IsStatic); Assert.False(c3M01Set.IsAbstract); Assert.False(c3M01Set.IsVirtual); Assert.False(c3M01Set.IsMetadataVirtual()); Assert.False(c3M01Set.IsMetadataFinal); Assert.False(c3M01Set.IsMetadataNewSlot()); Assert.Equal(MethodKind.PropertySet, c3M01Set.MethodKind); Assert.Equal("void C3.I2.M01.set", c3M01Set.ToTestDisplayString()); Assert.Equal("System.Int32 modopt(I2) value", c3M01Set.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.SetMethod, c3M01Set.ExplicitInterfaceImplementations.Single()); Assert.Same(c3M01Set, c3.FindImplementationForInterfaceMember(m01.SetMethod)); Assert.Same(c3M01, c3.GetMembers().OfType<PropertySymbol>().Single()); Assert.Equal(2, c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); } verifier.VerifyIL("C1.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.set"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStatiProperty_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static int M01 { get; set; } abstract static int M02 { get; set; } } public class C1 { public static int M01 { get; set; } } public class C2 : C1, I1 { static int I1.M02 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<PropertySymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<PropertySymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<PropertySymbol>("M01"); Assert.Equal("System.Int32 C1.M01 { get; set; }", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); var c1M01Get = c1M01.GetMethod; Assert.True(c1M01Get.IsStatic); Assert.False(c1M01Get.IsAbstract); Assert.False(c1M01Get.IsVirtual); Assert.False(c1M01Get.IsMetadataVirtual()); Assert.False(c1M01Get.IsMetadataFinal); Assert.False(c1M01Get.IsMetadataNewSlot()); Assert.Empty(c1M01Get.ExplicitInterfaceImplementations); var c1M01Set = c1M01.SetMethod; Assert.True(c1M01Set.IsStatic); Assert.False(c1M01Set.IsAbstract); Assert.False(c1M01Set.IsVirtual); Assert.False(c1M01Set.IsMetadataVirtual()); Assert.False(c1M01Set.IsMetadataFinal); Assert.False(c1M01Set.IsMetadataNewSlot()); Assert.Empty(c1M01Set.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01Get = c3.FindImplementationForInterfaceMember(m01.GetMethod); Assert.Equal("System.Int32 C2.I1.get_M01()", c2M01Get.ToTestDisplayString()); var c2M01Set = c3.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal("void C2.I1.set_M01(System.Int32 value)", c2M01Set.ToTestDisplayString()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c3.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.GetMethod, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c1M01.SetMethod, c3.FindImplementationForInterfaceMember(m01.SetMethod)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<PropertySymbol>().Single(); var c2M02 = c3.BaseType().GetMember<PropertySymbol>("I1.M02"); Assert.Equal("System.Int32 C2.I1.M02 { get; set; }", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c2M02.GetMethod, c3.FindImplementationForInterfaceMember(m02.GetMethod)); Assert.Same(c2M02.SetMethod, c3.FindImplementationForInterfaceMember(m02.SetMethod)); } } [Fact] public void ImplementAbstractStaticProperty_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1 : I1 { public static int M01 { get; set; } } public class C2 : C1 { new public static int M01 { get; set; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.get_M01", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C2.M01.get"" IL_0005: ret } "); verifier.VerifyIL("C3.I1.set_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.set"" IL_0006: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); var c2M01 = c3.BaseType().GetMember<PropertySymbol>("M01"); var c2M01Get = c2M01.GetMethod; var c2M01Set = c2M01.SetMethod; Assert.Equal("System.Int32 C2.M01 { get; set; }", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.True(c2M01Get.IsStatic); Assert.False(c2M01Get.IsAbstract); Assert.False(c2M01Get.IsVirtual); Assert.False(c2M01Get.IsMetadataVirtual()); Assert.False(c2M01Get.IsMetadataFinal); Assert.False(c2M01Get.IsMetadataNewSlot()); Assert.Empty(c2M01Get.ExplicitInterfaceImplementations); Assert.True(c2M01Set.IsStatic); Assert.False(c2M01Set.IsAbstract); Assert.False(c2M01Set.IsVirtual); Assert.False(c2M01Set.IsMetadataVirtual()); Assert.False(c2M01Set.IsMetadataFinal); Assert.False(c2M01Set.IsMetadataNewSlot()); Assert.Empty(c2M01Set.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (PropertySymbol)c3.FindImplementationForInterfaceMember(m01); // Forwarding methods for accessors aren't tied to a property Assert.Null(c3M01); var c3M01Get = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.GetMethod); Assert.Equal("System.Int32 C3.I1.get_M01()", c3M01Get.ToTestDisplayString()); Assert.Same(m01.GetMethod, c3M01Get.ExplicitInterfaceImplementations.Single()); var c3M01Set = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.SetMethod); Assert.Equal("void C3.I1.set_M01(System.Int32 value)", c3M01Set.ToTestDisplayString()); Assert.Same(m01.SetMethod, c3M01Set.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c2M01Get, c3.FindImplementationForInterfaceMember(m01.GetMethod)); Assert.Same(c2M01Set, c3.FindImplementationForInterfaceMember(m01.SetMethod)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_19(bool genericFirst) { // An "ambiguity" in implicit/explicit implementation declared in generic base class. var generic = @" public static T M01 { get; set; } "; var nonGeneric = @" static int I1.M01 { get; set; } "; var source1 = @" public interface I1 { abstract static int M01 { get; set; } } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<PropertySymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1<T>.I1.M01 { get; set; }", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticProperty_20(bool genericFirst) { // Same as ImplementAbstractStaticProperty_19 only interface is generic too. var generic = @" static T I1<T>.M01 { get; set; } "; var nonGeneric = @" public static int M01 { get; set; } "; var source1 = @" public interface I1<T> { abstract static T M01 { get; set; } } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<PropertySymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<PropertySymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (PropertySymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("T C1<T>.I1<T>.M01 { get; set; }", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_01(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public event System.Action M01; } " + typeKeyword + @" C3 : I1 { static event System.Action M01; } " + typeKeyword + @" C4 : I1 { event System.Action I1.M01 { add{} remove{}} } " + typeKeyword + @" C5 : I1 { public static event System.Action<int> M01; } " + typeKeyword + @" C6 : I1 { static event System.Action<int> I1.M01 { add{} remove{}} } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is not static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,28): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.M01 { add{} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 28), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'Action'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "System.Action").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,40): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action<int> I1.M01 { add{} remove{}} Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 40) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_02(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract event System.Action M01; } " + typeKeyword + @" C1 : I1 {} " + typeKeyword + @" C2 : I1 { public static event System.Action M01; } " + typeKeyword + @" C3 : I1 { event System.Action M01; } " + typeKeyword + @" C4 : I1 { static event System.Action I1.M01 { add{} remove{} } } " + typeKeyword + @" C5 : I1 { public event System.Action<int> M01; } " + typeKeyword + @" C6 : I1 { event System.Action<int> I1.M01 { add{} remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1.M01' // C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(8, 10), // (12,10): error CS0736: 'C2' does not implement instance interface member 'I1.M01'. 'C2.M01' cannot implement the interface member because it is static. // C2 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "I1").WithArguments("C2", "I1.M01", "C2.M01").WithLocation(12, 10), // (18,10): error CS0737: 'C3' does not implement interface member 'I1.M01'. 'C3.M01' cannot implement an interface member because it is not public. // C3 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1").WithArguments("C3", "I1.M01", "C3.M01").WithLocation(18, 10), // (24,10): error CS0535: 'C4' does not implement interface member 'I1.M01' // C4 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C4", "I1.M01").WithLocation(24, 10), // (26,35): error CS0539: 'C4.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C4.M01").WithLocation(26, 35), // (30,10): error CS0738: 'C5' does not implement interface member 'I1.M01'. 'C5.M01' cannot implement 'I1.M01' because it does not have the matching return type of 'Action'. // C5 : I1 Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1").WithArguments("C5", "I1.M01", "C5.M01", "System.Action").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1.M01' // C6 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C6", "I1.M01").WithLocation(36, 10), // (38,33): error CS0539: 'C6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action<int> I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C6.M01").WithLocation(38, 33) ); } [Fact] public void ImplementAbstractStaticEvent_03() { var source1 = @"#pragma warning disable CS0067 // WRN_UnreferencedEvent public interface I1 { abstract static event System.Action M01; } interface I2 : I1 {} interface I3 : I1 { public virtual event System.Action M01 { add{} remove{} } } interface I4 : I1 { static event System.Action M01; } interface I5 : I1 { event System.Action I1.M01 { add{} remove{} } } interface I6 : I1 { static event System.Action I1.M01 { add{} remove{} } } interface I7 : I1 { abstract static event System.Action M01; } interface I8 : I1 { abstract static event System.Action I1.M01; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,40): warning CS0108: 'I3.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // public virtual event System.Action M01 { add{} remove{} } Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I3.M01", "I1.M01").WithLocation(12, 40), // (17,32): warning CS0108: 'I4.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // static event System.Action M01; Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I4.M01", "I1.M01").WithLocation(17, 32), // (22,28): error CS0539: 'I5.M01' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I5.M01").WithLocation(22, 28), // (27,35): error CS0106: The modifier 'static' is not valid for this item // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(27, 35), // (27,35): error CS0539: 'I6.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I6.M01").WithLocation(27, 35), // (32,41): warning CS0108: 'I7.M01' hides inherited member 'I1.M01'. Use the new keyword if hiding was intended. // abstract static event System.Action M01; Diagnostic(ErrorCode.WRN_NewRequired, "M01").WithArguments("I7.M01", "I1.M01").WithLocation(32, 41), // (37,44): error CS0106: The modifier 'static' is not valid for this item // abstract static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "M01").WithArguments("static").WithLocation(37, 44), // (37,44): error CS0539: 'I8.M01' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static event System.Action I1.M01; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("I8.M01").WithLocation(37, 44) ); foreach (var m01 in compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers()) { Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I8").FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_04(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; abstract static event System.Action M02; } "; var source2 = typeKeyword + @" Test: I1 { static event System.Action I1.M01 { add{} remove => throw null; } public static event System.Action M02; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,35): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static event System.Action I1.M01 { add{} remove => throw null; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 35), // (5,39): warning CS0067: The event 'Test.M02' is never used // public static event System.Action M02; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "M02").WithArguments("Test.M02").WithLocation(5, 39) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,35): error CS8703: The modifier 'static' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // static event System.Action I1.M01 { add{} remove => throw null; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("static", "9.0", "preview").WithLocation(4, 35), // (5,39): warning CS0067: The event 'Test.M02' is never used // public static event System.Action M02; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "M02").WithArguments("Test.M02").WithLocation(5, 39), // (10,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M01").WithArguments("abstract", "9.0", "preview").WithLocation(10, 41), // (11,41): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static event System.Action M02; Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M02").WithArguments("abstract", "9.0", "preview").WithLocation(11, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_05(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } "; var source2 = typeKeyword + @" Test1: I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.remove' cannot implement interface member 'I1.M01.remove' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.remove", "I1.M01.remove", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.add' cannot implement interface member 'I1.M01.add' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.add", "I1.M01.add", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.M01.remove' cannot implement interface member 'I1.M01.remove' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.remove", "I1.M01.remove", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01.add' cannot implement interface member 'I1.M01.add' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01.add", "I1.M01.add", "Test1").WithLocation(2, 12), // (2,12): error CS8929: 'Test1.M01' cannot implement interface member 'I1.M01' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("Test1.M01", "I1.M01", "Test1").WithLocation(2, 12), // (9,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_06(bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } "; var source2 = typeKeyword + @" Test1: I1 { static event System.Action I1.M01 { add => throw null; remove => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static event System.Action I1.M01 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 35) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,35): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static event System.Action I1.M01 { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(4, 35), // (9,41): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static event System.Action M01; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M01").WithLocation(9, 41) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_07(bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C : I1 { public static event System.Action M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; var m01Remove = m01.RemoveMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.False(cM01Add.HasRuntimeSpecialName); Assert.True(cM01Add.HasSpecialName); Assert.Equal("void C.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.False(cM01Remove.HasRuntimeSpecialName); Assert.True(cM01Remove.HasSpecialName); Assert.Equal("void C.M01.remove", cM01Remove.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Add.ExplicitInterfaceImplementations); Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_08(bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1 { abstract static event System.Action M01; } " + typeKeyword + @" C : I1 { static event System.Action I1.M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; var m01Remove = m01.RemoveMethod; var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C.I1.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.False(cM01Add.HasRuntimeSpecialName); Assert.True(cM01Add.HasSpecialName); Assert.Equal("void C.I1.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.False(cM01Remove.HasRuntimeSpecialName); Assert.True(cM01Remove.HasSpecialName); Assert.Equal("void C.I1.M01.remove", cM01Remove.ToTestDisplayString()); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_09() { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1 { abstract static event System.Action M01; } public class C1 { public static event System.Action M01 { add => throw null; remove {} } } public class C2 : C1, I1 { static event System.Action I1.M01 { add => throw null; remove {} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<EventSymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var cM01 = (EventSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C2.I1.M01", cM01.ToTestDisplayString()); Assert.Same(cM01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(cM01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, cM01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, cM01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, cM01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_10() { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } .class public auto ansi beforefieldinit C1 extends System.Object implements I1 { .method private hidebysig specialname static void I1.add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::add_M01(class [mscorlib]System.Action) IL_0000: ret } .method private hidebysig specialname static void I1.remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::remove_M01(class [mscorlib]System.Action) IL_0000: ret } .event [mscorlib]System.Action I1.M01 { .addon void C1::I1.add_M01(class [mscorlib]System.Action) .removeon void C1::I1.remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void C1::add_M01(class [mscorlib]System.Action) .removeon void C1::remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements I1 { .method public hidebysig specialname static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void C2::add_M01(class [mscorlib]System.Action) .removeon void C2::remove_M01(class [mscorlib]System.Action) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1 { } public class C5 : C2, I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c1M01 = (EventSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C1.I1.M01", c1M01.ToTestDisplayString()); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c2.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c4.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c4.FindImplementationForInterfaceMember(m01.RemoveMethod)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (EventSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action C2.M01", c2M01.ToTestDisplayString()); Assert.Same(c2M01.AddMethod, c5.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c2M01.RemoveMethod, c5.FindImplementationForInterfaceMember(m01.RemoveMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Fact] public void ImplementAbstractStaticEvent_11() { // Ignore invalid metadata (non-abstract static virtual method). scenario1(); scenario2(); scenario3(); void scenario1() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname static virtual void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname static virtual void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,34): error CS0539: 'C1.M01' in explicit interface declaration is not found among members of the interface that can be implemented // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M01").WithArguments("C1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c.FindImplementationForInterfaceMember(m01)); Assert.Null(c.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c.FindImplementationForInterfaceMember(m01.RemoveMethod)); } } void scenario2() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname static virtual void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { add {} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add {} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var m01Add = m01.AddMethod; Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C1.M01", cM01.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.Same(cM01Add, c.FindImplementationForInterfaceMember(m01Add)); Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.Equal("void C1.M01.add", cM01Add.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.Equal("void C1.M01.remove", cM01Remove.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.RemoveMethod)); if (module is PEModuleSymbol) { Assert.Same(m01Add, cM01Add.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01Add.ExplicitInterfaceImplementations); } Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,46): error CS0550: 'C1.I1.M01.remove' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "remove").WithArguments("C1.I1.M01.remove", "I1.M01").WithLocation(4, 46) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static event System.Action M01 { add{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { add{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation5.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source6 = @" public class C1 : I1 { public static event System.Action M01 { remove{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.add' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.add").WithLocation(2, 19), // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source7 = @" public class C1 : I1 { static event System.Action I1.M01 { remove{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.add' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.add").WithLocation(2, 19), // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34), // (4,40): error CS0550: 'C1.I1.M01.remove' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "remove").WithArguments("C1.I1.M01.remove", "I1.M01").WithLocation(4, 40) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } void scenario3() { var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname static virtual void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { IL_0000: ret } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I1 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i1.FindImplementationForInterfaceMember(m01.AddMethod)); var source2 = @" public class C1 : I1 { static event System.Action I1.M01 { remove {} } } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add {} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); var source3 = @" public class C1 : I1 { public static event System.Action M01 { add{} remove{} } } "; var compilation3 = CreateCompilationWithIL(source3, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation3, sourceSymbolValidator: validate3, symbolValidator: validate3, verify: Verification.Skipped).VerifyDiagnostics(); void validate3(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var m01Remove = m01.RemoveMethod; Assert.Equal(1, c.GetMembers().OfType<EventSymbol>().Count()); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var cM01 = (EventSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.Equal("event System.Action C1.M01", cM01.ToTestDisplayString()); var cM01Remove = cM01.RemoveMethod; Assert.Same(cM01Remove, c.FindImplementationForInterfaceMember(m01Remove)); Assert.True(cM01Remove.IsStatic); Assert.False(cM01Remove.IsAbstract); Assert.False(cM01Remove.IsVirtual); Assert.False(cM01Remove.IsMetadataVirtual()); Assert.False(cM01Remove.IsMetadataFinal); Assert.False(cM01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, cM01Remove.MethodKind); Assert.Equal("void C1.M01.remove", cM01Remove.ToTestDisplayString()); var cM01Add = cM01.AddMethod; Assert.True(cM01Add.IsStatic); Assert.False(cM01Add.IsAbstract); Assert.False(cM01Add.IsVirtual); Assert.False(cM01Add.IsMetadataVirtual()); Assert.False(cM01Add.IsMetadataFinal); Assert.False(cM01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, cM01Add.MethodKind); Assert.Equal("void C1.M01.add", cM01Add.ToTestDisplayString()); Assert.Null(c.FindImplementationForInterfaceMember(m01.AddMethod)); if (module is PEModuleSymbol) { Assert.Same(m01Remove, cM01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01Remove.ExplicitInterfaceImplementations); } Assert.Empty(cM01.ExplicitInterfaceImplementations); Assert.Empty(cM01Add.ExplicitInterfaceImplementations); } var source4 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} remove{} } } "; var compilation4 = CreateCompilationWithIL(source4, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation4.VerifyDiagnostics( // (4,40): error CS0550: 'C1.I1.M01.add' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} remove{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "add").WithArguments("C1.I1.M01.add", "I1.M01").WithLocation(4, 40) ); c1 = compilation4.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, c1M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); var source5 = @" public class C1 : I1 { public static event System.Action M01 { remove{} } } "; var compilation5 = CreateCompilationWithIL(source5, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation5.VerifyDiagnostics( // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation5.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.RemoveMethod, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); var source6 = @" public class C1 : I1 { public static event System.Action M01 { add{} } } "; var compilation6 = CreateCompilationWithIL(source6, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation6.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.remove' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.remove").WithLocation(2, 19), // (4,38): error CS0065: 'C1.M01': event property must have both add and remove accessors // public static event System.Action M01 { remove{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.M01").WithLocation(4, 38) ); c1 = compilation6.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); var source7 = @" public class C1 : I1 { static event System.Action I1.M01 { add{} } } "; var compilation7 = CreateCompilationWithIL(source7, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation7.VerifyDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01.remove' // public class C1 : I1 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1").WithArguments("C1", "I1.M01.remove").WithLocation(2, 19), // (4,34): error CS0065: 'C1.I1.M01': event property must have both add and remove accessors // static event System.Action I1.M01 { add{} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "M01").WithArguments("C1.I1.M01").WithLocation(4, 34), // (4,40): error CS0550: 'C1.I1.M01.add' adds an accessor not found in interface member 'I1.M01' // static event System.Action I1.M01 { add{} } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "add").WithArguments("C1.I1.M01.add", "I1.M01").WithLocation(4, 40) ); c1 = compilation7.GlobalNamespace.GetTypeMember("C1"); i1 = c1.Interfaces().Single(); m01 = i1.GetMembers().OfType<EventSymbol>().Single(); c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, c1M01.AddMethod.ExplicitInterfaceImplementations.Single()); } } [Fact] public void ImplementAbstractStaticEvent_12() { // Ignore invalid metadata (default interface implementation for a static method) var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { } .event [mscorlib]System.Action M01 { .addon void I1::add_M01(class [mscorlib]System.Action) .removeon void I1::remove_M01(class [mscorlib]System.Action) } } .class interface public auto ansi abstract I2 implements I1 { .method private hidebysig specialname static void I1.add_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::add_M01(class [mscorlib]System.Action) IL_0000: ret } .method private hidebysig specialname static void I1.remove_M01 ( class [mscorlib]System.Action 'value' ) cil managed { .override method void I1::remove_M01(class [mscorlib]System.Action) IL_0000: ret } .event [mscorlib]System.Action I1.M01 { .addon void I2::I1.add_M01(class [mscorlib]System.Action) .removeon void I2::I1.remove_M01(class [mscorlib]System.Action) } } "; var source1 = @" public class C1 : I2 { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1.M01' // public class C1 : I2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2").WithArguments("C1", "I1.M01").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<EventSymbol>().Single(); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Null(c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Null(i2.FindImplementationForInterfaceMember(m01.RemoveMethod)); var i2M01 = i2.GetMembers().OfType<EventSymbol>().Single(); Assert.Same(m01, i2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.AddMethod, i2M01.AddMethod.ExplicitInterfaceImplementations.Single()); Assert.Same(m01.RemoveMethod, i2M01.RemoveMethod.ExplicitInterfaceImplementations.Single()); } [Fact] public void ImplementAbstractStaticEvent_13() { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public interface I1 { abstract static event System.Action M01; } class C1 { public static event System.Action M01 { add => throw null; remove{} } } class C2 : C1, I1 { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var m01 = module.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<EventSymbol>().Single(); var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Add = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.AddMethod); var c2M01Remove = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Add.MethodKind); Assert.False(c2M01Add.HasRuntimeSpecialName); Assert.False(c2M01Add.HasSpecialName); Assert.Equal("void C2.I1.add_M01(System.Action value)", c2M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c2M01Add.ExplicitInterfaceImplementations.Single()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01Remove.MethodKind); Assert.False(c2M01Remove.HasRuntimeSpecialName); Assert.False(c2M01Remove.HasSpecialName); Assert.Equal("void C2.I1.remove_M01(System.Action value)", c2M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c2M01Remove.ExplicitInterfaceImplementations.Single()); // Forwarding methods for accessors aren't tied to a property Assert.Null(c2M01); var c1M01 = module.GlobalNamespace.GetMember<EventSymbol>("C1.M01"); var c1M01Add = c1M01.AddMethod; var c1M01Remove = c1M01.RemoveMethod; Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c1M01Add.MethodKind); Assert.False(c1M01Add.HasRuntimeSpecialName); Assert.True(c1M01Add.HasSpecialName); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c1M01Remove.MethodKind); Assert.False(c1M01Remove.HasRuntimeSpecialName); Assert.True(c1M01Remove.HasSpecialName); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); } else { Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Equal("event System.Action C1.M01", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.EventAdd, c2M01Add.MethodKind); Assert.False(c2M01Add.HasRuntimeSpecialName); Assert.True(c2M01Add.HasSpecialName); Assert.Same(c2M01.AddMethod, c2M01Add); Assert.Empty(c2M01Add.ExplicitInterfaceImplementations); Assert.Equal(MethodKind.EventRemove, c2M01Remove.MethodKind); Assert.False(c2M01Remove.HasRuntimeSpecialName); Assert.True(c2M01Remove.HasSpecialName); Assert.Same(c2M01.RemoveMethod, c2M01Remove); Assert.Empty(c2M01Remove.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C2.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.remove"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticEvent_14() { // A forwarding method is added for an implicit implementation with modopt mismatch. var ilSource = @" .class interface public auto ansi abstract I1 { .method public hidebysig specialname abstract virtual static void add_M01 ( class [mscorlib]System.Action`1<int32 modopt(I1)> 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void remove_M01 ( class [mscorlib]System.Action`1<int32 modopt(I1)> 'value' ) cil managed { } .event class [mscorlib]System.Action`1<int32 modopt(I1)> M01 { .addon void I1::add_M01(class [mscorlib]System.Action`1<int32 modopt(I1)>) .removeon void I1::remove_M01(class [mscorlib]System.Action`1<int32 modopt(I1)>) } } .class interface public auto ansi abstract I2 { .method public hidebysig specialname abstract virtual static void add_M02 ( class [mscorlib]System.Action modopt(I1) 'value' ) cil managed { } .method public hidebysig specialname abstract virtual static void modopt(I2) remove_M02 ( class [mscorlib]System.Action 'value' ) cil managed { } .event class [mscorlib]System.Action M02 { .addon void I2::add_M02(class [mscorlib]System.Action modopt(I1)) .removeon void modopt(I2) I2::remove_M02(class [mscorlib]System.Action) } } "; var source1 = @" class C1 : I1 { public static event System.Action<int> M01 { add => throw null; remove{} } } class C2 : I1 { static event System.Action<int> I1.M01 { add => throw null; remove{} } } #pragma warning disable CS0067 // The event 'C3.M02' is never used class C3 : I2 { public static event System.Action M02; } class C4 : I2 { static event System.Action I2.M02 { add => throw null; remove{} } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c1M01 = c1.GetMembers().OfType<EventSymbol>().Single(); var c1M01Add = c1M01.AddMethod; var c1M01Remove = c1M01.RemoveMethod; Assert.Equal("event System.Action<System.Int32> C1.M01", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Equal(MethodKind.EventAdd, c1M01Add.MethodKind); Assert.Equal("void C1.M01.add", c1M01Add.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32> value", c1M01Add.Parameters.Single().ToTestDisplayString()); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c1M01Remove.MethodKind); Assert.Equal("void C1.M01.remove", c1M01Remove.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32> value", c1M01Remove.Parameters.Single().ToTestDisplayString()); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { c1M01Add = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Add.MethodKind); Assert.Equal("void C1.I1.add_M01(System.Action<System.Int32 modopt(I1)> value)", c1M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c1M01Add.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); c1M01Remove = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01Remove.MethodKind); Assert.Equal("void C1.I1.remove_M01(System.Action<System.Int32 modopt(I1)> value)", c1M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c1M01Remove.ExplicitInterfaceImplementations.Single()); Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); // Forwarding methods aren't tied to an event Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c1.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01Add, c1.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01Remove, c1.FindImplementationForInterfaceMember(m01.RemoveMethod)); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); var c2M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); var c2M01Add = c2M01.AddMethod; var c2M01Remove = c2M01.RemoveMethod; Assert.Equal("event System.Action<System.Int32 modopt(I1)> C2.I1.M01", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Same(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c2M01Add.MethodKind); Assert.Equal("void C2.I1.M01.add", c2M01Add.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32 modopt(I1)> value", c2M01Add.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.AddMethod, c2M01Add.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Add, c2.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c2M01Remove.MethodKind); Assert.Equal("void C2.I1.M01.remove", c2M01Remove.ToTestDisplayString()); Assert.Equal("System.Action<System.Int32 modopt(I1)> value", c2M01Remove.Parameters.Single().ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c2M01Remove.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01Remove, c2.FindImplementationForInterfaceMember(m01.RemoveMethod)); Assert.Same(c2M01, c2.GetMembers().OfType<EventSymbol>().Single()); Assert.Equal(2, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m02 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c3M02 = c3.GetMembers().OfType<EventSymbol>().Single(); var c3M02Add = c3M02.AddMethod; var c3M02Remove = c3M02.RemoveMethod; Assert.Equal("event System.Action C3.M02", c3M02.ToTestDisplayString()); Assert.Empty(c3M02.ExplicitInterfaceImplementations); Assert.True(c3M02.IsStatic); Assert.False(c3M02.IsAbstract); Assert.False(c3M02.IsVirtual); Assert.Equal(MethodKind.EventAdd, c3M02Add.MethodKind); Assert.Equal("void C3.M02.add", c3M02Add.ToTestDisplayString()); Assert.Equal("System.Action value", c3M02Add.Parameters.Single().ToTestDisplayString()); Assert.Empty(c3M02Add.ExplicitInterfaceImplementations); Assert.True(c3M02Add.IsStatic); Assert.False(c3M02Add.IsAbstract); Assert.False(c3M02Add.IsVirtual); Assert.False(c3M02Add.IsMetadataVirtual()); Assert.False(c3M02Add.IsMetadataFinal); Assert.False(c3M02Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c3M02Remove.MethodKind); Assert.Equal("void C3.M02.remove", c3M02Remove.ToTestDisplayString()); Assert.Equal("System.Void", c3M02Remove.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Empty(c3M02Remove.ExplicitInterfaceImplementations); Assert.True(c3M02Remove.IsStatic); Assert.False(c3M02Remove.IsAbstract); Assert.False(c3M02Remove.IsVirtual); Assert.False(c3M02Remove.IsMetadataVirtual()); Assert.False(c3M02Remove.IsMetadataFinal); Assert.False(c3M02Remove.IsMetadataNewSlot()); if (module is PEModuleSymbol) { c3M02Add = (MethodSymbol)c3.FindImplementationForInterfaceMember(m02.AddMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c3M02Add.MethodKind); Assert.Equal("void C3.I2.add_M02(System.Action modopt(I1) value)", c3M02Add.ToTestDisplayString()); Assert.Same(m02.AddMethod, c3M02Add.ExplicitInterfaceImplementations.Single()); Assert.True(c3M02Add.IsStatic); Assert.False(c3M02Add.IsAbstract); Assert.False(c3M02Add.IsVirtual); Assert.False(c3M02Add.IsMetadataVirtual()); Assert.False(c3M02Add.IsMetadataFinal); Assert.False(c3M02Add.IsMetadataNewSlot()); c3M02Remove = (MethodSymbol)c3.FindImplementationForInterfaceMember(m02.RemoveMethod); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c3M02Remove.MethodKind); Assert.Equal("void modopt(I2) C3.I2.remove_M02(System.Action value)", c3M02Remove.ToTestDisplayString()); Assert.Same(m02.RemoveMethod, c3M02Remove.ExplicitInterfaceImplementations.Single()); Assert.True(c3M02Remove.IsStatic); Assert.False(c3M02Remove.IsAbstract); Assert.False(c3M02Remove.IsVirtual); Assert.False(c3M02Remove.IsMetadataVirtual()); Assert.False(c3M02Remove.IsMetadataFinal); Assert.False(c3M02Remove.IsMetadataNewSlot()); // Forwarding methods aren't tied to an event Assert.Null(c3.FindImplementationForInterfaceMember(m02)); } else { Assert.Same(c3M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c3M02Add, c3.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.Same(c3M02Remove, c3.FindImplementationForInterfaceMember(m02.RemoveMethod)); } var c4 = module.GlobalNamespace.GetTypeMember("C4"); var c4M02 = (EventSymbol)c4.FindImplementationForInterfaceMember(m02); var c4M02Add = c4M02.AddMethod; var c4M02Remove = c4M02.RemoveMethod; Assert.Equal("event System.Action C4.I2.M02", c4M02.ToTestDisplayString()); // Signatures of accessors are lacking custom modifiers due to https://github.com/dotnet/roslyn/issues/53390. Assert.True(c4M02.IsStatic); Assert.False(c4M02.IsAbstract); Assert.False(c4M02.IsVirtual); Assert.Same(m02, c4M02.ExplicitInterfaceImplementations.Single()); Assert.True(c4M02Add.IsStatic); Assert.False(c4M02Add.IsAbstract); Assert.False(c4M02Add.IsVirtual); Assert.False(c4M02Add.IsMetadataVirtual()); Assert.False(c4M02Add.IsMetadataFinal); Assert.False(c4M02Add.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventAdd, c4M02Add.MethodKind); Assert.Equal("void C4.I2.M02.add", c4M02Add.ToTestDisplayString()); Assert.Equal("System.Action value", c4M02Add.Parameters.Single().ToTestDisplayString()); Assert.Equal("System.Void", c4M02Add.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Same(m02.AddMethod, c4M02Add.ExplicitInterfaceImplementations.Single()); Assert.Same(c4M02Add, c4.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.True(c4M02Remove.IsStatic); Assert.False(c4M02Remove.IsAbstract); Assert.False(c4M02Remove.IsVirtual); Assert.False(c4M02Remove.IsMetadataVirtual()); Assert.False(c4M02Remove.IsMetadataFinal); Assert.False(c4M02Remove.IsMetadataNewSlot()); Assert.Equal(MethodKind.EventRemove, c4M02Remove.MethodKind); Assert.Equal("void C4.I2.M02.remove", c4M02Remove.ToTestDisplayString()); Assert.Equal("System.Action value", c4M02Remove.Parameters.Single().ToTestDisplayString()); Assert.Equal("System.Void", c4M02Remove.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Same(m02.RemoveMethod, c4M02Remove.ExplicitInterfaceImplementations.Single()); Assert.Same(c4M02Remove, c4.FindImplementationForInterfaceMember(m02.RemoveMethod)); Assert.Same(c4M02, c4.GetMembers().OfType<EventSymbol>().Single()); Assert.Equal(2, c4.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); } verifier.VerifyIL("C1.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C1.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C1.M01.remove"" IL_0006: ret } "); verifier.VerifyIL("C3.I2.add_M02", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C3.M02.add"" IL_0006: ret } "); verifier.VerifyIL("C3.I2.remove_M02", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C3.M02.remove"" IL_0006: ret } "); } [Fact] public void ImplementAbstractStaticEvent_15() { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public interface I1 { abstract static event System.Action M01; abstract static event System.Action M02; } public class C1 { public static event System.Action M01 { add => throw null; remove{} } } public class C2 : C1, I1 { static event System.Action I1.M02 { add => throw null; remove{} } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<EventSymbol>()); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers("M01").OfType<EventSymbol>().Single(); var c1M01 = c3.BaseType().BaseType().GetMember<EventSymbol>("M01"); Assert.Equal("event System.Action C1.M01", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.Empty(c1M01.ExplicitInterfaceImplementations); var c1M01Add = c1M01.AddMethod; Assert.True(c1M01Add.IsStatic); Assert.False(c1M01Add.IsAbstract); Assert.False(c1M01Add.IsVirtual); Assert.False(c1M01Add.IsMetadataVirtual()); Assert.False(c1M01Add.IsMetadataFinal); Assert.False(c1M01Add.IsMetadataNewSlot()); Assert.Empty(c1M01Add.ExplicitInterfaceImplementations); var c1M01Remove = c1M01.RemoveMethod; Assert.True(c1M01Remove.IsStatic); Assert.False(c1M01Remove.IsAbstract); Assert.False(c1M01Remove.IsVirtual); Assert.False(c1M01Remove.IsMetadataVirtual()); Assert.False(c1M01Remove.IsMetadataFinal); Assert.False(c1M01Remove.IsMetadataNewSlot()); Assert.Empty(c1M01Remove.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01Add = c3.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal("void C2.I1.add_M01(System.Action value)", c2M01Add.ToTestDisplayString()); var c2M01Remove = c3.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal("void C2.I1.remove_M01(System.Action value)", c2M01Remove.ToTestDisplayString()); // Forwarding methods for accessors aren't tied to an event Assert.Null(c3.FindImplementationForInterfaceMember(m01)); } else { Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c1M01.AddMethod, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c1M01.RemoveMethod, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); } var m02 = c3.Interfaces().Single().GetMembers("M02").OfType<EventSymbol>().Single(); var c2M02 = c3.BaseType().GetMember<EventSymbol>("I1.M02"); Assert.Equal("event System.Action C2.I1.M02", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); Assert.Same(c2M02.AddMethod, c3.FindImplementationForInterfaceMember(m02.AddMethod)); Assert.Same(c2M02.RemoveMethod, c3.FindImplementationForInterfaceMember(m02.RemoveMethod)); } } [Fact] public void ImplementAbstractStaticEvent_16() { // A new implicit implementation is properly considered. var source1 = @" public interface I1 { abstract static event System.Action M01; } public class C1 : I1 { public static event System.Action M01 { add{} remove => throw null; } } public class C2 : C1 { new public static event System.Action M01 { add{} remove => throw null; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); var verifier = CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("C3.I1.add_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.add"" IL_0006: ret } "); verifier.VerifyIL("C3.I1.remove_M01", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""void C2.M01.remove"" IL_0006: ret } "); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); var m01 = c3.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); var c2M01 = c3.BaseType().GetMember<EventSymbol>("M01"); var c2M01Add = c2M01.AddMethod; var c2M01Remove = c2M01.RemoveMethod; Assert.Equal("event System.Action C2.M01", c2M01.ToTestDisplayString()); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.Empty(c2M01.ExplicitInterfaceImplementations); Assert.True(c2M01Add.IsStatic); Assert.False(c2M01Add.IsAbstract); Assert.False(c2M01Add.IsVirtual); Assert.False(c2M01Add.IsMetadataVirtual()); Assert.False(c2M01Add.IsMetadataFinal); Assert.False(c2M01Add.IsMetadataNewSlot()); Assert.Empty(c2M01Add.ExplicitInterfaceImplementations); Assert.True(c2M01Remove.IsStatic); Assert.False(c2M01Remove.IsAbstract); Assert.False(c2M01Remove.IsVirtual); Assert.False(c2M01Remove.IsMetadataVirtual()); Assert.False(c2M01Remove.IsMetadataFinal); Assert.False(c2M01Remove.IsMetadataNewSlot()); Assert.Empty(c2M01Remove.ExplicitInterfaceImplementations); if (module is PEModuleSymbol) { var c3M01 = (EventSymbol)c3.FindImplementationForInterfaceMember(m01); // Forwarding methods for accessors aren't tied to an event Assert.Null(c3M01); var c3M01Add = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.AddMethod); Assert.Equal("void C3.I1.add_M01(System.Action value)", c3M01Add.ToTestDisplayString()); Assert.Same(m01.AddMethod, c3M01Add.ExplicitInterfaceImplementations.Single()); var c3M01Remove = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01.RemoveMethod); Assert.Equal("void C3.I1.remove_M01(System.Action value)", c3M01Remove.ToTestDisplayString()); Assert.Same(m01.RemoveMethod, c3M01Remove.ExplicitInterfaceImplementations.Single()); } else { Assert.Same(c2M01, c3.FindImplementationForInterfaceMember(m01)); Assert.Same(c2M01Add, c3.FindImplementationForInterfaceMember(m01.AddMethod)); Assert.Same(c2M01Remove, c3.FindImplementationForInterfaceMember(m01.RemoveMethod)); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_19(bool genericFirst) { // An "ambiguity" in implicit/explicit implementation declared in generic base class. var generic = @" public static event System.Action<T> M01 { add{} remove{} } "; var nonGeneric = @" static event System.Action<int> I1.M01 { add{} remove{} } "; var source1 = @" public interface I1 { abstract static event System.Action<int> M01; } public class C1<T> : I1 { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<EventSymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1 { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action<System.Int32> C1<T>.I1.M01", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Same(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticEvent_20(bool genericFirst) { // Same as ImplementAbstractStaticEvent_19 only interface is generic too. var generic = @" static event System.Action<T> I1<T>.M01 { add{} remove{} } "; var nonGeneric = @" public static event System.Action<int> M01 { add{} remove{} } "; var source1 = @" public interface I1<T> { abstract static event System.Action<T> M01; } public class C1<T> : I1<T> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().OfType<EventSymbol>().Where(m => m.Name.Contains("M01")).Count()); compilation1.VerifyDiagnostics(); var source2 = @" public class C2 : C1<int>, I1<int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers().OfType<EventSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (EventSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("event System.Action<T> C1<T>.I1<T>.M01", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } private static string ConversionOperatorName(string op) => op switch { "implicit" => WellKnownMemberNames.ImplicitConversionName, "explicit" => WellKnownMemberNames.ExplicitConversionName, _ => throw TestExceptionUtilities.UnexpectedValue(op) }; [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; string opName = ConversionOperatorName(op); var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } " + typeKeyword + @" C1 : I1<C1> {} " + typeKeyword + @" C2 : I1<C2> { public " + op + @" operator int(C2 x) => throw null; } " + typeKeyword + @" C3 : I1<C3> { static " + op + @" operator int(C3 x) => throw null; } " + typeKeyword + @" C4 : I1<C4> { " + op + @" I1<C4>.operator int(C4 x) => throw null; } " + typeKeyword + @" C5 : I1<C5> { public static " + op + @" operator long(C5 x) => throw null; } " + typeKeyword + @" C6 : I1<C6> { static " + op + @" I1<C6>.operator long(C6 x) => throw null; } " + typeKeyword + @" C7 : I1<C7> { public static int " + opName + @"(C7 x) => throw null; } " + typeKeyword + @" C8 : I1<C8> { static int I1<C8>." + opName + @"(C8 x) => throw null; } public interface I2<T> where T : I2<T> { abstract static int " + opName + @"(T x); } " + typeKeyword + @" C9 : I2<C9> { public static " + op + @" operator int(C9 x) => throw null; } " + typeKeyword + @" C10 : I2<C10> { static " + op + @" I2<C10>.operator int(C10 x) => throw null; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (8,10): error CS0535: 'C1' does not implement interface member 'I1<C1>.explicit operator int(C1)' // C1 : I1<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C1>").WithArguments("C1", "I1<C1>." + op + " operator int(C1)").WithLocation(8, 10), // (12,10): error CS8928: 'C2' does not implement static interface member 'I1<C2>.explicit operator int(C2)'. 'C2.explicit operator int(C2)' cannot implement the interface member because it is not static. // C2 : I1<C2> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, "I1<C2>").WithArguments("C2", "I1<C2>." + op + " operator int(C2)", "C2." + op + " operator int(C2)").WithLocation(12, 10), // (14,30): error CS0558: User-defined operator 'C2.explicit operator int(C2)' must be declared static and public // public explicit operator int(C2 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("C2." + op + " operator int(C2)").WithLocation(14, 30), // (18,10): error CS0737: 'C3' does not implement interface member 'I1<C3>.explicit operator int(C3)'. 'C3.explicit operator int(C3)' cannot implement an interface member because it is not public. // C3 : I1<C3> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "I1<C3>").WithArguments("C3", "I1<C3>." + op + " operator int(C3)", "C3." + op + " operator int(C3)").WithLocation(18, 10), // (20,30): error CS0558: User-defined operator 'C3.explicit operator int(C3)' must be declared static and public // static explicit operator int(C3 x) => throw null; Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("C3." + op + " operator int(C3)").WithLocation(20, 30), // (24,10): error CS0535: 'C4' does not implement interface member 'I1<C4>.explicit operator int(C4)' // C4 : I1<C4> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C4>").WithArguments("C4", "I1<C4>." + op + " operator int(C4)").WithLocation(24, 10), // (26,30): error CS8930: Explicit implementation of a user-defined operator 'C4.explicit operator int(C4)' must be declared static // explicit I1<C4>.operator int(C4 x) => throw null; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, "int").WithArguments("C4." + op + " operator int(C4)").WithLocation(26, 30), // (26,30): error CS0539: 'C4.explicit operator int(C4)' in explicit interface declaration is not found among members of the interface that can be implemented // explicit I1<C4>.operator int(C4 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C4." + op + " operator int(C4)").WithLocation(26, 30), // (30,10): error CS0738: 'C5' does not implement interface member 'I1<C5>.explicit operator int(C5)'. 'C5.explicit operator long(C5)' cannot implement 'I1<C5>.explicit operator int(C5)' because it does not have the matching return type of 'int'. // C5 : I1<C5> Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "I1<C5>").WithArguments("C5", "I1<C5>." + op + " operator int(C5)", "C5." + op + " operator long(C5)", "int").WithLocation(30, 10), // (36,10): error CS0535: 'C6' does not implement interface member 'I1<C6>.explicit operator int(C6)' // C6 : I1<C6> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C6>").WithArguments("C6", "I1<C6>." + op + " operator int(C6)").WithLocation(36, 10), // (38,37): error CS0539: 'C6.explicit operator long(C6)' in explicit interface declaration is not found among members of the interface that can be implemented // static explicit I1<C6>.operator long(C6 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "long").WithArguments("C6." + op + " operator long(C6)").WithLocation(38, 37), // (42,10): error CS0535: 'C7' does not implement interface member 'I1<C7>.explicit operator int(C7)' // C7 : I1<C7> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C7>").WithArguments("C7", "I1<C7>." + op + " operator int(C7)").WithLocation(42, 10), // (48,10): error CS0535: 'C8' does not implement interface member 'I1<C8>.explicit operator int(C8)' // C8 : I1<C8> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<C8>").WithArguments("C8", "I1<C8>." + op + " operator int(C8)").WithLocation(48, 10), // (50,23): error CS0539: 'C8.op_Explicit(C8)' in explicit interface declaration is not found among members of the interface that can be implemented // static int I1<C8>.op_Explicit(C8 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, opName).WithArguments("C8." + opName + "(C8)").WithLocation(50, 23), // (59,10): error CS0535: 'C9' does not implement interface member 'I2<C9>.op_Explicit(C9)' // C9 : I2<C9> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C9>").WithArguments("C9", "I2<C9>." + opName + "(C9)").WithLocation(59, 10), // (65,11): error CS0535: 'C10' does not implement interface member 'I2<C10>.op_Explicit(C10)' // C10 : I2<C10> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C10>").WithArguments("C10", "I2<C10>." + opName + "(C10)").WithLocation(65, 11), // (67,38): error CS0539: 'C10.explicit operator int(C10)' in explicit interface declaration is not found among members of the interface that can be implemented // static explicit I2<C10>.operator int(C10 x) => throw null; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C10." + op + " operator int(C10)").WithLocation(67, 38) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_03([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } interface I2<T> : I1<T> where T : I1<T> {} interface I3<T> : I1<T> where T : I1<T> { " + op + @" operator int(T x) => default; } interface I4<T> : I1<T> where T : I1<T> { static " + op + @" operator int(T x) => default; } interface I5<T> : I1<T> where T : I1<T> { " + op + @" I1<T>.operator int(T x) => default; } interface I6<T> : I1<T> where T : I1<T> { static " + op + @" I1<T>.operator int(T x) => default; } interface I7<T> : I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public interface I11<T> where T : I11<T> { abstract static " + op + @" operator int(T x); } interface I8<T> : I11<T> where T : I8<T> { " + op + @" operator int(T x) => default; } interface I9<T> : I11<T> where T : I9<T> { static " + op + @" operator int(T x) => default; } interface I10<T> : I11<T> where T : I10<T> { abstract static " + op + @" operator int(T x); } interface I12<T> : I11<T> where T : I12<T> { static " + op + @" I11<T>.operator int(T x) => default; } interface I13<T> : I11<T> where T : I13<T> { abstract static " + op + @" I11<T>.operator int(T x); } interface I14<T> : I1<T> where T : I1<T> { abstract static " + op + @" I1<T>.operator int(T x); } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,23): error CS0556: User-defined conversion must convert to or from the enclosing type // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(12, 23), // (12,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(12, 23), // (17,30): error CS0556: User-defined conversion must convert to or from the enclosing type // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(17, 30), // (17,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(17, 30), // (22,29): error CS8930: Explicit implementation of a user-defined operator 'I5<T>.implicit operator int(T)' must be declared static // implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_ExplicitImplementationOfOperatorsMustBeStatic, "int").WithArguments("I5<T>." + op + " operator int(T)").WithLocation(22, 29), // (22,29): error CS0539: 'I5<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I5<T>." + op + " operator int(T)").WithLocation(22, 29), // (27,36): error CS0539: 'I6<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I1<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I6<T>." + op + " operator int(T)").WithLocation(27, 36), // (32,39): error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_AbstractConversionNotInvolvingContainedType, "int").WithLocation(32, 39), // (42,23): error CS0556: User-defined conversion must convert to or from the enclosing type // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(42, 23), // (42,23): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(42, 23), // (47,30): error CS0556: User-defined conversion must convert to or from the enclosing type // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int").WithLocation(47, 30), // (47,30): error CS0567: Conversion, equality, or inequality operators declared in interfaces must be abstract // static implicit operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, "int").WithLocation(47, 30), // (57,37): error CS0539: 'I12<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I11<T>.operator int(T x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I12<T>." + op + " operator int(T)").WithLocation(57, 37), // (62,46): error CS0106: The modifier 'abstract' is not valid for this item // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(62, 46), // (62,46): error CS0501: 'I13<T>.implicit operator int(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "int").WithArguments("I13<T>." + op + " operator int(T)").WithLocation(62, 46), // (62,46): error CS0539: 'I13<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static implicit I11<T>.operator int(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I13<T>." + op + " operator int(T)").WithLocation(62, 46), // (67,45): error CS0106: The modifier 'abstract' is not valid for this item // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(67, 45), // (67,45): error CS0501: 'I14<T>.implicit operator int(T)' must declare a body because it is not marked abstract, extern, or partial // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "int").WithArguments("I14<T>." + op + " operator int(T)").WithLocation(67, 45), // (67,45): error CS0539: 'I14<T>.implicit operator int(T)' in explicit interface declaration is not found among members of the interface that can be implemented // abstract static implicit I1<T>.operator int(T x); Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("I14<T>." + op + " operator int(T)").WithLocation(67, 45) ); var m01 = compilation1.GlobalNamespace.GetTypeMember("I1").GetMembers().OfType<MethodSymbol>().Single(); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I2").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I3").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I4").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I5").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I6").FindImplementationForInterfaceMember(m01)); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I7").FindImplementationForInterfaceMember(m01)); var i8 = compilation1.GlobalNamespace.GetTypeMember("I8"); Assert.Null(i8.FindImplementationForInterfaceMember(i8.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i9 = compilation1.GlobalNamespace.GetTypeMember("I9"); Assert.Null(i9.FindImplementationForInterfaceMember(i9.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i10 = compilation1.GlobalNamespace.GetTypeMember("I10"); Assert.Null(i10.FindImplementationForInterfaceMember(i10.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i12 = compilation1.GlobalNamespace.GetTypeMember("I12"); Assert.Null(i12.FindImplementationForInterfaceMember(i12.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); var i13 = compilation1.GlobalNamespace.GetTypeMember("I13"); Assert.Null(i13.FindImplementationForInterfaceMember(i13.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single())); Assert.Null(compilation1.GlobalNamespace.GetTypeMember("I14").FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_04([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I2<T> where T : I2<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1 : I2<Test1> { static " + op + @" I2<Test1>.operator int(Test1 x) => default; } " + typeKeyword + @" Test2: I2<Test2> { public static " + op + @" operator int(Test2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,21): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static explicit I2<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I2<Test1>.").WithArguments("static abstract members in interfaces").WithLocation(4, 21) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (4,21): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // static explicit I2<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I2<Test1>.").WithArguments("static abstract members in interfaces").WithLocation(4, 21), // (14,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(14, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_05([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1: I1<Test1> { public static " + op + @" operator int(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.explicit operator int(Test1)' cannot implement interface member 'I1<Test1>.explicit operator int(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1." + op + " operator int(Test1)", "I1<Test1>." + op + " operator int(Test1)", "Test1").WithLocation(2, 12) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (2,12): error CS8929: 'Test1.explicit operator int(Test1)' cannot implement interface member 'I1<Test1>.explicit operator int(Test1)' in type 'Test1' because the target runtime doesn't support static abstract members in interfaces. // Test1: I1<Test1> Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1<Test1>").WithArguments("Test1." + op + " operator int(Test1)", "I1<Test1>." + op + " operator int(Test1)", "Test1").WithLocation(2, 12), // (9,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(9, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_06([CombinatorialValues("implicit", "explicit")] string op, bool structure) { var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = typeKeyword + @" Test1 : I1<Test1> { static " + op + @" I1<Test1>.operator int(Test1 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (4,40): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static explicit I1<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 40) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (4,40): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static explicit I1<Test1>.operator int(Test1 x) => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(4, 40), // (9,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(9, 39) ); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_07([CombinatorialValues("implicit", "explicit")] string op, bool structure) { // Basic implicit implementation scenario, MethodImpl is emitted var typeKeyword = structure ? "struct" : "class"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); abstract static " + op + @" operator long(T x); } " + typeKeyword + @" C : I1<C> { public static " + op + @" operator long(C x) => default; public static " + op + @" operator int(C x) => default; } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); var i1 = c.Interfaces().Single(); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = i1.GetMembers().OfType<MethodSymbol>().First(); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.True(cM01.HasSpecialName); Assert.Equal("System.Int32 C." + opName + "(C x)", cM01.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM01.ExplicitInterfaceImplementations); } var m02 = i1.GetMembers().OfType<MethodSymbol>().ElementAt(1); var cM02 = (MethodSymbol)c.FindImplementationForInterfaceMember(m02); Assert.True(cM02.IsStatic); Assert.False(cM02.IsAbstract); Assert.False(cM02.IsVirtual); Assert.False(cM02.IsMetadataVirtual()); Assert.False(cM02.IsMetadataFinal); Assert.False(cM02.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, cM02.MethodKind); Assert.False(cM02.HasRuntimeSpecialName); Assert.True(cM02.HasSpecialName); Assert.Equal("System.Int64 C." + opName + "(C x)", cM02.ToTestDisplayString()); if (module is PEModuleSymbol) { Assert.Equal(m02, cM02.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(cM02.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_08([CombinatorialValues("implicit", "explicit")] string op, bool structure) { // Basic explicit implementation scenario var typeKeyword = structure ? "struct" : "class"; var source1 = @" interface I1<T> where T : I1<T> { abstract static " + op + @" operator C(T x); abstract static " + op + @" operator int(T x); } " + typeKeyword + @" C : I1<C> { static " + op + @" I1<C>.operator int(C x) => int.MaxValue; static " + op + @" I1<C>.operator C(C x) => default; } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal("default", node.ToString()); Assert.Equal("C", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()); var declaredSymbol = model.GetDeclaredSymbol(node.FirstAncestorOrSelf<ConversionOperatorDeclarationSyntax>()); Assert.Equal("C C.I1<C>." + opName + "(C x)", declaredSymbol.ToTestDisplayString()); Assert.DoesNotContain(opName, declaredSymbol.ContainingType.MemberNames); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped, emitOptions: EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c = module.GlobalNamespace.GetTypeMember("C"); Assert.Equal(2, c.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Count()); var m01 = c.Interfaces().Single().GetMembers().OfType<MethodSymbol>().First(); var cM01 = (MethodSymbol)c.FindImplementationForInterfaceMember(m01); Assert.True(cM01.IsStatic); Assert.False(cM01.IsAbstract); Assert.False(cM01.IsVirtual); Assert.False(cM01.IsMetadataVirtual()); Assert.False(cM01.IsMetadataFinal); Assert.False(cM01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM01.MethodKind); Assert.False(cM01.HasRuntimeSpecialName); Assert.False(cM01.HasSpecialName); Assert.Equal("C C.I1<C>." + opName + "(C x)", cM01.ToTestDisplayString()); Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); var m02 = c.Interfaces().Single().GetMembers().OfType<MethodSymbol>().ElementAt(1); var cM02 = (MethodSymbol)c.FindImplementationForInterfaceMember(m02); Assert.True(cM02.IsStatic); Assert.False(cM02.IsAbstract); Assert.False(cM02.IsVirtual); Assert.False(cM02.IsMetadataVirtual()); Assert.False(cM02.IsMetadataFinal); Assert.False(cM02.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, cM02.MethodKind); Assert.False(cM02.HasRuntimeSpecialName); Assert.False(cM02.HasSpecialName); Assert.Equal("System.Int32 C.I1<C>." + opName + "(C x)", cM02.ToTestDisplayString()); Assert.Equal(m02, cM02.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_09([CombinatorialValues("implicit", "explicit")] string op) { // Explicit implementation from base is treated as an implementation var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = ConversionOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var cM01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2.I1<C2>." + opName + "(C2 x)", cM01.ToTestDisplayString()); Assert.Equal(m01, cM01.ExplicitInterfaceImplementations.Single()); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_10([CombinatorialValues("implicit", "explicit")] string op) { // Implicit implementation is considered only for types implementing interface in source. // In metadata, only explicit implementations are considered var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 " + opName + @" ( !T x ) cil managed { } } .class public auto ansi beforefieldinit C1 extends System.Object implements class I1`1<class C1> { .method private hidebysig static int32 'I1<C1>." + opName + @"' ( class C1 x ) cil managed { .override method int32 class I1`1<class C1>::" + opName + @"(!0) IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig static specialname int32 " + opName + @" ( class C1 x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2053 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: nop IL_0007: ret } } .class public auto ansi beforefieldinit C2 extends C1 implements class I1`1<class C1> { .method public hidebysig static specialname int32 " + opName + @" ( class C1 x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: ret } } "; var source1 = @" public class C3 : C2 { } public class C4 : C1, I1<C1> { } public class C5 : C2, I1<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Equal(MethodKind.Conversion, c1.GetMember<MethodSymbol>(opName).MethodKind); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); var c2 = compilation1.GlobalNamespace.GetTypeMember("C2"); Assert.Same(c1M01, c2.FindImplementationForInterfaceMember(m01)); var c3 = compilation1.GlobalNamespace.GetTypeMember("C3"); Assert.Same(c1M01, c3.FindImplementationForInterfaceMember(m01)); var c4 = compilation1.GlobalNamespace.GetTypeMember("C4"); Assert.Same(c1M01, c4.FindImplementationForInterfaceMember(m01)); var c5 = compilation1.GlobalNamespace.GetTypeMember("C5"); var c2M01 = (MethodSymbol)c5.FindImplementationForInterfaceMember(m01); Assert.Equal("System.Int32 C2." + opName + "(C1 x)", c2M01.ToTestDisplayString()); Assert.Equal(MethodKind.Conversion, c2M01.MethodKind); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_11([CombinatorialValues("implicit", "explicit")] string op) { // Ignore invalid metadata (non-abstract static virtual method). var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname virtual static int32 " + opName + @" ( !T x ) cil managed { IL_0000: ldc.i4.0 IL_0001: ret } } "; var source1 = @" public class C1 : I1<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i1 = c1.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i1.FindImplementationForInterfaceMember(m01)); compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics(); var source2 = @" public class C1 : I1<C1> { static " + op + @" I1<C1>.operator int(C1 x) => default; } "; var compilation2 = CreateCompilationWithIL(source2, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyEmitDiagnostics( // (4,37): error CS0539: 'C1.implicit operator int(C1)' in explicit interface declaration is not found among members of the interface that can be implemented // static implicit I1<C1>.operator int(C1 x) => default; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "int").WithArguments("C1." + op + " operator int(C1)").WithLocation(4, 37) ); c1 = compilation2.GlobalNamespace.GetTypeMember("C1"); m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal("System.Int32 I1<C1>." + opName + "(C1 x)", m01.ToTestDisplayString()); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_12([CombinatorialValues("implicit", "explicit")] string op) { // Ignore invalid metadata (default interface implementation for a static method) var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 " + opName + @" ( !T x ) cil managed { } } .class interface public auto ansi abstract I2`1<(class I1`1<!T>) T> implements class I1`1<!T> { .method private hidebysig static int32 'I1<!T>." + opName + @"' ( !T x ) cil managed { .override method int32 class I1`1<!T>::" + opName + @"(!0) IL_0000: ldc.i4.0 IL_0001: ret } } "; var source1 = @" public class C1 : I2<C1> { } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyEmitDiagnostics( // (2,19): error CS0535: 'C1' does not implement interface member 'I1<C1>.explicit operator int(C1)' // public class C1 : I2<C1> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I2<C1>").WithArguments("C1", "I1<C1>." + op + " operator int(C1)").WithLocation(2, 19) ); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); var i2 = c1.Interfaces().Single(); var i1 = i2.Interfaces().Single(); var m01 = i1.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(MethodKind.Conversion, m01.MethodKind); Assert.Null(c1.FindImplementationForInterfaceMember(m01)); Assert.Null(i2.FindImplementationForInterfaceMember(m01)); var i2M01 = i2.GetMembers().OfType<MethodSymbol>().Single(); Assert.Equal(m01, i2M01.ExplicitInterfaceImplementations.Single()); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_13([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method is added for an implicit implementation declared in base class. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static " + op + @" operator C1<T>(T x); } public partial class C1<T> { public static " + op + @" operator C1<T>(T x) => default; } public class C2 : C1<C2>, I1<C2> { } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var i1 = c2.Interfaces().Single(); var m01 = i1.GetMembers(opName).OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.False(c2M01.HasSpecialName); Assert.Equal("C1<C2> C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); var c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.False(c1M01.HasRuntimeSpecialName); Assert.True(c1M01.HasSpecialName); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Conversion, c2M01.MethodKind); Assert.False(c2M01.HasRuntimeSpecialName); Assert.True(c2M01.HasSpecialName); Assert.Equal("C1<C2> C1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Empty(c2M01.ExplicitInterfaceImplementations); } } verifier.VerifyIL("C2.I1<C2>." + opName + "(C2)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""C1<C2> C1<C2>." + opName + @"(C2)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_14([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method is added for an implicit implementation with modopt mismatch. var opName = ConversionOperatorName(op); var ilSource = @" .class interface public auto ansi abstract I1`1<(class I1`1<!T>) T> { // Methods .method public hidebysig specialname abstract virtual static int32 modopt(I1`1) " + opName + @" ( !T x ) cil managed { } } "; var source1 = @" class C1 : I1<C1> { public static " + op + @" operator int(C1 x) => default; } class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var c1 = module.GlobalNamespace.GetTypeMember("C1"); var m01 = c1.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c1M01 = (MethodSymbol)c1.FindImplementationForInterfaceMember(m01); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); if (module is PEModuleSymbol) { Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c1M01.MethodKind); Assert.Equal("System.Int32 modopt(I1<>) C1.I1<C1>." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); c1M01 = module.GlobalNamespace.GetMember<MethodSymbol>("C1." + opName); Assert.Equal("System.Int32 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } else { Assert.Equal(MethodKind.Conversion, c1M01.MethodKind); Assert.Equal("System.Int32 C1." + opName + "(C1 x)", c1M01.ToTestDisplayString()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); } var c2 = module.GlobalNamespace.GetTypeMember("C2"); m01 = c2.Interfaces().Single().GetMembers().OfType<MethodSymbol>().Single(); var c2M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.True(c2M01.IsStatic); Assert.False(c2M01.IsAbstract); Assert.False(c2M01.IsVirtual); Assert.False(c2M01.IsMetadataVirtual()); Assert.False(c2M01.IsMetadataFinal); Assert.False(c2M01.IsMetadataNewSlot()); Assert.Equal(MethodKind.ExplicitInterfaceImplementation, c2M01.MethodKind); Assert.Equal("System.Int32 modopt(I1<>) C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c2M01, c2.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single()); } verifier.VerifyIL("C1.I1<C1>." + opName + "(C1)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int C1." + opName + @"(C1)"" IL_0006: ret } "); } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_15([CombinatorialValues("implicit", "explicit")] string op) { // A forwarding method isn't created if base class implements interface exactly the same way. var source1 = @" public partial interface I1<T> where T : I1<T> { abstract static " + op + @" operator C1<T>(T x); abstract static " + op + @" operator T(int x); } public partial class C1<T> { public static " + op + @" operator C1<T>(T x) => default; } public class C2 : C1<C2>, I1<C2> { static " + op + @" I1<C2>.operator C2(int x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics(); var source2 = @" public class C3 : C2, I1<C2> { } "; var opName = ConversionOperatorName(op); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.RegularPreview, TestOptions.Regular9 }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c3 = module.GlobalNamespace.GetTypeMember("C3"); Assert.Empty(c3.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor())); var m01 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().First(); var c1M01 = c3.BaseType().BaseType().GetMember<MethodSymbol>(opName); Assert.Equal("C1<C2> C1<C2>." + opName + "(C2 x)", c1M01.ToTestDisplayString()); Assert.True(c1M01.IsStatic); Assert.False(c1M01.IsAbstract); Assert.False(c1M01.IsVirtual); Assert.False(c1M01.IsMetadataVirtual()); Assert.False(c1M01.IsMetadataFinal); Assert.False(c1M01.IsMetadataNewSlot()); Assert.Empty(c1M01.ExplicitInterfaceImplementations); if (c1M01.ContainingModule is PEModuleSymbol) { var c2M01 = (MethodSymbol)c3.FindImplementationForInterfaceMember(m01); Assert.Equal("C1<C2> C2.I1<C2>." + opName + "(C2 x)", c2M01.ToTestDisplayString()); Assert.Equal(m01, c2M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Equal(c1M01, c3.FindImplementationForInterfaceMember(m01)); } var m02 = c3.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().ElementAt(1); var c2M02 = c3.BaseType().GetMembers("I1<C2>." + opName).OfType<MethodSymbol>().First(); Assert.Equal("C2 C2.I1<C2>." + opName + "(System.Int32 x)", c2M02.ToTestDisplayString()); Assert.Same(c2M02, c3.FindImplementationForInterfaceMember(m02)); } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_18([CombinatorialValues("implicit", "explicit")] string op, bool genericFirst) { // An "ambiguity" in implicit implementation declared in generic base class plus interface is generic too. var generic = @" public static " + op + @" operator U(C1<T, U> x) => default; "; var nonGeneric = @" public static " + op + @" operator int(C1<T, U> x) => default; "; var source1 = @" public interface I1<T, U> where T : I1<T, U> { abstract static " + op + @" operator U(T x); } public class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>." + opName + "(C1<T, U> x)", c1M01.OriginalDefinition.ToTestDisplayString()); var baseI1M01 = c2.BaseType().FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>." + opName + "(C1<T, U> x)", baseI1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(c1M01, baseI1M01); if (c1M01.OriginalDefinition.ContainingModule is PEModuleSymbol) { Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); } else { Assert.Empty(c1M01.ExplicitInterfaceImplementations); } } } [Theory] [CombinatorialData] public void ImplementAbstractStaticConversionOperator_20([CombinatorialValues("implicit", "explicit")] string op, bool genericFirst) { // Same as ImplementAbstractStaticConversionOperator_18 only implementation is explicit in source. var generic = @" static " + op + @" I1<C1<T, U>, U>.operator U(C1<T, U> x) => default; "; var nonGeneric = @" public static " + op + @" operator int(C1<T, U> x) => default; "; var source1 = @" public interface I1<T, U> where T : I1<T, U> { abstract static " + op + @" operator U(T x); } public class C1<T, U> : I1<C1<T, U>, U> { " + (genericFirst ? generic + nonGeneric : nonGeneric + generic) + @" } "; var opName = ConversionOperatorName(op); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateCompilation("", targetFramework: TargetFramework.NetCoreApp).ToMetadataReference() }); compilation1.VerifyDiagnostics(); Assert.Equal(2, compilation1.GlobalNamespace.GetTypeMember("C1").GetMembers().Where(m => m.Name.Contains(opName)).Count()); var source2 = @" public class C2 : C1<int, int>, I1<C1<int, int>, int> { } "; foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var parseOptions in new[] { TestOptions.Regular9, TestOptions.RegularPreview }) { var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: parseOptions, targetFramework: TargetFramework.NetCoreApp, references: new[] { reference }); CompileAndVerify(compilation2, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); } } void validate(ModuleSymbol module) { var c2 = module.GlobalNamespace.GetTypeMember("C2"); var m01 = c2.Interfaces().Single().GetMembers(opName).OfType<MethodSymbol>().Single(); Assert.True(m01.ContainingModule is RetargetingModuleSymbol or PEModuleSymbol); var c1M01 = (MethodSymbol)c2.FindImplementationForInterfaceMember(m01); Assert.Equal("U C1<T, U>.I1<C1<T, U>, U>." + opName + "(C1<T, U> x)", c1M01.OriginalDefinition.ToTestDisplayString()); Assert.Equal(m01, c1M01.ExplicitInterfaceImplementations.Single()); Assert.Same(c1M01, c2.BaseType().FindImplementationForInterfaceMember(m01)); } } [Theory] [CombinatorialData] public void ExplicitImplementationModifiersConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class C1 : I1<C1> { static " + op + @" I1<C1>.operator int(C1 x) => default; } class C2 : I1<C2> { private static " + op + @" I1<C2>.operator int(C2 x) => default; } class C3 : I1<C3> { protected static " + op + @" I1<C3>.operator int(C3 x) => default; } class C4 : I1<C4> { internal static " + op + @" I1<C4>.operator int(C4 x) => default; } class C5 : I1<C5> { protected internal static " + op + @" I1<C5>.operator int(C5 x) => default; } class C6 : I1<C6> { private protected static " + op + @" I1<C6>.operator int(C6 x) => default; } class C7 : I1<C7> { public static " + op + @" I1<C7>.operator int(C7 x) => default; } class C9 : I1<C9> { async static " + op + @" I1<C9>.operator int(C9 x) => default; } class C10 : I1<C10> { unsafe static " + op + @" I1<C10>.operator int(C10 x) => default; } class C11 : I1<C11> { static readonly " + op + @" I1<C11>.operator int(C11 x) => default; } class C12 : I1<C12> { extern static " + op + @" I1<C12>.operator int(C12 x); } class C13 : I1<C13> { abstract static " + op + @" I1<C13>.operator int(C13 x) => default; } class C14 : I1<C14> { virtual static " + op + @" I1<C14>.operator int(C14 x) => default; } class C15 : I1<C15> { sealed static " + op + @" I1<C15>.operator int(C15 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var c1 = compilation1.GlobalNamespace.GetTypeMember("C1"); Assert.Equal(Accessibility.Private, c1.GetMembers().OfType<MethodSymbol>().Where(m => !m.IsConstructor()).Single().DeclaredAccessibility); compilation1.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.WRN_ExternMethodNoImplementation).Verify( // (16,45): error CS0106: The modifier 'private' is not valid for this item // private static explicit I1<C2>.operator int(C2 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("private").WithLocation(16, 45), // (22,47): error CS0106: The modifier 'protected' is not valid for this item // protected static explicit I1<C3>.operator int(C3 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("protected").WithLocation(22, 47), // (28,46): error CS0106: The modifier 'internal' is not valid for this item // internal static explicit I1<C4>.operator int(C4 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("internal").WithLocation(28, 46), // (34,56): error CS0106: The modifier 'protected internal' is not valid for this item // protected internal static explicit I1<C5>.operator int(C5 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("protected internal").WithLocation(34, 56), // (40,55): error CS0106: The modifier 'private protected' is not valid for this item // private protected static explicit I1<C6>.operator int(C6 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("private protected").WithLocation(40, 55), // (46,44): error CS0106: The modifier 'public' is not valid for this item // public static explicit I1<C7>.operator int(C7 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("public").WithLocation(46, 44), // (52,43): error CS0106: The modifier 'async' is not valid for this item // async static explicit I1<C9>.operator int(C9 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("async").WithLocation(52, 43), // (64,47): error CS0106: The modifier 'readonly' is not valid for this item // static readonly explicit I1<C11>.operator int(C11 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("readonly").WithLocation(64, 47), // (76,47): error CS0106: The modifier 'abstract' is not valid for this item // abstract static explicit I1<C13>.operator int(C13 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("abstract").WithLocation(76, 47), // (82,46): error CS0106: The modifier 'virtual' is not valid for this item // virtual static explicit I1<C14>.operator int(C14 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("virtual").WithLocation(82, 46), // (88,45): error CS0106: The modifier 'sealed' is not valid for this item // sealed static explicit I1<C15>.operator int(C15 x) => default; Diagnostic(ErrorCode.ERR_BadMemberFlag, "int").WithArguments("sealed").WithLocation(88, 45) ); } [Theory] [CombinatorialData] public void ExplicitInterfaceSpecifierErrorsConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { var source1 = @" public interface I1<T> where T : struct, I1<T> { abstract static " + op + @" operator int(T x); } class C1 { static " + op + @" I1<int>.operator int(int x) => default; } class C2 : I1<C2> { static " + op + @" I1<C2>.operator int(C2 x) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (9,21): error CS0540: 'C1.I1<int>.implicit operator int(int)': containing type does not implement interface 'I1<int>' // static implicit I1<int>.operator int(int x) => default; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<int>").WithArguments("C1.I1<int>." + op + " operator int(int)", "I1<int>").WithLocation(9, 21), // (9,21): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion from 'int' to 'I1<int>'. // static implicit I1<int>.operator int(int x) => default; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "I1<int>").WithArguments("I1<T>", "I1<int>", "T", "int").WithLocation(9, 21), // (12,7): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // class C2 : I1<C2> Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "C2").WithLocation(12, 7), // (14,21): error CS0453: The type 'C2' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'I1<T>' // static implicit I1<C2>.operator int(C2 x) => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "I1<C2>").WithArguments("I1<T>", "T", "C2").WithLocation(14, 21) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_01([CombinatorialValues("implicit", "explicit")] string op) { string cast = (op == "explicit" ? "(int)" : ""); var source1 = @" interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); static int M02(I1<T> x) { return " + cast + @"x; } int M03(I1<T> y) { return " + cast + @"y; } } class Test<T> where T : I1<T> { static int MT1(I1<T> a) { return " + cast + @"a; } static void MT2() { _ = (System.Linq.Expressions.Expression<System.Func<T, int>>)((T b) => " + cast + @"b); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (8,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)x; Diagnostic(error, cast + "x").WithArguments("I1<T>", "int").WithLocation(8, 16), // (13,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)y; Diagnostic(error, cast + "y").WithArguments("I1<T>", "int").WithLocation(13, 16), // (21,16): error CS0030: Cannot convert type 'I1<T>' to 'int' // return (int)a; Diagnostic(error, cast + "a").WithArguments("I1<T>", "int").WithLocation(21, 16), // (26,80): error CS8927: An expression tree may not contain an access of static abstract interface member // _ = (System.Linq.Expressions.Expression<System.Func<T, int>>)((T b) => (int)b); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, cast + "b").WithLocation(26, 80) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_01([CombinatorialValues("==", "!=")] string op) { var source1 = @" interface I1 { abstract static implicit operator bool(I1 x); static void M02((int, C<I1>) x) { _ = x " + op + @" x; } void M03((int, C<I1>) y) { _ = y " + op + @" y; } } class Test { static void MT1((int, C<I1>) a) { _ = a " + op + @" a; } static void MT2<T>() where T : I1 { _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b " + op + @" b).ToString()); } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (4,39): error CS0552: 'I1.implicit operator bool(I1)': user-defined conversions to or from an interface are not allowed // abstract static implicit operator bool(I1 x); Diagnostic(ErrorCode.ERR_ConversionWithInterface, "bool").WithArguments("I1.implicit operator bool(I1)").WithLocation(4, 39), // (9,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = x == x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x " + op + " x").WithArguments("I1", "bool").WithLocation(9, 13), // (14,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = y == y; Diagnostic(ErrorCode.ERR_NoImplicitConv, "y " + op + " y").WithArguments("I1", "bool").WithLocation(14, 13), // (22,13): error CS0029: Cannot implicitly convert type 'I1' to 'bool' // _ = a == a; Diagnostic(ErrorCode.ERR_NoImplicitConv, "a " + op + " a").WithArguments("I1", "bool").WithLocation(22, 13), // (27,98): error CS8382: An expression tree may not contain a tuple == or != operator // _ = (System.Linq.Expressions.Expression<System.Action<(int, C<T>)>>)(((int, C<T>) b) => (b == b).ToString()); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "b " + op + " b").WithLocation(27, 98) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_03([CombinatorialValues("implicit", "explicit")] string op) { string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class Test { static int M02<T, U>(T x) where T : U where U : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int? M03<T, U>(T y) where T : U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"y; } static int? M04<T, U>(T? y) where T : struct, U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"y; } static int? M05<T, U>() where T : struct, U where U : I1<T> { return " + (needCast ? "(int?)" : "") + @"(T?)new T(); } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 23 (0x17) .maxstack 1 .locals init (int? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: newobj ""int?..ctor(int)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (T? V_0, int? V_1, int? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool T?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""int?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly T T?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""int I1<T>." + metadataName + @"(T)"" IL_0029: newobj ""int?..ctor(int)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 27 (0x1b) .maxstack 1 .locals init (int? V_0) IL_0000: nop IL_0001: call ""T System.Activator.CreateInstance<T>()"" IL_0006: constrained. ""T"" IL_000c: call ""int I1<T>." + metadataName + @"(T)"" IL_0011: newobj ""int?..ctor(int)"" IL_0016: stloc.0 IL_0017: br.s IL_0019 IL_0019: ldloc.0 IL_001a: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""int I1<T>." + metadataName + @"(T)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""int I1<T>." + metadataName + @"(T)"" IL_000c: newobj ""int?..ctor(int)"" IL_0011: ret } "); verifier.VerifyIL("Test.M04<T, U>(T?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (T? V_0, int? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool T?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""int?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly T T?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""int I1<T>." + metadataName + @"(T)"" IL_0027: newobj ""int?..ctor(int)"" IL_002c: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 22 (0x16) .maxstack 1 IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: constrained. ""T"" IL_000b: call ""int I1<T>." + metadataName + @"(T)"" IL_0010: newobj ""int?..ctor(int)"" IL_0015: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().First(); Assert.Equal("return " + (needCast ? "(int)" : "") + @"x;", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return " + (needCast ? "(int)" : "") + @"x;') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 I1<T>." + metadataName + @"(T x)) (OperationKind.Conversion, Type: System.Int32" + (needCast ? "" : ", IsImplicit") + @") (Syntax: '" + (needCast ? "(int)" : "") + @"x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 I1<T>." + metadataName + @"(T x)) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_03([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool (T x); } class Test { static void M02<T, U>((int, C<T>) x) where T : U where U : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_Implicit(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.0 IL_0032: pop IL_0033: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.0 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0011: bne.un.s IL_0031 IL_0013: ldloc.0 IL_0014: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0019: ldloc.1 IL_001a: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001f: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0024: constrained. ""T"" IL_002a: call ""bool I1<T>.op_Implicit(T)"" IL_002f: br.s IL_0032 IL_0031: ldc.i4.1 IL_0032: pop IL_0033: ret } "); } compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); if (op == "==") { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Equality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_Implicit(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.0 IL_0031: pop IL_0032: ret } "); } else { verifier.VerifyIL("Test.M02<T, U>(System.ValueTuple<int, C<T>>)", @" { // Code size 51 (0x33) .maxstack 2 .locals init (System.ValueTuple<int, C<T>> V_0, System.ValueTuple<int, C<T>> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, C<T>>.Item1"" IL_0010: bne.un.s IL_0030 IL_0012: ldloc.0 IL_0013: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""C<T> System.ValueTuple<int, C<T>>.Item2"" IL_001e: call ""T C<T>.op_Inequality(C<T>, C<T>)"" IL_0023: constrained. ""T"" IL_0029: call ""bool I1<T>.op_Implicit(T)"" IL_002e: br.s IL_0031 IL_0030: ldc.i4.1 IL_0031: pop IL_0032: ret } "); } var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("x " + op + " x", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // Information about user-defined operators isn't exposed today. @" ITupleBinaryOperation (BinaryOperatorKind." + (op == "==" ? "Equals" : "NotEquals") + @") (OperationKind.TupleBinary, Type: System.Boolean) (Syntax: 'x " + op + @" x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, C<T>)) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_04([CombinatorialValues("implicit", "explicit")] string op) { bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = @" class Test { static int M02<T>(T x) where T : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,16): error CS8919: Target runtime doesn't support static abstract members in interfaces. // return (int)x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, (needCast ? "(int)" : "") + "x").WithLocation(6, 16) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static explicit operator int(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "int").WithLocation(12, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_04([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool(T x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8919: Target runtime doesn't support static abstract members in interfaces. // _ = x == x; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "x " + op + " x").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.DesktopLatestExtended); compilation3.VerifyDiagnostics( // (21,39): error CS8919: Target runtime doesn't support static abstract members in interfaces. // abstract static implicit operator bool(T x); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "bool").WithLocation(21, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_06([CombinatorialValues("implicit", "explicit")] string op) { bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } "; var source2 = @" class Test { static int M02<T>(T x) where T : I1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,16): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // return x; Diagnostic(ErrorCode.ERR_FeatureInPreview, (needCast ? "(int)" : "") + "x").WithArguments("static abstract members in interfaces").WithLocation(6, 16) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.GetDiagnostics().Where(d => d.Code is not (int)ErrorCode.ERR_OperatorNeedsMatch).Verify( // (12,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator int(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "int").WithArguments("abstract", "9.0", "preview").WithLocation(12, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperatorForTupleEquality_06([CombinatorialValues("==", "!=")] string op) { var source1 = @" public interface I1<T> where T : I1<T> { abstract static implicit operator bool(T x); } "; var source2 = @" class Test { static void M02<T>((int, C<T>) x) where T : I1<T> { _ = x " + op + @" x; } } #pragma warning disable CS0660 // 'C<T>' defines operator == or operator != but does not override Object.Equals(object o) #pragma warning disable CS0661 // 'C<T>' defines operator == or operator != but does not override Object.GetHashCode() class C<T> { public static T operator == (C<T> x, C<T> y) => default; public static T operator != (C<T> x, C<T> y) => default; } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation1.ToMetadataReference() }); compilation2.VerifyDiagnostics( // (6,13): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // _ = x == x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "x " + op + " x").WithArguments("static abstract members in interfaces").WithLocation(6, 13) ); var compilation3 = CreateCompilation(source2 + source1, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compilation3.VerifyDiagnostics( // (21,39): error CS8703: The modifier 'abstract' is not valid for this item in C# 9.0. Please use language version 'preview' or greater. // abstract static implicit operator bool(T x); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "bool").WithArguments("abstract", "9.0", "preview").WithLocation(21, 39) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_07([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_03 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } class Test { static T M02<T, U>(int x) where T : U where U : I1<T> { return " + (needCast ? "(T)" : "") + @"x; } static T? M03<T, U>(int y) where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"y; } static T? M04<T, U>(int? y) where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"y; } static T? M05<T, U>() where T : struct, U where U : I1<T> { return " + (needCast ? "(T?)" : "") + @"(T?)0; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); verifier.VerifyIL("Test.M03<T, U>(int)", @" { // Code size 23 (0x17) .maxstack 1 .locals init (T? V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: newobj ""T?..ctor(T)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?)", @" { // Code size 51 (0x33) .maxstack 1 .locals init (int? V_0, T? V_1, T? V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""readonly bool int?.HasValue.get"" IL_000a: brtrue.s IL_0017 IL_000c: ldloca.s V_1 IL_000e: initobj ""T?"" IL_0014: ldloc.1 IL_0015: br.s IL_002e IL_0017: ldloca.s V_0 IL_0019: call ""readonly int int?.GetValueOrDefault()"" IL_001e: constrained. ""T"" IL_0024: call ""T I1<T>." + metadataName + @"(int)"" IL_0029: newobj ""T?..ctor(T)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 23 (0x17) .maxstack 1 .locals init (T? V_0) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: newobj ""T?..ctor(T)"" IL_0012: stloc.0 IL_0013: br.s IL_0015 IL_0015: ldloc.0 IL_0016: ret } "); compilation1 = CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: ret } "); verifier.VerifyIL("Test.M03<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: newobj ""T?..ctor(T)"" IL_0011: ret } "); verifier.VerifyIL("Test.M04<T, U>(int?)", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (int? V_0, T? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""readonly bool int?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""T?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""readonly int int?.GetValueOrDefault()"" IL_001c: constrained. ""T"" IL_0022: call ""T I1<T>." + metadataName + @"(int)"" IL_0027: newobj ""T?..ctor(T)"" IL_002c: ret } "); verifier.VerifyIL("Test.M05<T, U>()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: constrained. ""T"" IL_0007: call ""T I1<T>." + metadataName + @"(int)"" IL_000c: newobj ""T?..ctor(T)"" IL_0011: ret } "); var tree = compilation1.SyntaxTrees.Single(); var model = compilation1.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().First(); Assert.Equal("return " + (needCast ? "(T)" : "") + @"x;", node.ToString()); VerifyOperationTreeForNode(compilation1, model, node, // https://github.com/dotnet/roslyn/issues/53803: It feels like the "T" constraint is important for this operator, but it is not // reflected in the IOperation tree. Should we change the shape of the tree in order // to expose this information? @" IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return " + (needCast ? "(T)" : "") + @"x;') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: T I1<T>." + metadataName + @"(System.Int32 x)) (OperationKind.Conversion, Type: T" + (needCast ? "" : ", IsImplicit") + @") (Syntax: '" + (needCast ? "(T)" : "") + @"x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: T I1<T>." + metadataName + @"(System.Int32 x)) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_08([CombinatorialValues("implicit", "explicit")] string op) { // Don't look in interfaces of the effective base string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } class C1<T> : I1<C1<T>> { static " + op + @" I1<C1<T>>.operator int(C1<T> x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int M03<T>(C1<T> y) where T : I1<C1<T>> { return " + (needCast ? "(int)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (16,16): error CS0030: Cannot convert type 'T' to 'int' // return (int)x; Diagnostic(error, (needCast ? "(int)" : "") + "x").WithArguments("T", "int").WithLocation(16, 16), // (21,16): error CS0030: Cannot convert type 'C1<T>' to 'int' // return (int)y; Diagnostic(error, (needCast ? "(int)" : "") + "y").WithArguments("C1<T>", "int").WithLocation(21, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_09([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_08 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } class C1<T> : I1<C1<T>> { static " + op + @" I1<C1<T>>.operator C1<T>(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1<T> { return " + (needCast ? "(T)" : "") + @"x; } static C1<T> M03<T>(int y) where T : I1<C1<T>> { return " + (needCast ? "(C1<T>)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var error = (op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv); compilation1.VerifyDiagnostics( // (16,16): error CS0030: Cannot convert type 'int' to 'T' // return (T)x; Diagnostic(error, (needCast ? "(T)" : "") + "x").WithArguments("int", "T").WithLocation(16, 16), // (21,16): error CS0030: Cannot convert type 'int' to 'C1<T>' // return (C1<T>)y; Diagnostic(error, (needCast ? "(C1<T>)" : "") + "y").WithArguments("int", "C1<T>").WithLocation(21, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_10([CombinatorialValues("implicit", "explicit")] string op) { // Look in derived interfaces string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public interface I2<T> : I1<T> where T : I1<T> {} class Test { static int M02<T, U>(T x) where T : U where U : I2<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""int I1<T>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_11([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_10 only direction of conversion is flipped string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } public interface I2<T> : I1<T> where T : I1<T> {} class Test { static T M02<T, U>(int x) where T : U where U : I2<T> { return " + (needCast ? "(T)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""T I1<T>." + metadataName + @"(int)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_12([CombinatorialValues("implicit", "explicit")] string op) { // Ignore duplicate candidates string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T, U> where T : I1<T, U> where U : I1<T, U> { abstract static " + op + @" operator U(T x); } class Test { static U M02<T, U>(T x) where T : I1<T, U> where U : I1<T, U> { return " + (needCast ? "(U)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 18 (0x12) .maxstack 1 .locals init (U V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: constrained. ""T"" IL_0008: call ""U I1<T, U>." + metadataName + @"(T)"" IL_000d: stloc.0 IL_000e: br.s IL_0010 IL_0010: ldloc.0 IL_0011: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_13([CombinatorialValues("implicit", "explicit")] string op) { // Look in effective base string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public class C1<T> { public static " + op + @" operator int(C1<T> x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1<T> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: call ""int C1<T>." + metadataName + @"(C1<T>)"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Fact] public void ConsumeAbstractConversionOperator_14() { // Same as ConsumeAbstractConversionOperator_13 only direction of conversion is flipped var source1 = @" public class C1<T> { public static explicit operator C1<T>(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1<T> { return (T)x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""C1<T> C1<T>.op_Explicit(int)"" IL_0007: unbox.any ""T"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_15([CombinatorialValues("implicit", "explicit")] string op) { // If there is a non-trivial class constraint, interfaces are not looked at. string metadataName = ConversionOperatorName(op); bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C1 : I1<C1> { public static " + op + @" operator int(C1 x) => default; } class Test { static int M02<T, U>(T x) where T : U where U : C1, I1<C1> { return " + (needCast ? "(int)" : "") + @"x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(T)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: box ""T"" IL_0007: call ""int C1." + metadataName + @"(C1)"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Fact] public void ConsumeAbstractConversionOperator_16() { // Same as ConsumeAbstractConversionOperator_15 only direction of conversion is flipped var source1 = @" public interface I1<T> where T : I1<T> { abstract static explicit operator T(int x); } public class C1 : I1<C1> { public static explicit operator C1(int x) => default; } class Test { static T M02<T, U>(int x) where T : U where U : C1, I1<C1> { return (T)x; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(compilation1, verify: Verification.Skipped).VerifyDiagnostics(); verifier.VerifyIL("Test.M02<T, U>(int)", @" { // Code size 17 (0x11) .maxstack 1 .locals init (T V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""C1 C1.op_Explicit(int)"" IL_0007: unbox.any ""T"" IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } "); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_17([CombinatorialValues("implicit", "explicit")] string op) { // If there is a non-trivial class constraint, interfaces are not looked at. bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator int(T x); } public class C1 { } class Test { static int M02<T, U>(T x) where T : U where U : C1, I1<T> { return " + (needCast ? "(int)" : "") + @"x; } static int M03<T, U>(T y) where T : U where U : I1<T> { return " + (needCast ? "(int)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (15,16): error CS0030: Cannot convert type 'T' to 'int' // return (int)x; Diagnostic((op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv), (needCast ? "(int)" : "") + "x").WithArguments("T", "int").WithLocation(15, 16) ); } [Theory] [CombinatorialData] public void ConsumeAbstractConversionOperator_18([CombinatorialValues("implicit", "explicit")] string op) { // Same as ConsumeAbstractConversionOperator_17 only direction of conversion is flipped bool needCast = op == "explicit"; var source1 = @" public interface I1<T> where T : I1<T> { abstract static " + op + @" operator T(int x); } public class C1 { } class Test { static T M02<T, U>(int x) where T : U where U : C1, I1<T> { return " + (needCast ? "(T)" : "") + @"x; } static T M03<T, U>(int y) where T : U where U : I1<T> { return " + (needCast ? "(T)" : "") + @"y; } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (15,16): error CS0030: Cannot convert type 'int' to 'T' // return (T)x; Diagnostic((op == "explicit" ? ErrorCode.ERR_NoExplicitConv : ErrorCode.ERR_NoImplicitConv), (needCast ? "(T)" : "") + "x").WithArguments("int", "T").WithLocation(15, 16) ); } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_01() { var source1 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } public class Derived : Base<int>, Interface<int, int> { } class YetAnother : Interface<int, int> { public static void Method(int i) { } } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var b = module.GlobalNamespace.GetTypeMember("Base"); var bI = b.Interfaces().Single(); var biMethods = bI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", biMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", biMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", biMethods[2].OriginalDefinition.ToTestDisplayString()); var bM1 = b.FindImplementationForInterfaceMember(biMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", bM1.ToTestDisplayString()); var bM2 = b.FindImplementationForInterfaceMember(biMethods[1]); Assert.Equal("void Base<T>.Method(T i)", bM2.ToTestDisplayString()); Assert.Same(bM2, b.FindImplementationForInterfaceMember(biMethods[2])); var bM1Impl = ((MethodSymbol)bM1).ExplicitInterfaceImplementations; var bM2Impl = ((MethodSymbol)bM2).ExplicitInterfaceImplementations; if (module is PEModuleSymbol) { Assert.Equal(biMethods[0], bM1Impl.Single()); Assert.Equal(2, bM2Impl.Length); Assert.Equal(biMethods[1], bM2Impl[0]); Assert.Equal(biMethods[2], bM2Impl[1]); } else { Assert.Empty(bM1Impl); Assert.Empty(bM2Impl); } var d = module.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Same(bM1, dM1.OriginalDefinition); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Same(bM2, dM2.OriginalDefinition); Assert.Same(bM2, d.FindImplementationForInterfaceMember(diMethods[2]).OriginalDefinition); } } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_02() { var source0 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation0.VerifyDiagnostics(); var source1 = @" public class Derived : Base<int>, Interface<int, int> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation0.EmitToImageReference() }); CompileAndVerify(compilation1, sourceSymbolValidator: validate, symbolValidator: validate, verify: Verification.Skipped).VerifyDiagnostics(); void validate(ModuleSymbol module) { var d = module.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", dM1.OriginalDefinition.ToTestDisplayString()); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Equal("void Base<T>.Method(T i)", dM2.OriginalDefinition.ToTestDisplayString()); Assert.Same(dM2, d.FindImplementationForInterfaceMember(diMethods[2])); var dM1Impl = ((MethodSymbol)dM1).ExplicitInterfaceImplementations; var dM2Impl = ((MethodSymbol)dM2).ExplicitInterfaceImplementations; Assert.Equal(diMethods[0], dM1Impl.Single()); Assert.Equal(2, dM2Impl.Length); Assert.Equal(diMethods[1], dM2Impl[0]); Assert.Equal(diMethods[2], dM2Impl[1]); } } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_03() { var source0 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } public class Base<T> : Interface<T, T> { public static void Method(int i) { } public static void Method(T i) { } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { CreateEmptyCompilation("").ToMetadataReference() }); compilation0.VerifyDiagnostics(); var source1 = @" public class Derived : Base<int>, Interface<int, int> { } "; var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp, references: new[] { compilation0.ToMetadataReference() }); var d = compilation1.GlobalNamespace.GetTypeMember("Derived"); var dB = d.BaseTypeNoUseSiteDiagnostics; var dI = d.Interfaces().Single(); var diMethods = dI.GetMembers(); Assert.IsType<RetargetingNamedTypeSymbol>(dB.OriginalDefinition); Assert.Equal("void Interface<T, U>.Method(System.Int32 i)", diMethods[0].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(T i)", diMethods[1].OriginalDefinition.ToTestDisplayString()); Assert.Equal("void Interface<T, U>.Method(U i)", diMethods[2].OriginalDefinition.ToTestDisplayString()); var dM1 = d.FindImplementationForInterfaceMember(diMethods[0]); Assert.Equal("void Base<T>.Method(System.Int32 i)", dM1.OriginalDefinition.ToTestDisplayString()); var dM2 = d.FindImplementationForInterfaceMember(diMethods[1]); Assert.Equal("void Base<T>.Method(T i)", dM2.OriginalDefinition.ToTestDisplayString()); Assert.Equal(dM2, d.FindImplementationForInterfaceMember(diMethods[2])); var dM1Impl = ((MethodSymbol)dM1).ExplicitInterfaceImplementations; var dM2Impl = ((MethodSymbol)dM2).ExplicitInterfaceImplementations; Assert.Empty(dM1Impl); Assert.Empty(dM2Impl); } [Fact] [WorkItem(53802, "https://github.com/dotnet/roslyn/issues/53802")] public void TestAmbiguousImplementationMethod_04() { var source2 = @" public interface Interface<T, U> { abstract static void Method(int i); abstract static void Method(T i); abstract static void Method(U i); } class Other : Interface<int, int> { static void Interface<int, int>.Method(int i) { } } "; var compilation2 = CreateCompilation(source2, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (9,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(9, 15), // (9,15): error CS0535: 'Other' does not implement interface member 'Interface<int, int>.Method(int)' // class Other : Interface<int, int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface<int, int>").WithArguments("Other", "Interface<int, int>.Method(int)").WithLocation(9, 15), // (11,37): warning CS0473: Explicit interface implementation 'Other.Interface<int, int>.Method(int)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // static void Interface<int, int>.Method(int i) { } Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Other.Interface<int, int>.Method(int)").WithLocation(11, 37) ); } [Fact] public void UnmanagedCallersOnly_01() { var source2 = @" using System.Runtime.InteropServices; public interface I1 { [UnmanagedCallersOnly] abstract static void M1(); [UnmanagedCallersOnly] abstract static int operator +(I1 x); [UnmanagedCallersOnly] abstract static int operator +(I1 x, I1 y); } public interface I2<T> where T : I2<T> { [UnmanagedCallersOnly] abstract static implicit operator int(T i); [UnmanagedCallersOnly] abstract static explicit operator T(int i); } "; var compilation2 = CreateCompilation(new[] { source2, UnmanagedCallersOnlyAttributeDefinition }, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (6,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static void M1(); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(6, 6), // (7,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static int operator +(I1 x); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 6), // (8,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static int operator +(I1 x, I1 y); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(8, 6), // (13,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static implicit operator int(T i); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(13, 6), // (14,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] abstract static explicit operator T(int i); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(14, 6) ); } [Fact] [WorkItem(54113, "https://github.com/dotnet/roslyn/issues/54113")] public void UnmanagedCallersOnly_02() { var ilSource = @" .class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72 69 74 65 64 00 ) .field public class [mscorlib]System.Type[] CallConvs .field public string EntryPoint .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } .class interface public auto ansi abstract I1 { .method public hidebysig abstract virtual static void M1 () cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static int32 op_UnaryPlus ( class I1 x ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static int32 op_Addition ( class I1 x, class I1 y ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } } .class interface public auto ansi abstract I2`1<(class I2`1<!T>) T> { .method public hidebysig specialname abstract virtual static int32 op_Implicit ( !T i ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } .method public hidebysig specialname abstract virtual static !T op_Explicit ( int32 i ) cil managed { // [System.Runtime.InteropServices.UnmanagedCallersOnly] .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) } } "; var source1 = @" class Test { static void M02<T>(T x, T y) where T : I1 { T.M1(); _ = +x; _ = x + y; } static int M03<T>(T x) where T : I2<T> { _ = (T)x; return x; } } "; var compilation1 = CreateCompilationWithIL(source1, ilSource, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); // Conversions aren't flagged due to https://github.com/dotnet/roslyn/issues/54113. compilation1.VerifyDiagnostics( // (6,11): error CS0570: 'I1.M1()' is not supported by the language // T.M1(); Diagnostic(ErrorCode.ERR_BindToBogus, "M1").WithArguments("I1.M1()").WithLocation(6, 11), // (7,13): error CS0570: 'I1.operator +(I1)' is not supported by the language // _ = +x; Diagnostic(ErrorCode.ERR_BindToBogus, "+x").WithArguments("I1.operator +(I1)").WithLocation(7, 13), // (8,13): error CS0570: 'I1.operator +(I1, I1)' is not supported by the language // _ = x + y; Diagnostic(ErrorCode.ERR_BindToBogus, "x + y").WithArguments("I1.operator +(I1, I1)").WithLocation(8, 13) ); } [Fact] public void UnmanagedCallersOnly_03() { var source2 = @" using System.Runtime.InteropServices; public interface I1<T> where T : I1<T> { abstract static void M1(); abstract static int operator +(T x); abstract static int operator +(T x, T y); abstract static implicit operator int(T i); abstract static explicit operator T(int i); } class C : I1<C> { [UnmanagedCallersOnly] public static void M1() {} [UnmanagedCallersOnly] public static int operator +(C x) => 0; [UnmanagedCallersOnly] public static int operator +(C x, C y) => 0; [UnmanagedCallersOnly] public static implicit operator int(C i) => 0; [UnmanagedCallersOnly] public static explicit operator C(int i) => null; } "; var compilation2 = CreateCompilation(new[] { source2, UnmanagedCallersOnlyAttributeDefinition }, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (15,47): error CS8932: 'UnmanagedCallersOnly' method 'C.M1()' cannot implement interface member 'I1<C>.M1()' in type 'C' // [UnmanagedCallersOnly] public static void M1() {} Diagnostic(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, "M1").WithArguments("C.M1()", "I1<C>.M1()", "C").WithLocation(15, 47), // (16,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static int operator +(C x) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(16, 6), // (17,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static int operator +(C x, C y) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(17, 6), // (18,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static implicit operator int(C i) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(18, 6), // (19,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] public static explicit operator C(int i) => null; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(19, 6) ); } [Fact] public void UnmanagedCallersOnly_04() { var source2 = @" using System.Runtime.InteropServices; public interface I1<T> where T : I1<T> { abstract static void M1(); abstract static int operator +(T x); abstract static int operator +(T x, T y); abstract static implicit operator int(T i); abstract static explicit operator T(int i); } class C : I1<C> { [UnmanagedCallersOnly] static void I1<C>.M1() {} [UnmanagedCallersOnly] static int I1<C>.operator +(C x) => 0; [UnmanagedCallersOnly] static int I1<C>.operator +(C x, C y) => 0; [UnmanagedCallersOnly] static implicit I1<C>.operator int(C i) => 0; [UnmanagedCallersOnly] static explicit I1<C>.operator C(int i) => null; } "; var compilation2 = CreateCompilation(new[] { source2, UnmanagedCallersOnlyAttributeDefinition }, options: TestOptions.DebugDll, parseOptions: TestOptions.RegularPreview, targetFramework: TargetFramework.NetCoreApp); compilation2.VerifyDiagnostics( // (15,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static void I1<C>.M1() {} Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(15, 6), // (16,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static int I1<C>.operator +(C x) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(16, 6), // (17,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static int I1<C>.operator +(C x, C y) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(17, 6), // (18,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static implicit I1<C>.operator int(C i) => 0; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(18, 6), // (19,6): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions. // [UnmanagedCallersOnly] static explicit I1<C>.operator C(int i) => null; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(19, 6) ); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/ExternalAccess/OmniSharp/GoToDefinition/OmniSharpFindDefinitionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.ExternalAccess.OmniSharp.Navigation; using Microsoft.CodeAnalysis.GoToDefinition; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.GoToDefinition { internal static class OmniSharpFindDefinitionService { internal static async Task<ImmutableArray<OmniSharpNavigableItem>> FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken) { var service = document.GetRequiredLanguageService<IFindDefinitionService>(); var result = await service.FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); return result.NullToEmpty().SelectAsArray(original => new OmniSharpNavigableItem(original.DisplayTaggedParts, original.Document, original.SourceSpan)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.ExternalAccess.OmniSharp.Navigation; using Microsoft.CodeAnalysis.GoToDefinition; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.GoToDefinition { internal static class OmniSharpFindDefinitionService { internal static async Task<ImmutableArray<OmniSharpNavigableItem>> FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken) { var service = document.GetRequiredLanguageService<IFindDefinitionService>(); var result = await service.FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); return result.NullToEmpty().SelectAsArray(original => new OmniSharpNavigableItem(original.DisplayTaggedParts, original.Document, original.SourceSpan)); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Impl/CodeModel/Interop/ICodeElements.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop { /// <summary> /// A redefinition of the EnvDTE.CodeElements interface. The interface, as defined in the PIA does not do /// PreserveSig for the Item function. WinForms, specifically, uses the Item property when generating methods to see /// if a method already exists. The only way it sees if something exists is if the call returns E_INVALIDARG. With /// the normal PIAs though, this would result in a first-chance exception. Therefore, the WinForms team has their /// own definition for CodeElements which also [PreserveSig]s Item. We do this here to make their work still /// worthwhile. /// </summary> [ComImport] [Guid("0CFBC2B5-0D4E-11D3-8997-00C04F688DDE")] [InterfaceType(ComInterfaceType.InterfaceIsDual)] internal interface ICodeElements : IEnumerable { [DispId(-4)] [TypeLibFunc(TypeLibFuncFlags.FRestricted)] new IEnumerator GetEnumerator(); [DispId(1)] EnvDTE.DTE DTE { [return: MarshalAs(UnmanagedType.Interface)] get; } [DispId(2)] object Parent { [return: MarshalAs(UnmanagedType.IDispatch)] get; } [DispId(0)] [PreserveSig] [return: MarshalAs(UnmanagedType.Error)] int Item(object index, [MarshalAs(UnmanagedType.Interface)] out EnvDTE.CodeElement element); [DispId(3)] int Count { get; } [TypeLibFunc(TypeLibFuncFlags.FHidden | TypeLibFuncFlags.FRestricted)] [DispId(4)] void Reserved1(object element); [DispId(5)] bool CreateUniqueID([MarshalAs(UnmanagedType.BStr)] string prefix, [MarshalAs(UnmanagedType.BStr)] ref string newName); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop { /// <summary> /// A redefinition of the EnvDTE.CodeElements interface. The interface, as defined in the PIA does not do /// PreserveSig for the Item function. WinForms, specifically, uses the Item property when generating methods to see /// if a method already exists. The only way it sees if something exists is if the call returns E_INVALIDARG. With /// the normal PIAs though, this would result in a first-chance exception. Therefore, the WinForms team has their /// own definition for CodeElements which also [PreserveSig]s Item. We do this here to make their work still /// worthwhile. /// </summary> [ComImport] [Guid("0CFBC2B5-0D4E-11D3-8997-00C04F688DDE")] [InterfaceType(ComInterfaceType.InterfaceIsDual)] internal interface ICodeElements : IEnumerable { [DispId(-4)] [TypeLibFunc(TypeLibFuncFlags.FRestricted)] new IEnumerator GetEnumerator(); [DispId(1)] EnvDTE.DTE DTE { [return: MarshalAs(UnmanagedType.Interface)] get; } [DispId(2)] object Parent { [return: MarshalAs(UnmanagedType.IDispatch)] get; } [DispId(0)] [PreserveSig] [return: MarshalAs(UnmanagedType.Error)] int Item(object index, [MarshalAs(UnmanagedType.Interface)] out EnvDTE.CodeElement element); [DispId(3)] int Count { get; } [TypeLibFunc(TypeLibFuncFlags.FHidden | TypeLibFuncFlags.FRestricted)] [DispId(4)] void Reserved1(object element); [DispId(5)] bool CreateUniqueID([MarshalAs(UnmanagedType.BStr)] string prefix, [MarshalAs(UnmanagedType.BStr)] ref string newName); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/Completion/EnterKeyRule.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Determines whether the enter key is passed through to the editor after it has been used to commit a completion item. /// </summary> public enum EnterKeyRule { Default = 0, /// <summary> /// The enter key is never passed through to the editor after it has been used to commit the completion item. /// </summary> Never, /// <summary> /// The enter key is always passed through to the editor after it has been used to commit the completion item. /// </summary> Always, /// <summary> /// The enter is key only passed through to the editor if the completion item has been fully typed out. /// </summary> AfterFullyTypedWord } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Determines whether the enter key is passed through to the editor after it has been used to commit a completion item. /// </summary> public enum EnterKeyRule { Default = 0, /// <summary> /// The enter key is never passed through to the editor after it has been used to commit the completion item. /// </summary> Never, /// <summary> /// The enter key is always passed through to the editor after it has been used to commit the completion item. /// </summary> Always, /// <summary> /// The enter is key only passed through to the editor if the completion item has been fully typed out. /// </summary> AfterFullyTypedWord } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/TestUtilities/DocumentationComments/AbstractDocumentationCommentTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.DocumentationComments { [UseExportProvider] public abstract class AbstractDocumentationCommentTests { protected abstract char DocumentationCommentCharacter { get; } internal abstract ICommandHandler CreateCommandHandler(TestWorkspace workspace); protected abstract TestWorkspace CreateTestWorkspace(string code); protected void VerifyTypingCharacter(string initialMarkup, string expectedMarkup, bool useTabs = false, bool autoGenerateXmlDocComments = true, string newLine = "\r\n") { Verify(initialMarkup, expectedMarkup, useTabs, autoGenerateXmlDocComments, newLine: newLine, execute: (workspace, view, editorOperationsFactoryService) => { var commandHandler = CreateCommandHandler(workspace); var commandArgs = new TypeCharCommandArgs(view, view.TextBuffer, DocumentationCommentCharacter); var nextHandler = CreateInsertTextHandler(view, DocumentationCommentCharacter.ToString()); commandHandler.ExecuteCommand(commandArgs, nextHandler, TestCommandExecutionContext.Create()); }); } protected void VerifyPressingEnter(string initialMarkup, string expectedMarkup, bool useTabs = false, bool autoGenerateXmlDocComments = true, Action<TestWorkspace> setOptionsOpt = null) { Verify(initialMarkup, expectedMarkup, useTabs, autoGenerateXmlDocComments, setOptionsOpt: setOptionsOpt, execute: (workspace, view, editorOperationsFactoryService) => { var commandHandler = CreateCommandHandler(workspace); var commandArgs = new ReturnKeyCommandArgs(view, view.TextBuffer); var nextHandler = CreateInsertTextHandler(view, "\r\n"); commandHandler.ExecuteCommand(commandArgs, nextHandler, TestCommandExecutionContext.Create()); }); } protected void VerifyInsertCommentCommand(string initialMarkup, string expectedMarkup, bool useTabs = false, bool autoGenerateXmlDocComments = true) { Verify(initialMarkup, expectedMarkup, useTabs, autoGenerateXmlDocComments, execute: (workspace, view, editorOperationsFactoryService) => { var commandHandler = CreateCommandHandler(workspace); var commandArgs = new InsertCommentCommandArgs(view, view.TextBuffer); Action nextHandler = delegate { }; commandHandler.ExecuteCommand(commandArgs, nextHandler, TestCommandExecutionContext.Create()); }); } protected void VerifyOpenLineAbove(string initialMarkup, string expectedMarkup, bool useTabs = false, bool autoGenerateXmlDocComments = true) { Verify(initialMarkup, expectedMarkup, useTabs, autoGenerateXmlDocComments, execute: (workspace, view, editorOperationsFactoryService) => { var commandHandler = CreateCommandHandler(workspace); var commandArgs = new OpenLineAboveCommandArgs(view, view.TextBuffer); void nextHandler() { var editorOperations = editorOperationsFactoryService.GetEditorOperations(view); editorOperations.OpenLineAbove(); } commandHandler.ExecuteCommand(commandArgs, nextHandler, TestCommandExecutionContext.Create()); }); } protected void VerifyOpenLineBelow(string initialMarkup, string expectedMarkup, bool useTabs = false, bool autoGenerateXmlDocComments = true) { Verify(initialMarkup, expectedMarkup, useTabs, autoGenerateXmlDocComments, execute: (workspace, view, editorOperationsFactoryService) => { var commandHandler = CreateCommandHandler(workspace); var commandArgs = new OpenLineBelowCommandArgs(view, view.TextBuffer); void nextHandler() { var editorOperations = editorOperationsFactoryService.GetEditorOperations(view); editorOperations.OpenLineBelow(); } commandHandler.ExecuteCommand(commandArgs, nextHandler, TestCommandExecutionContext.Create()); }); } private static Action CreateInsertTextHandler(ITextView textView, string text) { return () => { var caretPosition = textView.Caret.Position.BufferPosition; var newSpanshot = textView.TextBuffer.Insert(caretPosition, text); textView.Caret.MoveTo(new SnapshotPoint(newSpanshot, caretPosition + text.Length)); }; } private void Verify(string initialMarkup, string expectedMarkup, bool useTabs, bool autoGenerateXmlDocComments, Action<TestWorkspace, IWpfTextView, IEditorOperationsFactoryService> execute, Action<TestWorkspace> setOptionsOpt = null, string newLine = "\r\n") { using (var workspace = CreateTestWorkspace(initialMarkup)) { var testDocument = workspace.Documents.Single(); var options = workspace.Options; options = options.WithChangedOption(FormattingOptions.UseTabs, testDocument.Project.Language, useTabs); options = options.WithChangedOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration, testDocument.Project.Language, autoGenerateXmlDocComments); options = options.WithChangedOption(FormattingOptions.NewLine, testDocument.Project.Language, newLine); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options)); setOptionsOpt?.Invoke(workspace); Assert.True(testDocument.CursorPosition.HasValue, "No caret position set!"); var startCaretPosition = testDocument.CursorPosition.Value; var view = testDocument.GetTextView(); if (testDocument.SelectedSpans.Any()) { var selectedSpan = testDocument.SelectedSpans[0]; var isReversed = selectedSpan.Start == startCaretPosition ? true : false; view.Selection.Select(new SnapshotSpan(view.TextSnapshot, selectedSpan.Start, selectedSpan.Length), isReversed); } view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value)); execute( workspace, view, workspace.GetService<IEditorOperationsFactoryService>()); MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition); Assert.Equal(expectedCode, view.TextSnapshot.GetText()); var endCaretPosition = view.Caret.Position.BufferPosition.Position; Assert.True(expectedPosition == endCaretPosition, string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, endCaretPosition)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.DocumentationComments { [UseExportProvider] public abstract class AbstractDocumentationCommentTests { protected abstract char DocumentationCommentCharacter { get; } internal abstract ICommandHandler CreateCommandHandler(TestWorkspace workspace); protected abstract TestWorkspace CreateTestWorkspace(string code); protected void VerifyTypingCharacter(string initialMarkup, string expectedMarkup, bool useTabs = false, bool autoGenerateXmlDocComments = true, string newLine = "\r\n") { Verify(initialMarkup, expectedMarkup, useTabs, autoGenerateXmlDocComments, newLine: newLine, execute: (workspace, view, editorOperationsFactoryService) => { var commandHandler = CreateCommandHandler(workspace); var commandArgs = new TypeCharCommandArgs(view, view.TextBuffer, DocumentationCommentCharacter); var nextHandler = CreateInsertTextHandler(view, DocumentationCommentCharacter.ToString()); commandHandler.ExecuteCommand(commandArgs, nextHandler, TestCommandExecutionContext.Create()); }); } protected void VerifyPressingEnter(string initialMarkup, string expectedMarkup, bool useTabs = false, bool autoGenerateXmlDocComments = true, Action<TestWorkspace> setOptionsOpt = null) { Verify(initialMarkup, expectedMarkup, useTabs, autoGenerateXmlDocComments, setOptionsOpt: setOptionsOpt, execute: (workspace, view, editorOperationsFactoryService) => { var commandHandler = CreateCommandHandler(workspace); var commandArgs = new ReturnKeyCommandArgs(view, view.TextBuffer); var nextHandler = CreateInsertTextHandler(view, "\r\n"); commandHandler.ExecuteCommand(commandArgs, nextHandler, TestCommandExecutionContext.Create()); }); } protected void VerifyInsertCommentCommand(string initialMarkup, string expectedMarkup, bool useTabs = false, bool autoGenerateXmlDocComments = true) { Verify(initialMarkup, expectedMarkup, useTabs, autoGenerateXmlDocComments, execute: (workspace, view, editorOperationsFactoryService) => { var commandHandler = CreateCommandHandler(workspace); var commandArgs = new InsertCommentCommandArgs(view, view.TextBuffer); Action nextHandler = delegate { }; commandHandler.ExecuteCommand(commandArgs, nextHandler, TestCommandExecutionContext.Create()); }); } protected void VerifyOpenLineAbove(string initialMarkup, string expectedMarkup, bool useTabs = false, bool autoGenerateXmlDocComments = true) { Verify(initialMarkup, expectedMarkup, useTabs, autoGenerateXmlDocComments, execute: (workspace, view, editorOperationsFactoryService) => { var commandHandler = CreateCommandHandler(workspace); var commandArgs = new OpenLineAboveCommandArgs(view, view.TextBuffer); void nextHandler() { var editorOperations = editorOperationsFactoryService.GetEditorOperations(view); editorOperations.OpenLineAbove(); } commandHandler.ExecuteCommand(commandArgs, nextHandler, TestCommandExecutionContext.Create()); }); } protected void VerifyOpenLineBelow(string initialMarkup, string expectedMarkup, bool useTabs = false, bool autoGenerateXmlDocComments = true) { Verify(initialMarkup, expectedMarkup, useTabs, autoGenerateXmlDocComments, execute: (workspace, view, editorOperationsFactoryService) => { var commandHandler = CreateCommandHandler(workspace); var commandArgs = new OpenLineBelowCommandArgs(view, view.TextBuffer); void nextHandler() { var editorOperations = editorOperationsFactoryService.GetEditorOperations(view); editorOperations.OpenLineBelow(); } commandHandler.ExecuteCommand(commandArgs, nextHandler, TestCommandExecutionContext.Create()); }); } private static Action CreateInsertTextHandler(ITextView textView, string text) { return () => { var caretPosition = textView.Caret.Position.BufferPosition; var newSpanshot = textView.TextBuffer.Insert(caretPosition, text); textView.Caret.MoveTo(new SnapshotPoint(newSpanshot, caretPosition + text.Length)); }; } private void Verify(string initialMarkup, string expectedMarkup, bool useTabs, bool autoGenerateXmlDocComments, Action<TestWorkspace, IWpfTextView, IEditorOperationsFactoryService> execute, Action<TestWorkspace> setOptionsOpt = null, string newLine = "\r\n") { using (var workspace = CreateTestWorkspace(initialMarkup)) { var testDocument = workspace.Documents.Single(); var options = workspace.Options; options = options.WithChangedOption(FormattingOptions.UseTabs, testDocument.Project.Language, useTabs); options = options.WithChangedOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration, testDocument.Project.Language, autoGenerateXmlDocComments); options = options.WithChangedOption(FormattingOptions.NewLine, testDocument.Project.Language, newLine); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options)); setOptionsOpt?.Invoke(workspace); Assert.True(testDocument.CursorPosition.HasValue, "No caret position set!"); var startCaretPosition = testDocument.CursorPosition.Value; var view = testDocument.GetTextView(); if (testDocument.SelectedSpans.Any()) { var selectedSpan = testDocument.SelectedSpans[0]; var isReversed = selectedSpan.Start == startCaretPosition ? true : false; view.Selection.Select(new SnapshotSpan(view.TextSnapshot, selectedSpan.Start, selectedSpan.Length), isReversed); } view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value)); execute( workspace, view, workspace.GetService<IEditorOperationsFactoryService>()); MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition); Assert.Equal(expectedCode, view.TextSnapshot.GetText()); var endCaretPosition = view.Caret.Position.BufferPosition.Position; Assert.True(expectedPosition == endCaretPosition, string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, endCaretPosition)); } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/ExternalAccess/FSharp/Navigation/IFSharpDocumentNavigationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Navigation { internal interface IFSharpDocumentNavigationService : IWorkspaceService { [Obsolete("Call overload that takes a CancellationToken", error: false)] bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan); [Obsolete("Call overload that takes a CancellationToken", error: false)] bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset); [Obsolete("Call overload that takes a CancellationToken", error: false)] bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0); [Obsolete("Call overload that takes a CancellationToken", error: false)] bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options = null); [Obsolete("Call overload that takes a CancellationToken", error: false)] bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options = null); [Obsolete("Call overload that takes a CancellationToken", error: false)] bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0, OptionSet options = null); /// <inheritdoc cref="IDocumentNavigationService.CanNavigateToSpan"/> bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken); /// <inheritdoc cref="IDocumentNavigationService.CanNavigateToLineAndOffset"/> bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken); /// <inheritdoc cref="IDocumentNavigationService.CanNavigateToPosition"/> bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken); /// <inheritdoc cref="IDocumentNavigationService.TryNavigateToSpan"/> bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken); /// <inheritdoc cref="IDocumentNavigationService.TryNavigateToLineAndOffset"/> bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken); /// <inheritdoc cref="IDocumentNavigationService.TryNavigateToPosition"/> bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, 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; using System.Threading; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Navigation { internal interface IFSharpDocumentNavigationService : IWorkspaceService { [Obsolete("Call overload that takes a CancellationToken", error: false)] bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan); [Obsolete("Call overload that takes a CancellationToken", error: false)] bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset); [Obsolete("Call overload that takes a CancellationToken", error: false)] bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0); [Obsolete("Call overload that takes a CancellationToken", error: false)] bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options = null); [Obsolete("Call overload that takes a CancellationToken", error: false)] bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options = null); [Obsolete("Call overload that takes a CancellationToken", error: false)] bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0, OptionSet options = null); /// <inheritdoc cref="IDocumentNavigationService.CanNavigateToSpan"/> bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken); /// <inheritdoc cref="IDocumentNavigationService.CanNavigateToLineAndOffset"/> bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken); /// <inheritdoc cref="IDocumentNavigationService.CanNavigateToPosition"/> bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken); /// <inheritdoc cref="IDocumentNavigationService.TryNavigateToSpan"/> bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken); /// <inheritdoc cref="IDocumentNavigationService.TryNavigateToLineAndOffset"/> bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken); /// <inheritdoc cref="IDocumentNavigationService.TryNavigateToPosition"/> bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentStates.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Holds on a <see cref="DocumentId"/> to <see cref="TextDocumentState"/> map and an ordering. /// </summary> internal readonly struct TextDocumentStates<TState> where TState : TextDocumentState { public static readonly TextDocumentStates<TState> Empty = new(ImmutableList<DocumentId>.Empty, ImmutableSortedDictionary.Create<DocumentId, TState>(DocumentIdComparer.Instance)); private readonly ImmutableList<DocumentId> _ids; /// <summary> /// The entries in the map are sorted by <see cref="DocumentId.Id"/>, which yields locally deterministic order but not the order that /// matches the order in which documents were added. Therefore this ordering can't be used when creating compilations and it can't be /// used when persisting document lists that do not preserve the GUIDs. /// </summary> private readonly ImmutableSortedDictionary<DocumentId, TState> _map; private TextDocumentStates(ImmutableList<DocumentId> ids, ImmutableSortedDictionary<DocumentId, TState> map) { Debug.Assert(map.KeyComparer == DocumentIdComparer.Instance); _ids = ids; _map = map; } public TextDocumentStates(IEnumerable<TState> states) : this(states.Select(s => s.Id).ToImmutableList(), states.ToImmutableSortedDictionary(state => state.Id, state => state, DocumentIdComparer.Instance)) { } public TextDocumentStates(IEnumerable<DocumentInfo> infos, Func<DocumentInfo, TState> stateConstructor) : this(infos.Select(info => info.Id).ToImmutableList(), infos.ToImmutableSortedDictionary(info => info.Id, stateConstructor, DocumentIdComparer.Instance)) { } public TextDocumentStates<TState> WithCompilationOrder(ImmutableList<DocumentId> ids) => new(ids, _map); public int Count => _map.Count; public bool IsEmpty => Count == 0; public bool Contains(DocumentId id) => _map.ContainsKey(id); public bool TryGetState(DocumentId documentId, [NotNullWhen(true)] out TState? state) => _map.TryGetValue(documentId, out state); public TState? GetState(DocumentId documentId) => _map.TryGetValue(documentId, out var state) ? state : null; public TState GetRequiredState(DocumentId documentId) => _map.TryGetValue(documentId, out var state) ? state : throw ExceptionUtilities.Unreachable; /// <summary> /// <see cref="DocumentId"/>s in the order in which they were added to the project (the compilation order). /// </summary> public readonly IReadOnlyList<DocumentId> Ids => _ids; /// <summary> /// States ordered by <see cref="DocumentId"/>. /// </summary> public ImmutableSortedDictionary<DocumentId, TState> States => _map; /// <summary> /// Get states ordered in compilation order. /// </summary> /// <returns></returns> public IEnumerable<TState> GetStatesInCompilationOrder() { foreach (var id in Ids) { yield return _map[id]; } } public ImmutableArray<TValue> SelectAsArray<TValue>(Func<TState, TValue> selector) { using var _ = ArrayBuilder<TValue>.GetInstance(out var builder); foreach (var (_, state) in _map) { builder.Add(selector(state)); } return builder.ToImmutable(); } public ImmutableArray<TValue> SelectAsArray<TValue, TArg>(Func<TState, TArg, TValue> selector, TArg arg) { using var _ = ArrayBuilder<TValue>.GetInstance(out var builder); foreach (var (_, state) in _map) { builder.Add(selector(state, arg)); } return builder.ToImmutable(); } public async ValueTask<ImmutableArray<TValue>> SelectAsArrayAsync<TValue, TArg>(Func<TState, TArg, CancellationToken, ValueTask<TValue>> selector, TArg arg, CancellationToken cancellationToken) { using var _ = ArrayBuilder<TValue>.GetInstance(out var builder); foreach (var (_, state) in _map) { builder.Add(await selector(state, arg, cancellationToken).ConfigureAwait(true)); } return builder.ToImmutable(); } public TextDocumentStates<TState> AddRange(ImmutableArray<TState> states) => new(_ids.AddRange(states.Select(state => state.Id)), _map.AddRange(states.Select(state => KeyValuePairUtil.Create(state.Id, state)))); public TextDocumentStates<TState> RemoveRange(ImmutableArray<DocumentId> ids) { IEnumerable<DocumentId> enumerableIds = ids; return new(_ids.RemoveRange(enumerableIds), _map.RemoveRange(enumerableIds)); } internal TextDocumentStates<TState> SetState(DocumentId id, TState state) => new(_ids, _map.SetItem(id, state)); public TextDocumentStates<TState> UpdateStates<TArg>(Func<TState, TArg, TState> transformation, TArg arg) { var builder = _map.ToBuilder(); foreach (var (id, state) in _map) { builder[id] = transformation(state, arg); } return new(_ids, builder.ToImmutable()); } /// <summary> /// Returns a <see cref="DocumentId"/>s of documents whose state changed when compared to older states. /// </summary> public IEnumerable<DocumentId> GetChangedStateIds(TextDocumentStates<TState> oldStates, bool ignoreUnchangedContent = false, bool ignoreUnchangeableDocuments = false) { Contract.ThrowIfTrue(!ignoreUnchangedContent && ignoreUnchangeableDocuments); foreach (var id in Ids) { if (!oldStates.TryGetState(id, out var oldState)) { // document was removed continue; } var newState = _map[id]; if (newState == oldState) { continue; } if (ignoreUnchangedContent && !newState.HasTextChanged(oldState, ignoreUnchangeableDocuments)) { continue; } yield return id; } } /// <summary> /// Returns a <see cref="DocumentId"/>s of added documents. /// </summary> public IEnumerable<DocumentId> GetAddedStateIds(TextDocumentStates<TState> oldStates) => (_ids == oldStates._ids) ? SpecializedCollections.EmptyEnumerable<DocumentId>() : Except(_ids, oldStates._map); /// <summary> /// Returns a <see cref="DocumentId"/>s of removed documents. /// </summary> public IEnumerable<DocumentId> GetRemovedStateIds(TextDocumentStates<TState> oldStates) => (_ids == oldStates._ids) ? SpecializedCollections.EmptyEnumerable<DocumentId>() : Except(oldStates._ids, _map); private static IEnumerable<DocumentId> Except(IEnumerable<DocumentId> ids, ImmutableSortedDictionary<DocumentId, TState> map) { foreach (var id in ids) { if (!map.ContainsKey(id)) { yield return id; } } } public bool HasAnyStateChanges(TextDocumentStates<TState> oldStates) => !_map.Values.SequenceEqual(oldStates._map.Values); private sealed class DocumentIdComparer : IComparer<DocumentId?> { public static readonly IComparer<DocumentId?> Instance = new DocumentIdComparer(); private DocumentIdComparer() { } public int Compare(DocumentId? x, DocumentId? y) { if (x is null) { return y is null ? 0 : -1; } else if (y is null) { return 1; } return x.Id.CompareTo(y.Id); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Holds on a <see cref="DocumentId"/> to <see cref="TextDocumentState"/> map and an ordering. /// </summary> internal readonly struct TextDocumentStates<TState> where TState : TextDocumentState { public static readonly TextDocumentStates<TState> Empty = new(ImmutableList<DocumentId>.Empty, ImmutableSortedDictionary.Create<DocumentId, TState>(DocumentIdComparer.Instance)); private readonly ImmutableList<DocumentId> _ids; /// <summary> /// The entries in the map are sorted by <see cref="DocumentId.Id"/>, which yields locally deterministic order but not the order that /// matches the order in which documents were added. Therefore this ordering can't be used when creating compilations and it can't be /// used when persisting document lists that do not preserve the GUIDs. /// </summary> private readonly ImmutableSortedDictionary<DocumentId, TState> _map; private TextDocumentStates(ImmutableList<DocumentId> ids, ImmutableSortedDictionary<DocumentId, TState> map) { Debug.Assert(map.KeyComparer == DocumentIdComparer.Instance); _ids = ids; _map = map; } public TextDocumentStates(IEnumerable<TState> states) : this(states.Select(s => s.Id).ToImmutableList(), states.ToImmutableSortedDictionary(state => state.Id, state => state, DocumentIdComparer.Instance)) { } public TextDocumentStates(IEnumerable<DocumentInfo> infos, Func<DocumentInfo, TState> stateConstructor) : this(infos.Select(info => info.Id).ToImmutableList(), infos.ToImmutableSortedDictionary(info => info.Id, stateConstructor, DocumentIdComparer.Instance)) { } public TextDocumentStates<TState> WithCompilationOrder(ImmutableList<DocumentId> ids) => new(ids, _map); public int Count => _map.Count; public bool IsEmpty => Count == 0; public bool Contains(DocumentId id) => _map.ContainsKey(id); public bool TryGetState(DocumentId documentId, [NotNullWhen(true)] out TState? state) => _map.TryGetValue(documentId, out state); public TState? GetState(DocumentId documentId) => _map.TryGetValue(documentId, out var state) ? state : null; public TState GetRequiredState(DocumentId documentId) => _map.TryGetValue(documentId, out var state) ? state : throw ExceptionUtilities.Unreachable; /// <summary> /// <see cref="DocumentId"/>s in the order in which they were added to the project (the compilation order). /// </summary> public readonly IReadOnlyList<DocumentId> Ids => _ids; /// <summary> /// States ordered by <see cref="DocumentId"/>. /// </summary> public ImmutableSortedDictionary<DocumentId, TState> States => _map; /// <summary> /// Get states ordered in compilation order. /// </summary> /// <returns></returns> public IEnumerable<TState> GetStatesInCompilationOrder() { foreach (var id in Ids) { yield return _map[id]; } } public ImmutableArray<TValue> SelectAsArray<TValue>(Func<TState, TValue> selector) { using var _ = ArrayBuilder<TValue>.GetInstance(out var builder); foreach (var (_, state) in _map) { builder.Add(selector(state)); } return builder.ToImmutable(); } public ImmutableArray<TValue> SelectAsArray<TValue, TArg>(Func<TState, TArg, TValue> selector, TArg arg) { using var _ = ArrayBuilder<TValue>.GetInstance(out var builder); foreach (var (_, state) in _map) { builder.Add(selector(state, arg)); } return builder.ToImmutable(); } public async ValueTask<ImmutableArray<TValue>> SelectAsArrayAsync<TValue, TArg>(Func<TState, TArg, CancellationToken, ValueTask<TValue>> selector, TArg arg, CancellationToken cancellationToken) { using var _ = ArrayBuilder<TValue>.GetInstance(out var builder); foreach (var (_, state) in _map) { builder.Add(await selector(state, arg, cancellationToken).ConfigureAwait(true)); } return builder.ToImmutable(); } public TextDocumentStates<TState> AddRange(ImmutableArray<TState> states) => new(_ids.AddRange(states.Select(state => state.Id)), _map.AddRange(states.Select(state => KeyValuePairUtil.Create(state.Id, state)))); public TextDocumentStates<TState> RemoveRange(ImmutableArray<DocumentId> ids) { IEnumerable<DocumentId> enumerableIds = ids; return new(_ids.RemoveRange(enumerableIds), _map.RemoveRange(enumerableIds)); } internal TextDocumentStates<TState> SetState(DocumentId id, TState state) => new(_ids, _map.SetItem(id, state)); public TextDocumentStates<TState> UpdateStates<TArg>(Func<TState, TArg, TState> transformation, TArg arg) { var builder = _map.ToBuilder(); foreach (var (id, state) in _map) { builder[id] = transformation(state, arg); } return new(_ids, builder.ToImmutable()); } /// <summary> /// Returns a <see cref="DocumentId"/>s of documents whose state changed when compared to older states. /// </summary> public IEnumerable<DocumentId> GetChangedStateIds(TextDocumentStates<TState> oldStates, bool ignoreUnchangedContent = false, bool ignoreUnchangeableDocuments = false) { Contract.ThrowIfTrue(!ignoreUnchangedContent && ignoreUnchangeableDocuments); foreach (var id in Ids) { if (!oldStates.TryGetState(id, out var oldState)) { // document was removed continue; } var newState = _map[id]; if (newState == oldState) { continue; } if (ignoreUnchangedContent && !newState.HasTextChanged(oldState, ignoreUnchangeableDocuments)) { continue; } yield return id; } } /// <summary> /// Returns a <see cref="DocumentId"/>s of added documents. /// </summary> public IEnumerable<DocumentId> GetAddedStateIds(TextDocumentStates<TState> oldStates) => (_ids == oldStates._ids) ? SpecializedCollections.EmptyEnumerable<DocumentId>() : Except(_ids, oldStates._map); /// <summary> /// Returns a <see cref="DocumentId"/>s of removed documents. /// </summary> public IEnumerable<DocumentId> GetRemovedStateIds(TextDocumentStates<TState> oldStates) => (_ids == oldStates._ids) ? SpecializedCollections.EmptyEnumerable<DocumentId>() : Except(oldStates._ids, _map); private static IEnumerable<DocumentId> Except(IEnumerable<DocumentId> ids, ImmutableSortedDictionary<DocumentId, TState> map) { foreach (var id in ids) { if (!map.ContainsKey(id)) { yield return id; } } } public bool HasAnyStateChanges(TextDocumentStates<TState> oldStates) => !_map.Values.SequenceEqual(oldStates._map.Values); private sealed class DocumentIdComparer : IComparer<DocumentId?> { public static readonly IComparer<DocumentId?> Instance = new DocumentIdComparer(); private DocumentIdComparer() { } public int Compare(DocumentId? x, DocumentId? y) { if (x is null) { return y is null ? 0 : -1; } else if (y is null) { return 1; } return x.Id.CompareTo(y.Id); } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/MayHaveSideEffectsVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class MayHaveSideEffectsVisitor : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private bool _mayHaveSideEffects; internal static bool MayHaveSideEffects(BoundNode node) { var visitor = new MayHaveSideEffectsVisitor(); visitor.Visit(node); return visitor._mayHaveSideEffects; } public override BoundNode Visit(BoundNode node) { if (_mayHaveSideEffects) { return null; } return base.Visit(node); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { return this.SetMayHaveSideEffects(); } public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { return this.SetMayHaveSideEffects(); } // Calls are treated as having side effects, but properties and // indexers are not. (Since this visitor is run on the bound tree // before lowering, properties are not represented as calls.) public override BoundNode VisitCall(BoundCall node) { return this.SetMayHaveSideEffects(); } public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) { return this.SetMayHaveSideEffects(); } public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { return this.SetMayHaveSideEffects(); } public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { return this.SetMayHaveSideEffects(); } public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) { return this.SetMayHaveSideEffects(); } public override BoundNode VisitObjectInitializerExpression(BoundObjectInitializerExpression node) { foreach (var initializer in node.Initializers) { // Do not treat initializer assignment as a side effect since it is // part of an object creation. In short, visit the RHS only. var expr = (initializer.Kind == BoundKind.AssignmentOperator) ? ((BoundAssignmentOperator)initializer).Right : initializer; this.Visit(expr); } return null; } private BoundNode SetMayHaveSideEffects() { _mayHaveSideEffects = true; return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class MayHaveSideEffectsVisitor : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private bool _mayHaveSideEffects; internal static bool MayHaveSideEffects(BoundNode node) { var visitor = new MayHaveSideEffectsVisitor(); visitor.Visit(node); return visitor._mayHaveSideEffects; } public override BoundNode Visit(BoundNode node) { if (_mayHaveSideEffects) { return null; } return base.Visit(node); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { return this.SetMayHaveSideEffects(); } public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { return this.SetMayHaveSideEffects(); } // Calls are treated as having side effects, but properties and // indexers are not. (Since this visitor is run on the bound tree // before lowering, properties are not represented as calls.) public override BoundNode VisitCall(BoundCall node) { return this.SetMayHaveSideEffects(); } public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) { return this.SetMayHaveSideEffects(); } public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { return this.SetMayHaveSideEffects(); } public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { return this.SetMayHaveSideEffects(); } public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) { return this.SetMayHaveSideEffects(); } public override BoundNode VisitObjectInitializerExpression(BoundObjectInitializerExpression node) { foreach (var initializer in node.Initializers) { // Do not treat initializer assignment as a side effect since it is // part of an object creation. In short, visit the RHS only. var expr = (initializer.Kind == BoundKind.AssignmentOperator) ? ((BoundAssignmentOperator)initializer).Right : initializer; this.Visit(expr); } return null; } private BoundNode SetMayHaveSideEffects() { _mayHaveSideEffects = true; return null; } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Diagnostics/MakeStatementAsynchronous/CSharpMakeStatementAsynchronousCodeFixTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeFixes.MakeStatementAsynchronous; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.MakeStatementAsynchronous { [Trait(Traits.Feature, Traits.Features.CodeActionsMakeStatementAsynchronous)] public class CSharpMakeStatementAsynchronousCodeFixTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public CSharpMakeStatementAsynchronousCodeFixTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpMakeStatementAsynchronousCodeFixProvider()); private static readonly TestParameters s_asyncStreamsFeature = new TestParameters(parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); [Fact] public async Task FixAllForeach() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<int> collection) { foreach (var i in {|FixAllInDocument:collection|}) { } foreach (var j in collection) { } } }", IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<int> collection) { await foreach (var i in collection) { } await foreach (var j in collection) { } } }", parameters: s_asyncStreamsFeature); } [Fact] public async Task FixAllForeachDeconstruction() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<(int, int)> collection) { foreach (var (i, j) in {|FixAllInDocument:collection|}) { } foreach (var (k, l) in collection) { } } }", IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<(int, int)> collection) { await foreach (var (i, j) in collection) { } await foreach (var (k, l) in collection) { } } }", parameters: s_asyncStreamsFeature); } [Fact] public async Task FixAllUsingStatement() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { using (var i = {|FixAllInDocument:disposable|}) { } using (var j = disposable) { } } }", IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { await using (var i = disposable) { } await using (var j = disposable) { } } }", parameters: s_asyncStreamsFeature); } [Fact] public async Task FixAllUsingDeclaration() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { using var i = {|FixAllInDocument:disposable|}; using var j = disposable; } }", IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { await using var i = disposable; await using var j = disposable; } }", parameters: s_asyncStreamsFeature); } [Fact] public async Task FixForeach() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<int> collection) { foreach (var i in [|collection|]) { } } }", IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<int> collection) { await foreach (var i in collection) { } } }", parameters: s_asyncStreamsFeature); } [Fact] public async Task FixForeachDeconstruction() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<(int, int)> collection) { foreach (var (i, j) in collection[||]) { } } }", IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<(int, int)> collection) { await foreach (var (i, j) in collection) { } } }", parameters: s_asyncStreamsFeature); } [Fact] public async Task FixUsingStatement() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { using (var i = disposable[||]) { } } }", IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { await using (var i = disposable) { } } }", parameters: s_asyncStreamsFeature); } [Fact] public async Task FixUsingDeclaration() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { using var i = disposable[||]; } }", IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { await using var i = disposable; } }", parameters: s_asyncStreamsFeature); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeFixes.MakeStatementAsynchronous; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.MakeStatementAsynchronous { [Trait(Traits.Feature, Traits.Features.CodeActionsMakeStatementAsynchronous)] public class CSharpMakeStatementAsynchronousCodeFixTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public CSharpMakeStatementAsynchronousCodeFixTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpMakeStatementAsynchronousCodeFixProvider()); private static readonly TestParameters s_asyncStreamsFeature = new TestParameters(parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)); [Fact] public async Task FixAllForeach() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<int> collection) { foreach (var i in {|FixAllInDocument:collection|}) { } foreach (var j in collection) { } } }", IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<int> collection) { await foreach (var i in collection) { } await foreach (var j in collection) { } } }", parameters: s_asyncStreamsFeature); } [Fact] public async Task FixAllForeachDeconstruction() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<(int, int)> collection) { foreach (var (i, j) in {|FixAllInDocument:collection|}) { } foreach (var (k, l) in collection) { } } }", IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<(int, int)> collection) { await foreach (var (i, j) in collection) { } await foreach (var (k, l) in collection) { } } }", parameters: s_asyncStreamsFeature); } [Fact] public async Task FixAllUsingStatement() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { using (var i = {|FixAllInDocument:disposable|}) { } using (var j = disposable) { } } }", IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { await using (var i = disposable) { } await using (var j = disposable) { } } }", parameters: s_asyncStreamsFeature); } [Fact] public async Task FixAllUsingDeclaration() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { using var i = {|FixAllInDocument:disposable|}; using var j = disposable; } }", IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { await using var i = disposable; await using var j = disposable; } }", parameters: s_asyncStreamsFeature); } [Fact] public async Task FixForeach() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<int> collection) { foreach (var i in [|collection|]) { } } }", IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<int> collection) { await foreach (var i in collection) { } } }", parameters: s_asyncStreamsFeature); } [Fact] public async Task FixForeachDeconstruction() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<(int, int)> collection) { foreach (var (i, j) in collection[||]) { } } }", IAsyncEnumerable + @" class Program { void M(System.Collections.Generic.IAsyncEnumerable<(int, int)> collection) { await foreach (var (i, j) in collection) { } } }", parameters: s_asyncStreamsFeature); } [Fact] public async Task FixUsingStatement() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { using (var i = disposable[||]) { } } }", IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { await using (var i = disposable) { } } }", parameters: s_asyncStreamsFeature); } [Fact] public async Task FixUsingDeclaration() { await TestInRegularAndScript1Async( IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { using var i = disposable[||]; } }", IAsyncEnumerable + @" class Program { void M(System.IAsyncDisposable disposable) { await using var i = disposable; } }", parameters: s_asyncStreamsFeature); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/ExternalAccess/FSharpTest/FSharpInlineRenameReplacementKindTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests { public class FSharpInlineRenameReplacementKindTests { public static IEnumerable<object[]> enumValues() { foreach (var number in Enum.GetValues(typeof(FSharpInlineRenameReplacementKind))) { yield return new object[] { number }; } } internal static InlineRenameReplacementKind GetExpectedInlineRenameReplacementKind(FSharpInlineRenameReplacementKind kind) { switch (kind) { case FSharpInlineRenameReplacementKind.NoConflict: { return InlineRenameReplacementKind.NoConflict; } case FSharpInlineRenameReplacementKind.ResolvedReferenceConflict: { return InlineRenameReplacementKind.ResolvedReferenceConflict; } case FSharpInlineRenameReplacementKind.ResolvedNonReferenceConflict: { return InlineRenameReplacementKind.ResolvedNonReferenceConflict; } case FSharpInlineRenameReplacementKind.UnresolvedConflict: { return InlineRenameReplacementKind.UnresolvedConflict; } case FSharpInlineRenameReplacementKind.Complexified: { return InlineRenameReplacementKind.Complexified; } default: { throw ExceptionUtilities.UnexpectedValue(kind); } } } [Theory] [MemberData(nameof(enumValues))] internal void MapsCorrectly(FSharpInlineRenameReplacementKind kind) { var actual = FSharpInlineRenameReplacementKindHelpers.ConvertTo(kind); var expected = GetExpectedInlineRenameReplacementKind(kind); Assert.Equal(expected, actual); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests { public class FSharpInlineRenameReplacementKindTests { public static IEnumerable<object[]> enumValues() { foreach (var number in Enum.GetValues(typeof(FSharpInlineRenameReplacementKind))) { yield return new object[] { number }; } } internal static InlineRenameReplacementKind GetExpectedInlineRenameReplacementKind(FSharpInlineRenameReplacementKind kind) { switch (kind) { case FSharpInlineRenameReplacementKind.NoConflict: { return InlineRenameReplacementKind.NoConflict; } case FSharpInlineRenameReplacementKind.ResolvedReferenceConflict: { return InlineRenameReplacementKind.ResolvedReferenceConflict; } case FSharpInlineRenameReplacementKind.ResolvedNonReferenceConflict: { return InlineRenameReplacementKind.ResolvedNonReferenceConflict; } case FSharpInlineRenameReplacementKind.UnresolvedConflict: { return InlineRenameReplacementKind.UnresolvedConflict; } case FSharpInlineRenameReplacementKind.Complexified: { return InlineRenameReplacementKind.Complexified; } default: { throw ExceptionUtilities.UnexpectedValue(kind); } } } [Theory] [MemberData(nameof(enumValues))] internal void MapsCorrectly(FSharpInlineRenameReplacementKind kind) { var actual = FSharpInlineRenameReplacementKindHelpers.ConvertTo(kind); var expected = GetExpectedInlineRenameReplacementKind(kind); Assert.Equal(expected, actual); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/CSharpResultProviderTestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public abstract class CSharpResultProviderTestBase : ResultProviderTestBase { public CSharpResultProviderTestBase() : this(new CSharpFormatter()) { } private CSharpResultProviderTestBase(CSharpFormatter formatter) : this(CreateDkmInspectionSession(formatter)) { } internal CSharpResultProviderTestBase(DkmInspectionSession inspectionSession, DkmInspectionContext defaultInspectionContext = null) : base(inspectionSession, defaultInspectionContext ?? CreateDkmInspectionContext(inspectionSession, DkmEvaluationFlags.None, radix: 10)) { } internal static DkmInspectionContext CreateDkmInspectionContext(DkmEvaluationFlags evalFlags) { var inspectionSession = CreateDkmInspectionSession(); return CreateDkmInspectionContext(inspectionSession, evalFlags, radix: 10); } private static DkmInspectionSession CreateDkmInspectionSession(CSharpFormatter formatter = null) { formatter = formatter ?? new CSharpFormatter(); return new DkmInspectionSession(ImmutableArray.Create<IDkmClrFormatter>(formatter), ImmutableArray.Create<IDkmClrResultProvider>(new CSharpResultProvider(formatter, formatter))); } public static Assembly GetAssembly(string source) { var comp = CSharpTestBase.CreateCompilationWithMscorlib45AndCSharp(source); return ReflectionUtilities.Load(comp.EmitToArray()); } public static Assembly GetUnsafeAssembly(string source) { var comp = CSharpTestBase.CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.UnsafeReleaseDll); return ReflectionUtilities.Load(comp.EmitToArray()); } protected static string PointerToString(IntPtr pointer) { if (Environment.Is64BitProcess) { return string.Format("0x{0:x16}", pointer.ToInt64()); } else { return string.Format("0x{0:x8}", pointer.ToInt32()); } } protected static string PointerToString(UIntPtr pointer) { if (Environment.Is64BitProcess) { return string.Format("0x{0:x16}", pointer.ToUInt64()); } else { return string.Format("0x{0:x8}", pointer.ToUInt32()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public abstract class CSharpResultProviderTestBase : ResultProviderTestBase { public CSharpResultProviderTestBase() : this(new CSharpFormatter()) { } private CSharpResultProviderTestBase(CSharpFormatter formatter) : this(CreateDkmInspectionSession(formatter)) { } internal CSharpResultProviderTestBase(DkmInspectionSession inspectionSession, DkmInspectionContext defaultInspectionContext = null) : base(inspectionSession, defaultInspectionContext ?? CreateDkmInspectionContext(inspectionSession, DkmEvaluationFlags.None, radix: 10)) { } internal static DkmInspectionContext CreateDkmInspectionContext(DkmEvaluationFlags evalFlags) { var inspectionSession = CreateDkmInspectionSession(); return CreateDkmInspectionContext(inspectionSession, evalFlags, radix: 10); } private static DkmInspectionSession CreateDkmInspectionSession(CSharpFormatter formatter = null) { formatter = formatter ?? new CSharpFormatter(); return new DkmInspectionSession(ImmutableArray.Create<IDkmClrFormatter>(formatter), ImmutableArray.Create<IDkmClrResultProvider>(new CSharpResultProvider(formatter, formatter))); } public static Assembly GetAssembly(string source) { var comp = CSharpTestBase.CreateCompilationWithMscorlib45AndCSharp(source); return ReflectionUtilities.Load(comp.EmitToArray()); } public static Assembly GetUnsafeAssembly(string source) { var comp = CSharpTestBase.CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.UnsafeReleaseDll); return ReflectionUtilities.Load(comp.EmitToArray()); } protected static string PointerToString(IntPtr pointer) { if (Environment.Is64BitProcess) { return string.Format("0x{0:x16}", pointer.ToInt64()); } else { return string.Format("0x{0:x8}", pointer.ToInt32()); } } protected static string PointerToString(UIntPtr pointer) { if (Environment.Is64BitProcess) { return string.Format("0x{0:x16}", pointer.ToUInt64()); } else { return string.Format("0x{0:x8}", pointer.ToUInt32()); } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Emitter/EditAndContinue/CSharpSymbolMatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Symbols; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class CSharpSymbolMatcher : SymbolMatcher { private readonly MatchDefs _defs; private readonly MatchSymbols _symbols; public CSharpSymbolMatcher( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, SourceAssemblySymbol sourceAssembly, EmitContext sourceContext, SourceAssemblySymbol otherAssembly, EmitContext otherContext, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> otherSynthesizedMembersOpt) { _defs = new MatchDefsToSource(sourceContext, otherContext); _symbols = new MatchSymbols(anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembersOpt, new DeepTranslator(otherAssembly.GetSpecialType(SpecialType.System_Object))); } public CSharpSymbolMatcher( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, SourceAssemblySymbol sourceAssembly, EmitContext sourceContext, PEAssemblySymbol otherAssembly) { _defs = new MatchDefsToMetadata(sourceContext, otherAssembly); _symbols = new MatchSymbols( anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembers: null, deepTranslator: null); } public override Cci.IDefinition? MapDefinition(Cci.IDefinition definition) { if (definition.GetInternalSymbol() is Symbol symbol) { return (Cci.IDefinition?)_symbols.Visit(symbol)?.GetCciAdapter(); } // TODO: this appears to be dead code, remove (https://github.com/dotnet/roslyn/issues/51595) return _defs.VisitDef(definition); } public override Cci.INamespace? MapNamespace(Cci.INamespace @namespace) { if (@namespace.GetInternalSymbol() is NamespaceSymbol symbol) { return (Cci.INamespace?)_symbols.Visit(symbol)?.GetCciAdapter(); } return null; } public override Cci.ITypeReference? MapReference(Cci.ITypeReference reference) { if (reference.GetInternalSymbol() is Symbol symbol) { return (Cci.ITypeReference?)_symbols.Visit(symbol)?.GetCciAdapter(); } return null; } internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, [NotNullWhen(true)] out string? name, out int index) => _symbols.TryGetAnonymousTypeName(template, out name, out index); private abstract class MatchDefs { private readonly EmitContext _sourceContext; private readonly ConcurrentDictionary<Cci.IDefinition, Cci.IDefinition?> _matches = new(ReferenceEqualityComparer.Instance); private IReadOnlyDictionary<string, Cci.INamespaceTypeDefinition>? _lazyTopLevelTypes; public MatchDefs(EmitContext sourceContext) { _sourceContext = sourceContext; } public Cci.IDefinition? VisitDef(Cci.IDefinition def) => _matches.GetOrAdd(def, VisitDefInternal); private Cci.IDefinition? VisitDefInternal(Cci.IDefinition def) { if (def is Cci.ITypeDefinition type) { var namespaceType = type.AsNamespaceTypeDefinition(_sourceContext); if (namespaceType != null) { return VisitNamespaceType(namespaceType); } var nestedType = type.AsNestedTypeDefinition(_sourceContext); Debug.Assert(nestedType != null); var otherContainer = (Cci.ITypeDefinition?)VisitDef(nestedType.ContainingTypeDefinition); if (otherContainer == null) { return null; } return VisitTypeMembers(otherContainer, nestedType, GetNestedTypes, (a, b) => StringOrdinalComparer.Equals(a.Name, b.Name)); } if (def is Cci.ITypeDefinitionMember member) { var otherContainer = (Cci.ITypeDefinition?)VisitDef(member.ContainingTypeDefinition); if (otherContainer == null) { return null; } if (def is Cci.IFieldDefinition field) { return VisitTypeMembers(otherContainer, field, GetFields, (a, b) => StringOrdinalComparer.Equals(a.Name, b.Name)); } } // We are only expecting types and fields currently. throw ExceptionUtilities.UnexpectedValue(def); } protected abstract IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes(); protected abstract IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def); protected abstract IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def); private Cci.INamespaceTypeDefinition? VisitNamespaceType(Cci.INamespaceTypeDefinition def) { // All generated top-level types are assumed to be in the global namespace. // However, this may be an embedded NoPIA type within a namespace. // Since we do not support edits that include references to NoPIA types // (see #855640), it's reasonable to simply drop such cases. if (!string.IsNullOrEmpty(def.NamespaceName)) { return null; } RoslynDebug.AssertNotNull(def.Name); var topLevelTypes = GetTopLevelTypesByName(); topLevelTypes.TryGetValue(def.Name, out var otherDef); return otherDef; } private IReadOnlyDictionary<string, Cci.INamespaceTypeDefinition> GetTopLevelTypesByName() { if (_lazyTopLevelTypes == null) { var typesByName = new Dictionary<string, Cci.INamespaceTypeDefinition>(StringOrdinalComparer.Instance); foreach (var type in GetTopLevelTypes()) { // All generated top-level types are assumed to be in the global namespace. if (string.IsNullOrEmpty(type.NamespaceName)) { RoslynDebug.AssertNotNull(type.Name); typesByName.Add(type.Name, type); } } Interlocked.CompareExchange(ref _lazyTopLevelTypes, typesByName, null); } return _lazyTopLevelTypes; } private static T VisitTypeMembers<T>( Cci.ITypeDefinition otherContainer, T member, Func<Cci.ITypeDefinition, IEnumerable<T>> getMembers, Func<T, T, bool> predicate) where T : class, Cci.ITypeDefinitionMember { // We could cache the members by name (see Matcher.VisitNamedTypeMembers) // but the assumption is this class is only used for types with few members // so caching is not necessary and linear search is acceptable. return getMembers(otherContainer).FirstOrDefault(otherMember => predicate(member, otherMember)); } } private sealed class MatchDefsToMetadata : MatchDefs { private readonly PEAssemblySymbol _otherAssembly; public MatchDefsToMetadata(EmitContext sourceContext, PEAssemblySymbol otherAssembly) : base(sourceContext) { _otherAssembly = otherAssembly; } protected override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes() { var builder = ArrayBuilder<Cci.INamespaceTypeDefinition>.GetInstance(); GetTopLevelTypes(builder, _otherAssembly.GlobalNamespace); return builder.ToArrayAndFree(); } protected override IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def) { var type = (PENamedTypeSymbol)def; return type.GetTypeMembers().Cast<Cci.INestedTypeDefinition>(); } protected override IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def) { var type = (PENamedTypeSymbol)def; return type.GetFieldsToEmit().Cast<Cci.IFieldDefinition>(); } private static void GetTopLevelTypes(ArrayBuilder<Cci.INamespaceTypeDefinition> builder, NamespaceSymbol @namespace) { foreach (var member in @namespace.GetMembers()) { if (member.Kind == SymbolKind.Namespace) { GetTopLevelTypes(builder, (NamespaceSymbol)member); } else { builder.Add((Cci.INamespaceTypeDefinition)member.GetCciAdapter()); } } } } private sealed class MatchDefsToSource : MatchDefs { private readonly EmitContext _otherContext; public MatchDefsToSource( EmitContext sourceContext, EmitContext otherContext) : base(sourceContext) { _otherContext = otherContext; } protected override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes() { return _otherContext.Module.GetTopLevelTypeDefinitions(_otherContext); } protected override IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def) { return def.GetNestedTypes(_otherContext); } protected override IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def) { return def.GetFields(_otherContext); } } private sealed class MatchSymbols : CSharpSymbolVisitor<Symbol?> { private readonly IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> _anonymousTypeMap; private readonly SourceAssemblySymbol _sourceAssembly; // metadata or source assembly: private readonly AssemblySymbol _otherAssembly; /// <summary> /// Members that are not listed directly on their containing type or namespace symbol as they were synthesized in a lowering phase, /// after the symbol has been created. /// </summary> private readonly ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>>? _otherSynthesizedMembers; private readonly SymbolComparer _comparer; private readonly ConcurrentDictionary<Symbol, Symbol?> _matches = new(ReferenceEqualityComparer.Instance); /// <summary> /// A cache of members per type, populated when the first member for a given /// type is needed. Within each type, members are indexed by name. The reason /// for caching, and indexing by name, is to avoid searching sequentially /// through all members of a given kind each time a member is matched. /// </summary> private readonly ConcurrentDictionary<ISymbolInternal, IReadOnlyDictionary<string, ImmutableArray<ISymbolInternal>>> _otherMembers = new(ReferenceEqualityComparer.Instance); public MatchSymbols( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, SourceAssemblySymbol sourceAssembly, AssemblySymbol otherAssembly, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>>? otherSynthesizedMembers, DeepTranslator? deepTranslator) { _anonymousTypeMap = anonymousTypeMap; _sourceAssembly = sourceAssembly; _otherAssembly = otherAssembly; _otherSynthesizedMembers = otherSynthesizedMembers; _comparer = new SymbolComparer(this, deepTranslator); } internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol type, [NotNullWhen(true)] out string? name, out int index) { if (TryFindAnonymousType(type, out var otherType)) { name = otherType.Name; index = otherType.UniqueIndex; return true; } name = null; index = -1; return false; } public override Symbol DefaultVisit(Symbol symbol) { // Symbol should have been handled elsewhere. throw ExceptionUtilities.Unreachable; } public override Symbol? Visit(Symbol symbol) { Debug.Assert((object)symbol.ContainingAssembly != (object)_otherAssembly); // Add an entry for the match, even if there is no match, to avoid // matching the same symbol unsuccessfully multiple times. return _matches.GetOrAdd(symbol, base.Visit); } public override Symbol? VisitArrayType(ArrayTypeSymbol symbol) { var otherElementType = (TypeSymbol?)Visit(symbol.ElementType); if (otherElementType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } var otherModifiers = VisitCustomModifiers(symbol.ElementTypeWithAnnotations.CustomModifiers); if (symbol.IsSZArray) { return ArrayTypeSymbol.CreateSZArray(_otherAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(otherElementType, otherModifiers)); } return ArrayTypeSymbol.CreateMDArray(_otherAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(otherElementType, otherModifiers), symbol.Rank, symbol.Sizes, symbol.LowerBounds); } public override Symbol? VisitEvent(EventSymbol symbol) => VisitNamedTypeMember(symbol, AreEventsEqual); public override Symbol? VisitField(FieldSymbol symbol) => VisitNamedTypeMember(symbol, AreFieldsEqual); public override Symbol? VisitMethod(MethodSymbol symbol) { // Not expecting constructed method. Debug.Assert(symbol.IsDefinition); return VisitNamedTypeMember(symbol, AreMethodsEqual); } public override Symbol? VisitModule(ModuleSymbol module) { var otherAssembly = (AssemblySymbol?)Visit(module.ContainingAssembly); if (otherAssembly is null) { return null; } // manifest module: if (module.Ordinal == 0) { return otherAssembly.Modules[0]; } // match non-manifest module by name: for (int i = 1; i < otherAssembly.Modules.Length; i++) { var otherModule = otherAssembly.Modules[i]; // use case sensitive comparison -- modules whose names differ in casing are considered distinct: if (StringComparer.Ordinal.Equals(otherModule.Name, module.Name)) { return otherModule; } } return null; } public override Symbol? VisitAssembly(AssemblySymbol assembly) { if (assembly.IsLinked) { return assembly; } // When we map synthesized symbols from previous generations to the latest compilation // we might encounter a symbol that is defined in arbitrary preceding generation, // not just the immediately preceding generation. If the source assembly uses time-based // versioning assemblies of preceding generations might differ in their version number. if (IdentityEqualIgnoringVersionWildcard(assembly, _sourceAssembly)) { return _otherAssembly; } // find a referenced assembly with the same source identity (modulo assembly version patterns): foreach (var otherReferencedAssembly in _otherAssembly.Modules[0].ReferencedAssemblySymbols) { if (IdentityEqualIgnoringVersionWildcard(assembly, otherReferencedAssembly)) { return otherReferencedAssembly; } } return null; } private static bool IdentityEqualIgnoringVersionWildcard(AssemblySymbol left, AssemblySymbol right) { var leftIdentity = left.Identity; var rightIdentity = right.Identity; return AssemblyIdentityComparer.SimpleNameComparer.Equals(leftIdentity.Name, rightIdentity.Name) && (left.AssemblyVersionPattern ?? leftIdentity.Version).Equals(right.AssemblyVersionPattern ?? rightIdentity.Version) && AssemblyIdentity.EqualIgnoringNameAndVersion(leftIdentity, rightIdentity); } public override Symbol? VisitNamespace(NamespaceSymbol @namespace) { var otherContainer = Visit(@namespace.ContainingSymbol); RoslynDebug.AssertNotNull(otherContainer); switch (otherContainer.Kind) { case SymbolKind.NetModule: Debug.Assert(@namespace.IsGlobalNamespace); return ((ModuleSymbol)otherContainer).GlobalNamespace; case SymbolKind.Namespace: return FindMatchingMember(otherContainer, @namespace, AreNamespacesEqual); default: throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind); } } public override Symbol VisitDynamicType(DynamicTypeSymbol symbol) { return _otherAssembly.GetSpecialType(SpecialType.System_Object); } public override Symbol? VisitNamedType(NamedTypeSymbol sourceType) { var originalDef = sourceType.OriginalDefinition; if ((object)originalDef != (object)sourceType) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var typeArguments = sourceType.GetAllTypeArguments(ref discardedUseSiteInfo); var otherDef = (NamedTypeSymbol?)Visit(originalDef); if (otherDef is null) { return null; } var otherTypeParameters = otherDef.GetAllTypeParameters(); bool translationFailed = false; var otherTypeArguments = typeArguments.SelectAsArray((t, v) => { var newType = (TypeSymbol?)v.Visit(t.Type); if (newType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. translationFailed = true; newType = t.Type; } return t.WithTypeAndModifiers(newType, v.VisitCustomModifiers(t.CustomModifiers)); }, this); if (translationFailed) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } // TODO: LambdaFrame has alpha renamed type parameters, should we rather fix that? var typeMap = new TypeMap(otherTypeParameters, otherTypeArguments, allowAlpha: true); return typeMap.SubstituteNamedType(otherDef); } Debug.Assert(sourceType.IsDefinition); var otherContainer = this.Visit(sourceType.ContainingSymbol); // Containing type will be missing from other assembly // if the type was added in the (newer) source assembly. if (otherContainer is null) { return null; } switch (otherContainer.Kind) { case SymbolKind.Namespace: if (sourceType is AnonymousTypeManager.AnonymousTypeTemplateSymbol template) { Debug.Assert((object)otherContainer == (object)_otherAssembly.GlobalNamespace); TryFindAnonymousType(template, out var value); return (NamedTypeSymbol?)value.Type?.GetInternalSymbol(); } if (sourceType.IsAnonymousType) { return Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(sourceType)); } return FindMatchingMember(otherContainer, sourceType, AreNamedTypesEqual); case SymbolKind.NamedType: return FindMatchingMember(otherContainer, sourceType, AreNamedTypesEqual); default: throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind); } } public override Symbol VisitParameter(ParameterSymbol parameter) { // Should never reach here. Should be matched as a result of matching the container. throw ExceptionUtilities.Unreachable; } public override Symbol? VisitPointerType(PointerTypeSymbol symbol) { var otherPointedAtType = (TypeSymbol?)Visit(symbol.PointedAtType); if (otherPointedAtType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } var otherModifiers = VisitCustomModifiers(symbol.PointedAtTypeWithAnnotations.CustomModifiers); return new PointerTypeSymbol(symbol.PointedAtTypeWithAnnotations.WithTypeAndModifiers(otherPointedAtType, otherModifiers)); } public override Symbol? VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { var sig = symbol.Signature; var otherReturnType = (TypeSymbol?)Visit(sig.ReturnType); if (otherReturnType is null) { return null; } var otherRefCustomModifiers = VisitCustomModifiers(sig.RefCustomModifiers); var otherReturnTypeWithAnnotations = sig.ReturnTypeWithAnnotations.WithTypeAndModifiers(otherReturnType, VisitCustomModifiers(sig.ReturnTypeWithAnnotations.CustomModifiers)); var otherParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; ImmutableArray<ImmutableArray<CustomModifier>> otherParamRefCustomModifiers = default; if (sig.ParameterCount > 0) { var otherParamsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(sig.ParameterCount); var otherParamRefCustomModifiersBuilder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(sig.ParameterCount); foreach (var param in sig.Parameters) { var otherType = (TypeSymbol?)Visit(param.Type); if (otherType is null) { otherParamsBuilder.Free(); otherParamRefCustomModifiersBuilder.Free(); return null; } otherParamRefCustomModifiersBuilder.Add(VisitCustomModifiers(param.RefCustomModifiers)); otherParamsBuilder.Add(param.TypeWithAnnotations.WithTypeAndModifiers(otherType, VisitCustomModifiers(param.TypeWithAnnotations.CustomModifiers))); } otherParameterTypes = otherParamsBuilder.ToImmutableAndFree(); otherParamRefCustomModifiers = otherParamRefCustomModifiersBuilder.ToImmutableAndFree(); } return symbol.SubstituteTypeSymbol(otherReturnTypeWithAnnotations, otherParameterTypes, otherRefCustomModifiers, otherParamRefCustomModifiers); } public override Symbol? VisitProperty(PropertySymbol symbol) => VisitNamedTypeMember(symbol, ArePropertiesEqual); public override Symbol VisitTypeParameter(TypeParameterSymbol symbol) { if (symbol is IndexedTypeParameterSymbol indexed) { return indexed; } var otherContainer = Visit(symbol.ContainingSymbol); RoslynDebug.AssertNotNull(otherContainer); var otherTypeParameters = otherContainer.Kind switch { SymbolKind.NamedType or SymbolKind.ErrorType => ((NamedTypeSymbol)otherContainer).TypeParameters, SymbolKind.Method => ((MethodSymbol)otherContainer).TypeParameters, _ => throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind), }; return otherTypeParameters[symbol.Ordinal]; } private ImmutableArray<CustomModifier> VisitCustomModifiers(ImmutableArray<CustomModifier> modifiers) { return modifiers.SelectAsArray(VisitCustomModifier); } private CustomModifier VisitCustomModifier(CustomModifier modifier) { var type = (NamedTypeSymbol?)Visit(((CSharpCustomModifier)modifier).ModifierSymbol); RoslynDebug.AssertNotNull(type); return modifier.IsOptional ? CSharpCustomModifier.CreateOptional(type) : CSharpCustomModifier.CreateRequired(type); } internal bool TryFindAnonymousType(AnonymousTypeManager.AnonymousTypeTemplateSymbol type, out AnonymousTypeValue otherType) { Debug.Assert((object)type.ContainingSymbol == (object)_sourceAssembly.GlobalNamespace); return _anonymousTypeMap.TryGetValue(type.GetAnonymousTypeKey(), out otherType); } private Symbol? VisitNamedTypeMember<T>(T member, Func<T, T, bool> predicate) where T : Symbol { var otherType = (NamedTypeSymbol?)Visit(member.ContainingType); // Containing type may be null for synthesized // types such as iterators. if (otherType is null) { return null; } return FindMatchingMember(otherType, member, predicate); } private T? FindMatchingMember<T>(ISymbolInternal otherTypeOrNamespace, T sourceMember, Func<T, T, bool> predicate) where T : Symbol { Debug.Assert(!string.IsNullOrEmpty(sourceMember.MetadataName)); var otherMembersByName = _otherMembers.GetOrAdd(otherTypeOrNamespace, GetAllEmittedMembers); if (otherMembersByName.TryGetValue(sourceMember.MetadataName, out var otherMembers)) { foreach (var otherMember in otherMembers) { if (otherMember is T other && predicate(sourceMember, other)) { return other; } } } return null; } private bool AreArrayTypesEqual(ArrayTypeSymbol type, ArrayTypeSymbol other) { // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.ElementTypeWithAnnotations.CustomModifiers.IsEmpty); Debug.Assert(other.ElementTypeWithAnnotations.CustomModifiers.IsEmpty); return type.HasSameShapeAs(other) && AreTypesEqual(type.ElementType, other.ElementType); } private bool AreEventsEqual(EventSymbol @event, EventSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(@event.Name, other.Name)); return _comparer.Equals(@event.Type, other.Type); } private bool AreFieldsEqual(FieldSymbol field, FieldSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(field.Name, other.Name)); return _comparer.Equals(field.Type, other.Type); } private bool AreMethodsEqual(MethodSymbol method, MethodSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(method.Name, other.Name)); Debug.Assert(method.IsDefinition); Debug.Assert(other.IsDefinition); method = SubstituteTypeParameters(method); other = SubstituteTypeParameters(other); return _comparer.Equals(method.ReturnType, other.ReturnType) && method.RefKind.Equals(other.RefKind) && method.Parameters.SequenceEqual(other.Parameters, AreParametersEqual) && method.TypeParameters.SequenceEqual(other.TypeParameters, AreTypesEqual); } private static MethodSymbol SubstituteTypeParameters(MethodSymbol method) { Debug.Assert(method.IsDefinition); var typeParameters = method.TypeParameters; int n = typeParameters.Length; if (n == 0) { return method; } return method.Construct(IndexedTypeParameterSymbol.Take(n)); } private bool AreNamedTypesEqual(NamedTypeSymbol type, NamedTypeSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(type.MetadataName, other.MetadataName)); // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); Debug.Assert(other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); return type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.SequenceEqual(other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, AreTypesEqual); } private bool AreNamespacesEqual(NamespaceSymbol @namespace, NamespaceSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(@namespace.MetadataName, other.MetadataName)); return true; } private bool AreParametersEqual(ParameterSymbol parameter, ParameterSymbol other) { Debug.Assert(parameter.Ordinal == other.Ordinal); return StringOrdinalComparer.Equals(parameter.MetadataName, other.MetadataName) && (parameter.RefKind == other.RefKind) && _comparer.Equals(parameter.Type, other.Type); } private bool ArePointerTypesEqual(PointerTypeSymbol type, PointerTypeSymbol other) { // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.PointedAtTypeWithAnnotations.CustomModifiers.IsEmpty); Debug.Assert(other.PointedAtTypeWithAnnotations.CustomModifiers.IsEmpty); return AreTypesEqual(type.PointedAtType, other.PointedAtType); } private bool AreFunctionPointerTypesEqual(FunctionPointerTypeSymbol type, FunctionPointerTypeSymbol other) { var sig = type.Signature; var otherSig = other.Signature; ValidateFunctionPointerParamOrReturn(sig.ReturnTypeWithAnnotations, sig.RefKind, sig.RefCustomModifiers, allowOut: false); ValidateFunctionPointerParamOrReturn(otherSig.ReturnTypeWithAnnotations, otherSig.RefKind, otherSig.RefCustomModifiers, allowOut: false); if (sig.RefKind != otherSig.RefKind || !AreTypesEqual(sig.ReturnTypeWithAnnotations, otherSig.ReturnTypeWithAnnotations)) { return false; } return sig.Parameters.SequenceEqual(otherSig.Parameters, AreFunctionPointerParametersEqual); } private bool AreFunctionPointerParametersEqual(ParameterSymbol param, ParameterSymbol otherParam) { ValidateFunctionPointerParamOrReturn(param.TypeWithAnnotations, param.RefKind, param.RefCustomModifiers, allowOut: true); ValidateFunctionPointerParamOrReturn(otherParam.TypeWithAnnotations, otherParam.RefKind, otherParam.RefCustomModifiers, allowOut: true); return param.RefKind == otherParam.RefKind && AreTypesEqual(param.TypeWithAnnotations, otherParam.TypeWithAnnotations); } [Conditional("DEBUG")] private static void ValidateFunctionPointerParamOrReturn(TypeWithAnnotations type, RefKind refKind, ImmutableArray<CustomModifier> refCustomModifiers, bool allowOut) { Debug.Assert(type.CustomModifiers.IsEmpty); Debug.Assert(verifyRefModifiers(refCustomModifiers, refKind, allowOut)); static bool verifyRefModifiers(ImmutableArray<CustomModifier> modifiers, RefKind refKind, bool allowOut) { Debug.Assert(RefKind.RefReadOnly == RefKind.In); switch (refKind) { case RefKind.RefReadOnly: case RefKind.Out when allowOut: return modifiers.Length == 1; default: return modifiers.IsEmpty; } } } private bool ArePropertiesEqual(PropertySymbol property, PropertySymbol other) { Debug.Assert(StringOrdinalComparer.Equals(property.MetadataName, other.MetadataName)); return _comparer.Equals(property.Type, other.Type) && property.RefKind.Equals(other.RefKind) && property.Parameters.SequenceEqual(other.Parameters, AreParametersEqual); } private static bool AreTypeParametersEqual(TypeParameterSymbol type, TypeParameterSymbol other) { Debug.Assert(type.Ordinal == other.Ordinal); Debug.Assert(StringOrdinalComparer.Equals(type.Name, other.Name)); // Comparing constraints is unnecessary: two methods cannot differ by // constraints alone and changing the signature of a method is a rude // edit. Furthermore, comparing constraint types might lead to a cycle. Debug.Assert(type.HasConstructorConstraint == other.HasConstructorConstraint); Debug.Assert(type.HasValueTypeConstraint == other.HasValueTypeConstraint); Debug.Assert(type.HasUnmanagedTypeConstraint == other.HasUnmanagedTypeConstraint); Debug.Assert(type.HasReferenceTypeConstraint == other.HasReferenceTypeConstraint); Debug.Assert(type.ConstraintTypesNoUseSiteDiagnostics.Length == other.ConstraintTypesNoUseSiteDiagnostics.Length); return true; } private bool AreTypesEqual(TypeWithAnnotations type, TypeWithAnnotations other) { Debug.Assert(type.CustomModifiers.IsDefaultOrEmpty); Debug.Assert(other.CustomModifiers.IsDefaultOrEmpty); return AreTypesEqual(type.Type, other.Type); } private bool AreTypesEqual(TypeSymbol type, TypeSymbol other) { if (type.Kind != other.Kind) { return false; } switch (type.Kind) { case SymbolKind.ArrayType: return AreArrayTypesEqual((ArrayTypeSymbol)type, (ArrayTypeSymbol)other); case SymbolKind.PointerType: return ArePointerTypesEqual((PointerTypeSymbol)type, (PointerTypeSymbol)other); case SymbolKind.FunctionPointerType: return AreFunctionPointerTypesEqual((FunctionPointerTypeSymbol)type, (FunctionPointerTypeSymbol)other); case SymbolKind.NamedType: case SymbolKind.ErrorType: return AreNamedTypesEqual((NamedTypeSymbol)type, (NamedTypeSymbol)other); case SymbolKind.TypeParameter: return AreTypeParametersEqual((TypeParameterSymbol)type, (TypeParameterSymbol)other); default: throw ExceptionUtilities.UnexpectedValue(type.Kind); } } private IReadOnlyDictionary<string, ImmutableArray<ISymbolInternal>> GetAllEmittedMembers(ISymbolInternal symbol) { var members = ArrayBuilder<ISymbolInternal>.GetInstance(); if (symbol.Kind == SymbolKind.NamedType) { var type = (NamedTypeSymbol)symbol; members.AddRange(type.GetEventsToEmit()); members.AddRange(type.GetFieldsToEmit()); members.AddRange(type.GetMethodsToEmit()); members.AddRange(type.GetTypeMembers()); members.AddRange(type.GetPropertiesToEmit()); } else { members.AddRange(((NamespaceSymbol)symbol).GetMembers()); } if (_otherSynthesizedMembers != null && _otherSynthesizedMembers.TryGetValue(symbol, out var synthesizedMembers)) { members.AddRange(synthesizedMembers); } var result = members.ToDictionary(s => s.MetadataName, StringOrdinalComparer.Instance); members.Free(); return result; } private sealed class SymbolComparer { private readonly MatchSymbols _matcher; private readonly DeepTranslator? _deepTranslator; public SymbolComparer(MatchSymbols matcher, DeepTranslator? deepTranslator) { Debug.Assert(matcher != null); _matcher = matcher; _deepTranslator = deepTranslator; } public bool Equals(TypeSymbol source, TypeSymbol other) { var visitedSource = (TypeSymbol?)_matcher.Visit(source); var visitedOther = (_deepTranslator != null) ? (TypeSymbol)_deepTranslator.Visit(other) : other; return visitedSource?.Equals(visitedOther, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) == true; } } } internal sealed class DeepTranslator : CSharpSymbolVisitor<Symbol> { private readonly ConcurrentDictionary<Symbol, Symbol> _matches; private readonly NamedTypeSymbol _systemObject; public DeepTranslator(NamedTypeSymbol systemObject) { _matches = new ConcurrentDictionary<Symbol, Symbol>(ReferenceEqualityComparer.Instance); _systemObject = systemObject; } public override Symbol DefaultVisit(Symbol symbol) { // Symbol should have been handled elsewhere. throw ExceptionUtilities.Unreachable; } public override Symbol Visit(Symbol symbol) { return _matches.GetOrAdd(symbol, base.Visit(symbol)); } public override Symbol VisitArrayType(ArrayTypeSymbol symbol) { var translatedElementType = (TypeSymbol)this.Visit(symbol.ElementType); var translatedModifiers = VisitCustomModifiers(symbol.ElementTypeWithAnnotations.CustomModifiers); if (symbol.IsSZArray) { return ArrayTypeSymbol.CreateSZArray(symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(translatedElementType, translatedModifiers)); } return ArrayTypeSymbol.CreateMDArray(symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(translatedElementType, translatedModifiers), symbol.Rank, symbol.Sizes, symbol.LowerBounds); } public override Symbol VisitDynamicType(DynamicTypeSymbol symbol) { return _systemObject; } public override Symbol VisitNamedType(NamedTypeSymbol type) { var originalDef = type.OriginalDefinition; if ((object)originalDef != type) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var translatedTypeArguments = type.GetAllTypeArguments(ref discardedUseSiteInfo).SelectAsArray((t, v) => t.WithTypeAndModifiers((TypeSymbol)v.Visit(t.Type), v.VisitCustomModifiers(t.CustomModifiers)), this); var translatedOriginalDef = (NamedTypeSymbol)this.Visit(originalDef); var typeMap = new TypeMap(translatedOriginalDef.GetAllTypeParameters(), translatedTypeArguments, allowAlpha: true); return typeMap.SubstituteNamedType(translatedOriginalDef); } Debug.Assert(type.IsDefinition); if (type.IsAnonymousType) { return this.Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(type)); } return type; } public override Symbol VisitPointerType(PointerTypeSymbol symbol) { var translatedPointedAtType = (TypeSymbol)this.Visit(symbol.PointedAtType); var translatedModifiers = VisitCustomModifiers(symbol.PointedAtTypeWithAnnotations.CustomModifiers); return new PointerTypeSymbol(symbol.PointedAtTypeWithAnnotations.WithTypeAndModifiers(translatedPointedAtType, translatedModifiers)); } public override Symbol VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { var sig = symbol.Signature; var translatedReturnType = (TypeSymbol)Visit(sig.ReturnType); var translatedReturnTypeWithAnnotations = sig.ReturnTypeWithAnnotations.WithTypeAndModifiers(translatedReturnType, VisitCustomModifiers(sig.ReturnTypeWithAnnotations.CustomModifiers)); var translatedRefCustomModifiers = VisitCustomModifiers(sig.RefCustomModifiers); var translatedParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; ImmutableArray<ImmutableArray<CustomModifier>> translatedParamRefCustomModifiers = default; if (sig.ParameterCount > 0) { var translatedParamsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(sig.ParameterCount); var translatedParamRefCustomModifiersBuilder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(sig.ParameterCount); foreach (var param in sig.Parameters) { var translatedParamType = (TypeSymbol)Visit(param.Type); translatedParamsBuilder.Add(param.TypeWithAnnotations.WithTypeAndModifiers(translatedParamType, VisitCustomModifiers(param.TypeWithAnnotations.CustomModifiers))); translatedParamRefCustomModifiersBuilder.Add(VisitCustomModifiers(param.RefCustomModifiers)); } translatedParameterTypes = translatedParamsBuilder.ToImmutableAndFree(); translatedParamRefCustomModifiers = translatedParamRefCustomModifiersBuilder.ToImmutableAndFree(); } return symbol.SubstituteTypeSymbol(translatedReturnTypeWithAnnotations, translatedParameterTypes, translatedRefCustomModifiers, translatedParamRefCustomModifiers); } public override Symbol VisitTypeParameter(TypeParameterSymbol symbol) { return symbol; } private ImmutableArray<CustomModifier> VisitCustomModifiers(ImmutableArray<CustomModifier> modifiers) { return modifiers.SelectAsArray(VisitCustomModifier); } private CustomModifier VisitCustomModifier(CustomModifier modifier) { var translatedType = (NamedTypeSymbol)this.Visit(((CSharpCustomModifier)modifier).ModifierSymbol); Debug.Assert((object)translatedType != null); return modifier.IsOptional ? CSharpCustomModifier.CreateOptional(translatedType) : CSharpCustomModifier.CreateRequired(translatedType); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Symbols; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class CSharpSymbolMatcher : SymbolMatcher { private readonly MatchDefs _defs; private readonly MatchSymbols _symbols; public CSharpSymbolMatcher( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, SourceAssemblySymbol sourceAssembly, EmitContext sourceContext, SourceAssemblySymbol otherAssembly, EmitContext otherContext, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> otherSynthesizedMembersOpt) { _defs = new MatchDefsToSource(sourceContext, otherContext); _symbols = new MatchSymbols(anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembersOpt, new DeepTranslator(otherAssembly.GetSpecialType(SpecialType.System_Object))); } public CSharpSymbolMatcher( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, SourceAssemblySymbol sourceAssembly, EmitContext sourceContext, PEAssemblySymbol otherAssembly) { _defs = new MatchDefsToMetadata(sourceContext, otherAssembly); _symbols = new MatchSymbols( anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembers: null, deepTranslator: null); } public override Cci.IDefinition? MapDefinition(Cci.IDefinition definition) { if (definition.GetInternalSymbol() is Symbol symbol) { return (Cci.IDefinition?)_symbols.Visit(symbol)?.GetCciAdapter(); } // TODO: this appears to be dead code, remove (https://github.com/dotnet/roslyn/issues/51595) return _defs.VisitDef(definition); } public override Cci.INamespace? MapNamespace(Cci.INamespace @namespace) { if (@namespace.GetInternalSymbol() is NamespaceSymbol symbol) { return (Cci.INamespace?)_symbols.Visit(symbol)?.GetCciAdapter(); } return null; } public override Cci.ITypeReference? MapReference(Cci.ITypeReference reference) { if (reference.GetInternalSymbol() is Symbol symbol) { return (Cci.ITypeReference?)_symbols.Visit(symbol)?.GetCciAdapter(); } return null; } internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, [NotNullWhen(true)] out string? name, out int index) => _symbols.TryGetAnonymousTypeName(template, out name, out index); private abstract class MatchDefs { private readonly EmitContext _sourceContext; private readonly ConcurrentDictionary<Cci.IDefinition, Cci.IDefinition?> _matches = new(ReferenceEqualityComparer.Instance); private IReadOnlyDictionary<string, Cci.INamespaceTypeDefinition>? _lazyTopLevelTypes; public MatchDefs(EmitContext sourceContext) { _sourceContext = sourceContext; } public Cci.IDefinition? VisitDef(Cci.IDefinition def) => _matches.GetOrAdd(def, VisitDefInternal); private Cci.IDefinition? VisitDefInternal(Cci.IDefinition def) { if (def is Cci.ITypeDefinition type) { var namespaceType = type.AsNamespaceTypeDefinition(_sourceContext); if (namespaceType != null) { return VisitNamespaceType(namespaceType); } var nestedType = type.AsNestedTypeDefinition(_sourceContext); Debug.Assert(nestedType != null); var otherContainer = (Cci.ITypeDefinition?)VisitDef(nestedType.ContainingTypeDefinition); if (otherContainer == null) { return null; } return VisitTypeMembers(otherContainer, nestedType, GetNestedTypes, (a, b) => StringOrdinalComparer.Equals(a.Name, b.Name)); } if (def is Cci.ITypeDefinitionMember member) { var otherContainer = (Cci.ITypeDefinition?)VisitDef(member.ContainingTypeDefinition); if (otherContainer == null) { return null; } if (def is Cci.IFieldDefinition field) { return VisitTypeMembers(otherContainer, field, GetFields, (a, b) => StringOrdinalComparer.Equals(a.Name, b.Name)); } } // We are only expecting types and fields currently. throw ExceptionUtilities.UnexpectedValue(def); } protected abstract IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes(); protected abstract IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def); protected abstract IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def); private Cci.INamespaceTypeDefinition? VisitNamespaceType(Cci.INamespaceTypeDefinition def) { // All generated top-level types are assumed to be in the global namespace. // However, this may be an embedded NoPIA type within a namespace. // Since we do not support edits that include references to NoPIA types // (see #855640), it's reasonable to simply drop such cases. if (!string.IsNullOrEmpty(def.NamespaceName)) { return null; } RoslynDebug.AssertNotNull(def.Name); var topLevelTypes = GetTopLevelTypesByName(); topLevelTypes.TryGetValue(def.Name, out var otherDef); return otherDef; } private IReadOnlyDictionary<string, Cci.INamespaceTypeDefinition> GetTopLevelTypesByName() { if (_lazyTopLevelTypes == null) { var typesByName = new Dictionary<string, Cci.INamespaceTypeDefinition>(StringOrdinalComparer.Instance); foreach (var type in GetTopLevelTypes()) { // All generated top-level types are assumed to be in the global namespace. if (string.IsNullOrEmpty(type.NamespaceName)) { RoslynDebug.AssertNotNull(type.Name); typesByName.Add(type.Name, type); } } Interlocked.CompareExchange(ref _lazyTopLevelTypes, typesByName, null); } return _lazyTopLevelTypes; } private static T VisitTypeMembers<T>( Cci.ITypeDefinition otherContainer, T member, Func<Cci.ITypeDefinition, IEnumerable<T>> getMembers, Func<T, T, bool> predicate) where T : class, Cci.ITypeDefinitionMember { // We could cache the members by name (see Matcher.VisitNamedTypeMembers) // but the assumption is this class is only used for types with few members // so caching is not necessary and linear search is acceptable. return getMembers(otherContainer).FirstOrDefault(otherMember => predicate(member, otherMember)); } } private sealed class MatchDefsToMetadata : MatchDefs { private readonly PEAssemblySymbol _otherAssembly; public MatchDefsToMetadata(EmitContext sourceContext, PEAssemblySymbol otherAssembly) : base(sourceContext) { _otherAssembly = otherAssembly; } protected override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes() { var builder = ArrayBuilder<Cci.INamespaceTypeDefinition>.GetInstance(); GetTopLevelTypes(builder, _otherAssembly.GlobalNamespace); return builder.ToArrayAndFree(); } protected override IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def) { var type = (PENamedTypeSymbol)def; return type.GetTypeMembers().Cast<Cci.INestedTypeDefinition>(); } protected override IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def) { var type = (PENamedTypeSymbol)def; return type.GetFieldsToEmit().Cast<Cci.IFieldDefinition>(); } private static void GetTopLevelTypes(ArrayBuilder<Cci.INamespaceTypeDefinition> builder, NamespaceSymbol @namespace) { foreach (var member in @namespace.GetMembers()) { if (member.Kind == SymbolKind.Namespace) { GetTopLevelTypes(builder, (NamespaceSymbol)member); } else { builder.Add((Cci.INamespaceTypeDefinition)member.GetCciAdapter()); } } } } private sealed class MatchDefsToSource : MatchDefs { private readonly EmitContext _otherContext; public MatchDefsToSource( EmitContext sourceContext, EmitContext otherContext) : base(sourceContext) { _otherContext = otherContext; } protected override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes() { return _otherContext.Module.GetTopLevelTypeDefinitions(_otherContext); } protected override IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def) { return def.GetNestedTypes(_otherContext); } protected override IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def) { return def.GetFields(_otherContext); } } private sealed class MatchSymbols : CSharpSymbolVisitor<Symbol?> { private readonly IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> _anonymousTypeMap; private readonly SourceAssemblySymbol _sourceAssembly; // metadata or source assembly: private readonly AssemblySymbol _otherAssembly; /// <summary> /// Members that are not listed directly on their containing type or namespace symbol as they were synthesized in a lowering phase, /// after the symbol has been created. /// </summary> private readonly ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>>? _otherSynthesizedMembers; private readonly SymbolComparer _comparer; private readonly ConcurrentDictionary<Symbol, Symbol?> _matches = new(ReferenceEqualityComparer.Instance); /// <summary> /// A cache of members per type, populated when the first member for a given /// type is needed. Within each type, members are indexed by name. The reason /// for caching, and indexing by name, is to avoid searching sequentially /// through all members of a given kind each time a member is matched. /// </summary> private readonly ConcurrentDictionary<ISymbolInternal, IReadOnlyDictionary<string, ImmutableArray<ISymbolInternal>>> _otherMembers = new(ReferenceEqualityComparer.Instance); public MatchSymbols( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, SourceAssemblySymbol sourceAssembly, AssemblySymbol otherAssembly, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>>? otherSynthesizedMembers, DeepTranslator? deepTranslator) { _anonymousTypeMap = anonymousTypeMap; _sourceAssembly = sourceAssembly; _otherAssembly = otherAssembly; _otherSynthesizedMembers = otherSynthesizedMembers; _comparer = new SymbolComparer(this, deepTranslator); } internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol type, [NotNullWhen(true)] out string? name, out int index) { if (TryFindAnonymousType(type, out var otherType)) { name = otherType.Name; index = otherType.UniqueIndex; return true; } name = null; index = -1; return false; } public override Symbol DefaultVisit(Symbol symbol) { // Symbol should have been handled elsewhere. throw ExceptionUtilities.Unreachable; } public override Symbol? Visit(Symbol symbol) { Debug.Assert((object)symbol.ContainingAssembly != (object)_otherAssembly); // Add an entry for the match, even if there is no match, to avoid // matching the same symbol unsuccessfully multiple times. return _matches.GetOrAdd(symbol, base.Visit); } public override Symbol? VisitArrayType(ArrayTypeSymbol symbol) { var otherElementType = (TypeSymbol?)Visit(symbol.ElementType); if (otherElementType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } var otherModifiers = VisitCustomModifiers(symbol.ElementTypeWithAnnotations.CustomModifiers); if (symbol.IsSZArray) { return ArrayTypeSymbol.CreateSZArray(_otherAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(otherElementType, otherModifiers)); } return ArrayTypeSymbol.CreateMDArray(_otherAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(otherElementType, otherModifiers), symbol.Rank, symbol.Sizes, symbol.LowerBounds); } public override Symbol? VisitEvent(EventSymbol symbol) => VisitNamedTypeMember(symbol, AreEventsEqual); public override Symbol? VisitField(FieldSymbol symbol) => VisitNamedTypeMember(symbol, AreFieldsEqual); public override Symbol? VisitMethod(MethodSymbol symbol) { // Not expecting constructed method. Debug.Assert(symbol.IsDefinition); return VisitNamedTypeMember(symbol, AreMethodsEqual); } public override Symbol? VisitModule(ModuleSymbol module) { var otherAssembly = (AssemblySymbol?)Visit(module.ContainingAssembly); if (otherAssembly is null) { return null; } // manifest module: if (module.Ordinal == 0) { return otherAssembly.Modules[0]; } // match non-manifest module by name: for (int i = 1; i < otherAssembly.Modules.Length; i++) { var otherModule = otherAssembly.Modules[i]; // use case sensitive comparison -- modules whose names differ in casing are considered distinct: if (StringComparer.Ordinal.Equals(otherModule.Name, module.Name)) { return otherModule; } } return null; } public override Symbol? VisitAssembly(AssemblySymbol assembly) { if (assembly.IsLinked) { return assembly; } // When we map synthesized symbols from previous generations to the latest compilation // we might encounter a symbol that is defined in arbitrary preceding generation, // not just the immediately preceding generation. If the source assembly uses time-based // versioning assemblies of preceding generations might differ in their version number. if (IdentityEqualIgnoringVersionWildcard(assembly, _sourceAssembly)) { return _otherAssembly; } // find a referenced assembly with the same source identity (modulo assembly version patterns): foreach (var otherReferencedAssembly in _otherAssembly.Modules[0].ReferencedAssemblySymbols) { if (IdentityEqualIgnoringVersionWildcard(assembly, otherReferencedAssembly)) { return otherReferencedAssembly; } } return null; } private static bool IdentityEqualIgnoringVersionWildcard(AssemblySymbol left, AssemblySymbol right) { var leftIdentity = left.Identity; var rightIdentity = right.Identity; return AssemblyIdentityComparer.SimpleNameComparer.Equals(leftIdentity.Name, rightIdentity.Name) && (left.AssemblyVersionPattern ?? leftIdentity.Version).Equals(right.AssemblyVersionPattern ?? rightIdentity.Version) && AssemblyIdentity.EqualIgnoringNameAndVersion(leftIdentity, rightIdentity); } public override Symbol? VisitNamespace(NamespaceSymbol @namespace) { var otherContainer = Visit(@namespace.ContainingSymbol); RoslynDebug.AssertNotNull(otherContainer); switch (otherContainer.Kind) { case SymbolKind.NetModule: Debug.Assert(@namespace.IsGlobalNamespace); return ((ModuleSymbol)otherContainer).GlobalNamespace; case SymbolKind.Namespace: return FindMatchingMember(otherContainer, @namespace, AreNamespacesEqual); default: throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind); } } public override Symbol VisitDynamicType(DynamicTypeSymbol symbol) { return _otherAssembly.GetSpecialType(SpecialType.System_Object); } public override Symbol? VisitNamedType(NamedTypeSymbol sourceType) { var originalDef = sourceType.OriginalDefinition; if ((object)originalDef != (object)sourceType) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var typeArguments = sourceType.GetAllTypeArguments(ref discardedUseSiteInfo); var otherDef = (NamedTypeSymbol?)Visit(originalDef); if (otherDef is null) { return null; } var otherTypeParameters = otherDef.GetAllTypeParameters(); bool translationFailed = false; var otherTypeArguments = typeArguments.SelectAsArray((t, v) => { var newType = (TypeSymbol?)v.Visit(t.Type); if (newType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. translationFailed = true; newType = t.Type; } return t.WithTypeAndModifiers(newType, v.VisitCustomModifiers(t.CustomModifiers)); }, this); if (translationFailed) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } // TODO: LambdaFrame has alpha renamed type parameters, should we rather fix that? var typeMap = new TypeMap(otherTypeParameters, otherTypeArguments, allowAlpha: true); return typeMap.SubstituteNamedType(otherDef); } Debug.Assert(sourceType.IsDefinition); var otherContainer = this.Visit(sourceType.ContainingSymbol); // Containing type will be missing from other assembly // if the type was added in the (newer) source assembly. if (otherContainer is null) { return null; } switch (otherContainer.Kind) { case SymbolKind.Namespace: if (sourceType is AnonymousTypeManager.AnonymousTypeTemplateSymbol template) { Debug.Assert((object)otherContainer == (object)_otherAssembly.GlobalNamespace); TryFindAnonymousType(template, out var value); return (NamedTypeSymbol?)value.Type?.GetInternalSymbol(); } if (sourceType.IsAnonymousType) { return Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(sourceType)); } return FindMatchingMember(otherContainer, sourceType, AreNamedTypesEqual); case SymbolKind.NamedType: return FindMatchingMember(otherContainer, sourceType, AreNamedTypesEqual); default: throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind); } } public override Symbol VisitParameter(ParameterSymbol parameter) { // Should never reach here. Should be matched as a result of matching the container. throw ExceptionUtilities.Unreachable; } public override Symbol? VisitPointerType(PointerTypeSymbol symbol) { var otherPointedAtType = (TypeSymbol?)Visit(symbol.PointedAtType); if (otherPointedAtType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } var otherModifiers = VisitCustomModifiers(symbol.PointedAtTypeWithAnnotations.CustomModifiers); return new PointerTypeSymbol(symbol.PointedAtTypeWithAnnotations.WithTypeAndModifiers(otherPointedAtType, otherModifiers)); } public override Symbol? VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { var sig = symbol.Signature; var otherReturnType = (TypeSymbol?)Visit(sig.ReturnType); if (otherReturnType is null) { return null; } var otherRefCustomModifiers = VisitCustomModifiers(sig.RefCustomModifiers); var otherReturnTypeWithAnnotations = sig.ReturnTypeWithAnnotations.WithTypeAndModifiers(otherReturnType, VisitCustomModifiers(sig.ReturnTypeWithAnnotations.CustomModifiers)); var otherParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; ImmutableArray<ImmutableArray<CustomModifier>> otherParamRefCustomModifiers = default; if (sig.ParameterCount > 0) { var otherParamsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(sig.ParameterCount); var otherParamRefCustomModifiersBuilder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(sig.ParameterCount); foreach (var param in sig.Parameters) { var otherType = (TypeSymbol?)Visit(param.Type); if (otherType is null) { otherParamsBuilder.Free(); otherParamRefCustomModifiersBuilder.Free(); return null; } otherParamRefCustomModifiersBuilder.Add(VisitCustomModifiers(param.RefCustomModifiers)); otherParamsBuilder.Add(param.TypeWithAnnotations.WithTypeAndModifiers(otherType, VisitCustomModifiers(param.TypeWithAnnotations.CustomModifiers))); } otherParameterTypes = otherParamsBuilder.ToImmutableAndFree(); otherParamRefCustomModifiers = otherParamRefCustomModifiersBuilder.ToImmutableAndFree(); } return symbol.SubstituteTypeSymbol(otherReturnTypeWithAnnotations, otherParameterTypes, otherRefCustomModifiers, otherParamRefCustomModifiers); } public override Symbol? VisitProperty(PropertySymbol symbol) => VisitNamedTypeMember(symbol, ArePropertiesEqual); public override Symbol VisitTypeParameter(TypeParameterSymbol symbol) { if (symbol is IndexedTypeParameterSymbol indexed) { return indexed; } var otherContainer = Visit(symbol.ContainingSymbol); RoslynDebug.AssertNotNull(otherContainer); var otherTypeParameters = otherContainer.Kind switch { SymbolKind.NamedType or SymbolKind.ErrorType => ((NamedTypeSymbol)otherContainer).TypeParameters, SymbolKind.Method => ((MethodSymbol)otherContainer).TypeParameters, _ => throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind), }; return otherTypeParameters[symbol.Ordinal]; } private ImmutableArray<CustomModifier> VisitCustomModifiers(ImmutableArray<CustomModifier> modifiers) { return modifiers.SelectAsArray(VisitCustomModifier); } private CustomModifier VisitCustomModifier(CustomModifier modifier) { var type = (NamedTypeSymbol?)Visit(((CSharpCustomModifier)modifier).ModifierSymbol); RoslynDebug.AssertNotNull(type); return modifier.IsOptional ? CSharpCustomModifier.CreateOptional(type) : CSharpCustomModifier.CreateRequired(type); } internal bool TryFindAnonymousType(AnonymousTypeManager.AnonymousTypeTemplateSymbol type, out AnonymousTypeValue otherType) { Debug.Assert((object)type.ContainingSymbol == (object)_sourceAssembly.GlobalNamespace); return _anonymousTypeMap.TryGetValue(type.GetAnonymousTypeKey(), out otherType); } private Symbol? VisitNamedTypeMember<T>(T member, Func<T, T, bool> predicate) where T : Symbol { var otherType = (NamedTypeSymbol?)Visit(member.ContainingType); // Containing type may be null for synthesized // types such as iterators. if (otherType is null) { return null; } return FindMatchingMember(otherType, member, predicate); } private T? FindMatchingMember<T>(ISymbolInternal otherTypeOrNamespace, T sourceMember, Func<T, T, bool> predicate) where T : Symbol { Debug.Assert(!string.IsNullOrEmpty(sourceMember.MetadataName)); var otherMembersByName = _otherMembers.GetOrAdd(otherTypeOrNamespace, GetAllEmittedMembers); if (otherMembersByName.TryGetValue(sourceMember.MetadataName, out var otherMembers)) { foreach (var otherMember in otherMembers) { if (otherMember is T other && predicate(sourceMember, other)) { return other; } } } return null; } private bool AreArrayTypesEqual(ArrayTypeSymbol type, ArrayTypeSymbol other) { // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.ElementTypeWithAnnotations.CustomModifiers.IsEmpty); Debug.Assert(other.ElementTypeWithAnnotations.CustomModifiers.IsEmpty); return type.HasSameShapeAs(other) && AreTypesEqual(type.ElementType, other.ElementType); } private bool AreEventsEqual(EventSymbol @event, EventSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(@event.Name, other.Name)); return _comparer.Equals(@event.Type, other.Type); } private bool AreFieldsEqual(FieldSymbol field, FieldSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(field.Name, other.Name)); return _comparer.Equals(field.Type, other.Type); } private bool AreMethodsEqual(MethodSymbol method, MethodSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(method.Name, other.Name)); Debug.Assert(method.IsDefinition); Debug.Assert(other.IsDefinition); method = SubstituteTypeParameters(method); other = SubstituteTypeParameters(other); return _comparer.Equals(method.ReturnType, other.ReturnType) && method.RefKind.Equals(other.RefKind) && method.Parameters.SequenceEqual(other.Parameters, AreParametersEqual) && method.TypeParameters.SequenceEqual(other.TypeParameters, AreTypesEqual); } private static MethodSymbol SubstituteTypeParameters(MethodSymbol method) { Debug.Assert(method.IsDefinition); var typeParameters = method.TypeParameters; int n = typeParameters.Length; if (n == 0) { return method; } return method.Construct(IndexedTypeParameterSymbol.Take(n)); } private bool AreNamedTypesEqual(NamedTypeSymbol type, NamedTypeSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(type.MetadataName, other.MetadataName)); // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); Debug.Assert(other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); return type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.SequenceEqual(other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, AreTypesEqual); } private bool AreNamespacesEqual(NamespaceSymbol @namespace, NamespaceSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(@namespace.MetadataName, other.MetadataName)); return true; } private bool AreParametersEqual(ParameterSymbol parameter, ParameterSymbol other) { Debug.Assert(parameter.Ordinal == other.Ordinal); return StringOrdinalComparer.Equals(parameter.MetadataName, other.MetadataName) && (parameter.RefKind == other.RefKind) && _comparer.Equals(parameter.Type, other.Type); } private bool ArePointerTypesEqual(PointerTypeSymbol type, PointerTypeSymbol other) { // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.PointedAtTypeWithAnnotations.CustomModifiers.IsEmpty); Debug.Assert(other.PointedAtTypeWithAnnotations.CustomModifiers.IsEmpty); return AreTypesEqual(type.PointedAtType, other.PointedAtType); } private bool AreFunctionPointerTypesEqual(FunctionPointerTypeSymbol type, FunctionPointerTypeSymbol other) { var sig = type.Signature; var otherSig = other.Signature; ValidateFunctionPointerParamOrReturn(sig.ReturnTypeWithAnnotations, sig.RefKind, sig.RefCustomModifiers, allowOut: false); ValidateFunctionPointerParamOrReturn(otherSig.ReturnTypeWithAnnotations, otherSig.RefKind, otherSig.RefCustomModifiers, allowOut: false); if (sig.RefKind != otherSig.RefKind || !AreTypesEqual(sig.ReturnTypeWithAnnotations, otherSig.ReturnTypeWithAnnotations)) { return false; } return sig.Parameters.SequenceEqual(otherSig.Parameters, AreFunctionPointerParametersEqual); } private bool AreFunctionPointerParametersEqual(ParameterSymbol param, ParameterSymbol otherParam) { ValidateFunctionPointerParamOrReturn(param.TypeWithAnnotations, param.RefKind, param.RefCustomModifiers, allowOut: true); ValidateFunctionPointerParamOrReturn(otherParam.TypeWithAnnotations, otherParam.RefKind, otherParam.RefCustomModifiers, allowOut: true); return param.RefKind == otherParam.RefKind && AreTypesEqual(param.TypeWithAnnotations, otherParam.TypeWithAnnotations); } [Conditional("DEBUG")] private static void ValidateFunctionPointerParamOrReturn(TypeWithAnnotations type, RefKind refKind, ImmutableArray<CustomModifier> refCustomModifiers, bool allowOut) { Debug.Assert(type.CustomModifiers.IsEmpty); Debug.Assert(verifyRefModifiers(refCustomModifiers, refKind, allowOut)); static bool verifyRefModifiers(ImmutableArray<CustomModifier> modifiers, RefKind refKind, bool allowOut) { Debug.Assert(RefKind.RefReadOnly == RefKind.In); switch (refKind) { case RefKind.RefReadOnly: case RefKind.Out when allowOut: return modifiers.Length == 1; default: return modifiers.IsEmpty; } } } private bool ArePropertiesEqual(PropertySymbol property, PropertySymbol other) { Debug.Assert(StringOrdinalComparer.Equals(property.MetadataName, other.MetadataName)); return _comparer.Equals(property.Type, other.Type) && property.RefKind.Equals(other.RefKind) && property.Parameters.SequenceEqual(other.Parameters, AreParametersEqual); } private static bool AreTypeParametersEqual(TypeParameterSymbol type, TypeParameterSymbol other) { Debug.Assert(type.Ordinal == other.Ordinal); Debug.Assert(StringOrdinalComparer.Equals(type.Name, other.Name)); // Comparing constraints is unnecessary: two methods cannot differ by // constraints alone and changing the signature of a method is a rude // edit. Furthermore, comparing constraint types might lead to a cycle. Debug.Assert(type.HasConstructorConstraint == other.HasConstructorConstraint); Debug.Assert(type.HasValueTypeConstraint == other.HasValueTypeConstraint); Debug.Assert(type.HasUnmanagedTypeConstraint == other.HasUnmanagedTypeConstraint); Debug.Assert(type.HasReferenceTypeConstraint == other.HasReferenceTypeConstraint); Debug.Assert(type.ConstraintTypesNoUseSiteDiagnostics.Length == other.ConstraintTypesNoUseSiteDiagnostics.Length); return true; } private bool AreTypesEqual(TypeWithAnnotations type, TypeWithAnnotations other) { Debug.Assert(type.CustomModifiers.IsDefaultOrEmpty); Debug.Assert(other.CustomModifiers.IsDefaultOrEmpty); return AreTypesEqual(type.Type, other.Type); } private bool AreTypesEqual(TypeSymbol type, TypeSymbol other) { if (type.Kind != other.Kind) { return false; } switch (type.Kind) { case SymbolKind.ArrayType: return AreArrayTypesEqual((ArrayTypeSymbol)type, (ArrayTypeSymbol)other); case SymbolKind.PointerType: return ArePointerTypesEqual((PointerTypeSymbol)type, (PointerTypeSymbol)other); case SymbolKind.FunctionPointerType: return AreFunctionPointerTypesEqual((FunctionPointerTypeSymbol)type, (FunctionPointerTypeSymbol)other); case SymbolKind.NamedType: case SymbolKind.ErrorType: return AreNamedTypesEqual((NamedTypeSymbol)type, (NamedTypeSymbol)other); case SymbolKind.TypeParameter: return AreTypeParametersEqual((TypeParameterSymbol)type, (TypeParameterSymbol)other); default: throw ExceptionUtilities.UnexpectedValue(type.Kind); } } private IReadOnlyDictionary<string, ImmutableArray<ISymbolInternal>> GetAllEmittedMembers(ISymbolInternal symbol) { var members = ArrayBuilder<ISymbolInternal>.GetInstance(); if (symbol.Kind == SymbolKind.NamedType) { var type = (NamedTypeSymbol)symbol; members.AddRange(type.GetEventsToEmit()); members.AddRange(type.GetFieldsToEmit()); members.AddRange(type.GetMethodsToEmit()); members.AddRange(type.GetTypeMembers()); members.AddRange(type.GetPropertiesToEmit()); } else { members.AddRange(((NamespaceSymbol)symbol).GetMembers()); } if (_otherSynthesizedMembers != null && _otherSynthesizedMembers.TryGetValue(symbol, out var synthesizedMembers)) { members.AddRange(synthesizedMembers); } var result = members.ToDictionary(s => s.MetadataName, StringOrdinalComparer.Instance); members.Free(); return result; } private sealed class SymbolComparer { private readonly MatchSymbols _matcher; private readonly DeepTranslator? _deepTranslator; public SymbolComparer(MatchSymbols matcher, DeepTranslator? deepTranslator) { Debug.Assert(matcher != null); _matcher = matcher; _deepTranslator = deepTranslator; } public bool Equals(TypeSymbol source, TypeSymbol other) { var visitedSource = (TypeSymbol?)_matcher.Visit(source); var visitedOther = (_deepTranslator != null) ? (TypeSymbol)_deepTranslator.Visit(other) : other; return visitedSource?.Equals(visitedOther, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) == true; } } } internal sealed class DeepTranslator : CSharpSymbolVisitor<Symbol> { private readonly ConcurrentDictionary<Symbol, Symbol> _matches; private readonly NamedTypeSymbol _systemObject; public DeepTranslator(NamedTypeSymbol systemObject) { _matches = new ConcurrentDictionary<Symbol, Symbol>(ReferenceEqualityComparer.Instance); _systemObject = systemObject; } public override Symbol DefaultVisit(Symbol symbol) { // Symbol should have been handled elsewhere. throw ExceptionUtilities.Unreachable; } public override Symbol Visit(Symbol symbol) { return _matches.GetOrAdd(symbol, base.Visit(symbol)); } public override Symbol VisitArrayType(ArrayTypeSymbol symbol) { var translatedElementType = (TypeSymbol)this.Visit(symbol.ElementType); var translatedModifiers = VisitCustomModifiers(symbol.ElementTypeWithAnnotations.CustomModifiers); if (symbol.IsSZArray) { return ArrayTypeSymbol.CreateSZArray(symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(translatedElementType, translatedModifiers)); } return ArrayTypeSymbol.CreateMDArray(symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(translatedElementType, translatedModifiers), symbol.Rank, symbol.Sizes, symbol.LowerBounds); } public override Symbol VisitDynamicType(DynamicTypeSymbol symbol) { return _systemObject; } public override Symbol VisitNamedType(NamedTypeSymbol type) { var originalDef = type.OriginalDefinition; if ((object)originalDef != type) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var translatedTypeArguments = type.GetAllTypeArguments(ref discardedUseSiteInfo).SelectAsArray((t, v) => t.WithTypeAndModifiers((TypeSymbol)v.Visit(t.Type), v.VisitCustomModifiers(t.CustomModifiers)), this); var translatedOriginalDef = (NamedTypeSymbol)this.Visit(originalDef); var typeMap = new TypeMap(translatedOriginalDef.GetAllTypeParameters(), translatedTypeArguments, allowAlpha: true); return typeMap.SubstituteNamedType(translatedOriginalDef); } Debug.Assert(type.IsDefinition); if (type.IsAnonymousType) { return this.Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(type)); } return type; } public override Symbol VisitPointerType(PointerTypeSymbol symbol) { var translatedPointedAtType = (TypeSymbol)this.Visit(symbol.PointedAtType); var translatedModifiers = VisitCustomModifiers(symbol.PointedAtTypeWithAnnotations.CustomModifiers); return new PointerTypeSymbol(symbol.PointedAtTypeWithAnnotations.WithTypeAndModifiers(translatedPointedAtType, translatedModifiers)); } public override Symbol VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { var sig = symbol.Signature; var translatedReturnType = (TypeSymbol)Visit(sig.ReturnType); var translatedReturnTypeWithAnnotations = sig.ReturnTypeWithAnnotations.WithTypeAndModifiers(translatedReturnType, VisitCustomModifiers(sig.ReturnTypeWithAnnotations.CustomModifiers)); var translatedRefCustomModifiers = VisitCustomModifiers(sig.RefCustomModifiers); var translatedParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; ImmutableArray<ImmutableArray<CustomModifier>> translatedParamRefCustomModifiers = default; if (sig.ParameterCount > 0) { var translatedParamsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(sig.ParameterCount); var translatedParamRefCustomModifiersBuilder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(sig.ParameterCount); foreach (var param in sig.Parameters) { var translatedParamType = (TypeSymbol)Visit(param.Type); translatedParamsBuilder.Add(param.TypeWithAnnotations.WithTypeAndModifiers(translatedParamType, VisitCustomModifiers(param.TypeWithAnnotations.CustomModifiers))); translatedParamRefCustomModifiersBuilder.Add(VisitCustomModifiers(param.RefCustomModifiers)); } translatedParameterTypes = translatedParamsBuilder.ToImmutableAndFree(); translatedParamRefCustomModifiers = translatedParamRefCustomModifiersBuilder.ToImmutableAndFree(); } return symbol.SubstituteTypeSymbol(translatedReturnTypeWithAnnotations, translatedParameterTypes, translatedRefCustomModifiers, translatedParamRefCustomModifiers); } public override Symbol VisitTypeParameter(TypeParameterSymbol symbol) { return symbol; } private ImmutableArray<CustomModifier> VisitCustomModifiers(ImmutableArray<CustomModifier> modifiers) { return modifiers.SelectAsArray(VisitCustomModifier); } private CustomModifier VisitCustomModifier(CustomModifier modifier) { var translatedType = (NamedTypeSymbol)this.Visit(((CSharpCustomModifier)modifier).ModifierSymbol); Debug.Assert((object)translatedType != null); return modifier.IsOptional ? CSharpCustomModifier.CreateOptional(translatedType) : CSharpCustomModifier.CreateRequired(translatedType); } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/Operations/FormattingOperations.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Formatting.Rules { internal static class FormattingOperations { private static readonly AdjustNewLinesOperation s_preserveZeroLine = new(0, AdjustNewLinesOption.PreserveLines); private static readonly AdjustNewLinesOperation s_preserveOneLine = new(1, AdjustNewLinesOption.PreserveLines); private static readonly AdjustNewLinesOperation s_forceOneLine = new(1, AdjustNewLinesOption.ForceLines); private static readonly AdjustNewLinesOperation s_forceIfSameLine = new(1, AdjustNewLinesOption.ForceLinesIfOnSingleLine); private static readonly AdjustSpacesOperation s_defaultOneSpaceIfOnSingleLine = new(1, AdjustSpacesOption.DefaultSpacesIfOnSingleLine); private static readonly AdjustSpacesOperation s_forceOneSpaceIfOnSingleLine = new(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine); private static readonly AdjustSpacesOperation s_forceZeroSpaceIfOnSingleLine = new(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine); // As the name suggests, the line force operation is performed by force spacing private static readonly AdjustSpacesOperation s_forceZeroLineUsingSpaceForce = new(1, AdjustSpacesOption.ForceSpaces); /// <summary> /// create anchor indentation region around start and end token /// start token will act as anchor token and right after anchor token to end of end token will become anchor region /// </summary> public static AnchorIndentationOperation CreateAnchorIndentationOperation(SyntaxToken startToken, SyntaxToken endToken) => CreateAnchorIndentationOperation(startToken, startToken, endToken, TextSpan.FromBounds(startToken.Span.End, endToken.Span.End)); /// <summary> /// create anchor indentation region more explicitly by providing all necessary information. /// </summary> public static AnchorIndentationOperation CreateAnchorIndentationOperation(SyntaxToken anchorToken, SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan) => new(anchorToken, startToken, endToken, textSpan); /// <summary> /// create suppress region around start and end token /// </summary> public static SuppressOperation CreateSuppressOperation(SyntaxToken startToken, SyntaxToken endToken, SuppressOption option) => CreateSuppressOperation(startToken, endToken, TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End), option); /// <summary> /// create suppress region around the given text span /// </summary> private static SuppressOperation CreateSuppressOperation(SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan, SuppressOption option) => new(startToken, endToken, textSpan, option); /// <summary> /// create indent block region around the start and end token with the given indentation delta added to the existing indentation at the position of the start token /// </summary> public static IndentBlockOperation CreateIndentBlockOperation(SyntaxToken startToken, SyntaxToken endToken, int indentationDelta, IndentBlockOption option) { var span = CommonFormattingHelpers.GetSpanIncludingTrailingAndLeadingTriviaOfAdjacentTokens(startToken, endToken); return CreateIndentBlockOperation(startToken, endToken, span, indentationDelta, option); } /// <summary> /// create indent block region around the given text span with the given indentation delta added to the existing indentation at the position of the start token /// </summary> public static IndentBlockOperation CreateIndentBlockOperation(SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan, int indentationDelta, IndentBlockOption option) => new(startToken, endToken, textSpan, indentationDelta, option); /// <summary> /// create indent block region around the start and end token with the given indentation delta added to the column of the base token /// </summary> public static IndentBlockOperation CreateRelativeIndentBlockOperation(SyntaxToken baseToken, SyntaxToken startToken, SyntaxToken endToken, int indentationDelta, IndentBlockOption option) { var span = CommonFormattingHelpers.GetSpanIncludingTrailingAndLeadingTriviaOfAdjacentTokens(startToken, endToken); return CreateRelativeIndentBlockOperation(baseToken, startToken, endToken, span, indentationDelta, option); } /// <summary> /// create indent block region around the given text span with the given indentation delta added to the column of the base token /// </summary> public static IndentBlockOperation CreateRelativeIndentBlockOperation(SyntaxToken baseToken, SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan, int indentationDelta, IndentBlockOption option) => new(baseToken, startToken, endToken, textSpan, indentationDelta, option); /// <summary> /// instruct the engine to try to align first tokens on the lines among the given tokens to be aligned to the base token /// </summary> public static AlignTokensOperation CreateAlignTokensOperation(SyntaxToken baseToken, IEnumerable<SyntaxToken> tokens, AlignTokensOption option) => new(baseToken, tokens, option); /// <summary> /// instruct the engine to try to put the give lines between two tokens /// </summary> public static AdjustNewLinesOperation CreateAdjustNewLinesOperation(int line, AdjustNewLinesOption option) { if (line == 0) { if (option == AdjustNewLinesOption.PreserveLines) { return s_preserveZeroLine; } } else if (line == 1) { if (option == AdjustNewLinesOption.PreserveLines) { return s_preserveOneLine; } else if (option == AdjustNewLinesOption.ForceLines) { return s_forceOneLine; } else if (option == AdjustNewLinesOption.ForceLinesIfOnSingleLine) { return s_forceIfSameLine; } } return new AdjustNewLinesOperation(line, option); } /// <summary> /// instruct the engine to try to put the given spaces between two tokens /// </summary> public static AdjustSpacesOperation CreateAdjustSpacesOperation(int space, AdjustSpacesOption option) { if (space == 1 && option == AdjustSpacesOption.DefaultSpacesIfOnSingleLine) { return s_defaultOneSpaceIfOnSingleLine; } else if (space == 0 && option == AdjustSpacesOption.ForceSpacesIfOnSingleLine) { return s_forceZeroSpaceIfOnSingleLine; } else if (space == 1 && option == AdjustSpacesOption.ForceSpacesIfOnSingleLine) { return s_forceOneSpaceIfOnSingleLine; } else if (space == 1 && option == AdjustSpacesOption.ForceSpaces) { return s_forceZeroLineUsingSpaceForce; } return new AdjustSpacesOperation(space, option); } /// <summary> /// return SuppressOperation for the node provided by the given formatting rules /// </summary> internal static IEnumerable<SuppressOperation> GetSuppressOperations(IEnumerable<AbstractFormattingRule> formattingRules, SyntaxNode node, AnalyzerConfigOptions options) { var chainedFormattingRules = new ChainedFormattingRules(formattingRules, options); var list = new List<SuppressOperation>(); chainedFormattingRules.AddSuppressOperations(list, node); return list; } /// <summary> /// return AnchorIndentationOperation for the node provided by the given formatting rules /// </summary> internal static IEnumerable<AnchorIndentationOperation> GetAnchorIndentationOperations(IEnumerable<AbstractFormattingRule> formattingRules, SyntaxNode node, AnalyzerConfigOptions options) { var chainedFormattingRules = new ChainedFormattingRules(formattingRules, options); var list = new List<AnchorIndentationOperation>(); chainedFormattingRules.AddAnchorIndentationOperations(list, node); return list; } /// <summary> /// return IndentBlockOperation for the node provided by the given formatting rules /// </summary> internal static IEnumerable<IndentBlockOperation> GetIndentBlockOperations(IEnumerable<AbstractFormattingRule> formattingRules, SyntaxNode node, AnalyzerConfigOptions options) { var chainedFormattingRules = new ChainedFormattingRules(formattingRules, options); var list = new List<IndentBlockOperation>(); chainedFormattingRules.AddIndentBlockOperations(list, node); return list; } /// <summary> /// return AlignTokensOperation for the node provided by the given formatting rules /// </summary> internal static IEnumerable<AlignTokensOperation> GetAlignTokensOperations(IEnumerable<AbstractFormattingRule> formattingRules, SyntaxNode node, AnalyzerConfigOptions options) { var chainedFormattingRules = new ChainedFormattingRules(formattingRules, options); var list = new List<AlignTokensOperation>(); chainedFormattingRules.AddAlignTokensOperations(list, node); return list; } /// <summary> /// return AdjustNewLinesOperation for the node provided by the given formatting rules /// </summary> internal static AdjustNewLinesOperation? GetAdjustNewLinesOperation(IEnumerable<AbstractFormattingRule> formattingRules, SyntaxToken previousToken, SyntaxToken currentToken, AnalyzerConfigOptions options) { var chainedFormattingRules = new ChainedFormattingRules(formattingRules, options); return chainedFormattingRules.GetAdjustNewLinesOperation(previousToken, currentToken); } /// <summary> /// return AdjustSpacesOperation for the node provided by the given formatting rules /// </summary> internal static AdjustSpacesOperation? GetAdjustSpacesOperation(IEnumerable<AbstractFormattingRule> formattingRules, SyntaxToken previousToken, SyntaxToken currentToken, AnalyzerConfigOptions options) { var chainedFormattingRules = new ChainedFormattingRules(formattingRules, options); return chainedFormattingRules.GetAdjustSpacesOperation(previousToken, currentToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Formatting.Rules { internal static class FormattingOperations { private static readonly AdjustNewLinesOperation s_preserveZeroLine = new(0, AdjustNewLinesOption.PreserveLines); private static readonly AdjustNewLinesOperation s_preserveOneLine = new(1, AdjustNewLinesOption.PreserveLines); private static readonly AdjustNewLinesOperation s_forceOneLine = new(1, AdjustNewLinesOption.ForceLines); private static readonly AdjustNewLinesOperation s_forceIfSameLine = new(1, AdjustNewLinesOption.ForceLinesIfOnSingleLine); private static readonly AdjustSpacesOperation s_defaultOneSpaceIfOnSingleLine = new(1, AdjustSpacesOption.DefaultSpacesIfOnSingleLine); private static readonly AdjustSpacesOperation s_forceOneSpaceIfOnSingleLine = new(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine); private static readonly AdjustSpacesOperation s_forceZeroSpaceIfOnSingleLine = new(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine); // As the name suggests, the line force operation is performed by force spacing private static readonly AdjustSpacesOperation s_forceZeroLineUsingSpaceForce = new(1, AdjustSpacesOption.ForceSpaces); /// <summary> /// create anchor indentation region around start and end token /// start token will act as anchor token and right after anchor token to end of end token will become anchor region /// </summary> public static AnchorIndentationOperation CreateAnchorIndentationOperation(SyntaxToken startToken, SyntaxToken endToken) => CreateAnchorIndentationOperation(startToken, startToken, endToken, TextSpan.FromBounds(startToken.Span.End, endToken.Span.End)); /// <summary> /// create anchor indentation region more explicitly by providing all necessary information. /// </summary> public static AnchorIndentationOperation CreateAnchorIndentationOperation(SyntaxToken anchorToken, SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan) => new(anchorToken, startToken, endToken, textSpan); /// <summary> /// create suppress region around start and end token /// </summary> public static SuppressOperation CreateSuppressOperation(SyntaxToken startToken, SyntaxToken endToken, SuppressOption option) => CreateSuppressOperation(startToken, endToken, TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End), option); /// <summary> /// create suppress region around the given text span /// </summary> private static SuppressOperation CreateSuppressOperation(SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan, SuppressOption option) => new(startToken, endToken, textSpan, option); /// <summary> /// create indent block region around the start and end token with the given indentation delta added to the existing indentation at the position of the start token /// </summary> public static IndentBlockOperation CreateIndentBlockOperation(SyntaxToken startToken, SyntaxToken endToken, int indentationDelta, IndentBlockOption option) { var span = CommonFormattingHelpers.GetSpanIncludingTrailingAndLeadingTriviaOfAdjacentTokens(startToken, endToken); return CreateIndentBlockOperation(startToken, endToken, span, indentationDelta, option); } /// <summary> /// create indent block region around the given text span with the given indentation delta added to the existing indentation at the position of the start token /// </summary> public static IndentBlockOperation CreateIndentBlockOperation(SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan, int indentationDelta, IndentBlockOption option) => new(startToken, endToken, textSpan, indentationDelta, option); /// <summary> /// create indent block region around the start and end token with the given indentation delta added to the column of the base token /// </summary> public static IndentBlockOperation CreateRelativeIndentBlockOperation(SyntaxToken baseToken, SyntaxToken startToken, SyntaxToken endToken, int indentationDelta, IndentBlockOption option) { var span = CommonFormattingHelpers.GetSpanIncludingTrailingAndLeadingTriviaOfAdjacentTokens(startToken, endToken); return CreateRelativeIndentBlockOperation(baseToken, startToken, endToken, span, indentationDelta, option); } /// <summary> /// create indent block region around the given text span with the given indentation delta added to the column of the base token /// </summary> public static IndentBlockOperation CreateRelativeIndentBlockOperation(SyntaxToken baseToken, SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan, int indentationDelta, IndentBlockOption option) => new(baseToken, startToken, endToken, textSpan, indentationDelta, option); /// <summary> /// instruct the engine to try to align first tokens on the lines among the given tokens to be aligned to the base token /// </summary> public static AlignTokensOperation CreateAlignTokensOperation(SyntaxToken baseToken, IEnumerable<SyntaxToken> tokens, AlignTokensOption option) => new(baseToken, tokens, option); /// <summary> /// instruct the engine to try to put the give lines between two tokens /// </summary> public static AdjustNewLinesOperation CreateAdjustNewLinesOperation(int line, AdjustNewLinesOption option) { if (line == 0) { if (option == AdjustNewLinesOption.PreserveLines) { return s_preserveZeroLine; } } else if (line == 1) { if (option == AdjustNewLinesOption.PreserveLines) { return s_preserveOneLine; } else if (option == AdjustNewLinesOption.ForceLines) { return s_forceOneLine; } else if (option == AdjustNewLinesOption.ForceLinesIfOnSingleLine) { return s_forceIfSameLine; } } return new AdjustNewLinesOperation(line, option); } /// <summary> /// instruct the engine to try to put the given spaces between two tokens /// </summary> public static AdjustSpacesOperation CreateAdjustSpacesOperation(int space, AdjustSpacesOption option) { if (space == 1 && option == AdjustSpacesOption.DefaultSpacesIfOnSingleLine) { return s_defaultOneSpaceIfOnSingleLine; } else if (space == 0 && option == AdjustSpacesOption.ForceSpacesIfOnSingleLine) { return s_forceZeroSpaceIfOnSingleLine; } else if (space == 1 && option == AdjustSpacesOption.ForceSpacesIfOnSingleLine) { return s_forceOneSpaceIfOnSingleLine; } else if (space == 1 && option == AdjustSpacesOption.ForceSpaces) { return s_forceZeroLineUsingSpaceForce; } return new AdjustSpacesOperation(space, option); } /// <summary> /// return SuppressOperation for the node provided by the given formatting rules /// </summary> internal static IEnumerable<SuppressOperation> GetSuppressOperations(IEnumerable<AbstractFormattingRule> formattingRules, SyntaxNode node, AnalyzerConfigOptions options) { var chainedFormattingRules = new ChainedFormattingRules(formattingRules, options); var list = new List<SuppressOperation>(); chainedFormattingRules.AddSuppressOperations(list, node); return list; } /// <summary> /// return AnchorIndentationOperation for the node provided by the given formatting rules /// </summary> internal static IEnumerable<AnchorIndentationOperation> GetAnchorIndentationOperations(IEnumerable<AbstractFormattingRule> formattingRules, SyntaxNode node, AnalyzerConfigOptions options) { var chainedFormattingRules = new ChainedFormattingRules(formattingRules, options); var list = new List<AnchorIndentationOperation>(); chainedFormattingRules.AddAnchorIndentationOperations(list, node); return list; } /// <summary> /// return IndentBlockOperation for the node provided by the given formatting rules /// </summary> internal static IEnumerable<IndentBlockOperation> GetIndentBlockOperations(IEnumerable<AbstractFormattingRule> formattingRules, SyntaxNode node, AnalyzerConfigOptions options) { var chainedFormattingRules = new ChainedFormattingRules(formattingRules, options); var list = new List<IndentBlockOperation>(); chainedFormattingRules.AddIndentBlockOperations(list, node); return list; } /// <summary> /// return AlignTokensOperation for the node provided by the given formatting rules /// </summary> internal static IEnumerable<AlignTokensOperation> GetAlignTokensOperations(IEnumerable<AbstractFormattingRule> formattingRules, SyntaxNode node, AnalyzerConfigOptions options) { var chainedFormattingRules = new ChainedFormattingRules(formattingRules, options); var list = new List<AlignTokensOperation>(); chainedFormattingRules.AddAlignTokensOperations(list, node); return list; } /// <summary> /// return AdjustNewLinesOperation for the node provided by the given formatting rules /// </summary> internal static AdjustNewLinesOperation? GetAdjustNewLinesOperation(IEnumerable<AbstractFormattingRule> formattingRules, SyntaxToken previousToken, SyntaxToken currentToken, AnalyzerConfigOptions options) { var chainedFormattingRules = new ChainedFormattingRules(formattingRules, options); return chainedFormattingRules.GetAdjustNewLinesOperation(previousToken, currentToken); } /// <summary> /// return AdjustSpacesOperation for the node provided by the given formatting rules /// </summary> internal static AdjustSpacesOperation? GetAdjustSpacesOperation(IEnumerable<AbstractFormattingRule> formattingRules, SyntaxToken previousToken, SyntaxToken currentToken, AnalyzerConfigOptions options) { var chainedFormattingRules = new ChainedFormattingRules(formattingRules, options); return chainedFormattingRules.GetAdjustSpacesOperation(previousToken, currentToken); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Options/OptionsExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeStyle; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Options { internal static class OptionsExtensions { public static Option<CodeStyleOption<T>> ToPublicOption<T>(this Option2<CodeStyleOption2<T>> option) { RoslynDebug.Assert(option != null); var codeStyleOption = new CodeStyleOption<T>(option.DefaultValue); var optionDefinition = new OptionDefinition(option.Feature, option.Group, option.Name, defaultValue: codeStyleOption, type: typeof(CodeStyleOption<T>), isPerLanguage: false); return new Option<CodeStyleOption<T>>(optionDefinition, option.StorageLocations.As<OptionStorageLocation>()); } public static PerLanguageOption<CodeStyleOption<T>> ToPublicOption<T>(this PerLanguageOption2<CodeStyleOption2<T>> option) { RoslynDebug.Assert(option != null); var codeStyleOption = new CodeStyleOption<T>(option.DefaultValue); var optionDefinition = new OptionDefinition(option.Feature, option.Group, option.Name, defaultValue: codeStyleOption, type: typeof(CodeStyleOption<T>), isPerLanguage: true); return new PerLanguageOption<CodeStyleOption<T>>(optionDefinition, option.StorageLocations.As<OptionStorageLocation>()); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeStyle; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Options { internal static class OptionsExtensions { public static Option<CodeStyleOption<T>> ToPublicOption<T>(this Option2<CodeStyleOption2<T>> option) { RoslynDebug.Assert(option != null); var codeStyleOption = new CodeStyleOption<T>(option.DefaultValue); var optionDefinition = new OptionDefinition(option.Feature, option.Group, option.Name, defaultValue: codeStyleOption, type: typeof(CodeStyleOption<T>), isPerLanguage: false); return new Option<CodeStyleOption<T>>(optionDefinition, option.StorageLocations.As<OptionStorageLocation>()); } public static PerLanguageOption<CodeStyleOption<T>> ToPublicOption<T>(this PerLanguageOption2<CodeStyleOption2<T>> option) { RoslynDebug.Assert(option != null); var codeStyleOption = new CodeStyleOption<T>(option.DefaultValue); var optionDefinition = new OptionDefinition(option.Feature, option.Group, option.Name, defaultValue: codeStyleOption, type: typeof(CodeStyleOption<T>), isPerLanguage: true); return new PerLanguageOption<CodeStyleOption<T>>(optionDefinition, option.StorageLocations.As<OptionStorageLocation>()); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/EditorConfigSettings/Updater/OptionUpdater.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater { internal class OptionUpdater : SettingsUpdaterBase<IOption2, object> { public OptionUpdater(Workspace workspace, string editorconfigPath) : base(workspace, editorconfigPath) { } protected override SourceText? GetNewText(SourceText SourceText, IReadOnlyList<(IOption2 option, object value)> settingsToUpdate, CancellationToken token) => SettingsUpdateHelper.TryUpdateAnalyzerConfigDocument(SourceText, EditorconfigPath, Workspace.Options, settingsToUpdate); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater { internal class OptionUpdater : SettingsUpdaterBase<IOption2, object> { public OptionUpdater(Workspace workspace, string editorconfigPath) : base(workspace, editorconfigPath) { } protected override SourceText? GetNewText(SourceText SourceText, IReadOnlyList<(IOption2 option, object value)> settingsToUpdate, CancellationToken token) => SettingsUpdateHelper.TryUpdateAnalyzerConfigDocument(SourceText, EditorconfigPath, Workspace.Options, settingsToUpdate); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Syntax/InternalSyntax/SyntaxList.WithLotsOfChildren.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { internal partial class SyntaxList { internal sealed class WithLotsOfChildren : WithManyChildrenBase { static WithLotsOfChildren() { ObjectBinder.RegisterTypeReader(typeof(WithLotsOfChildren), r => new WithLotsOfChildren(r)); } private readonly int[] _childOffsets; internal WithLotsOfChildren(ArrayElement<GreenNode>[] children) : base(children) { _childOffsets = CalculateOffsets(children); } internal WithLotsOfChildren(DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations, ArrayElement<GreenNode>[] children, int[] childOffsets) : base(diagnostics, annotations, children) { _childOffsets = childOffsets; } internal WithLotsOfChildren(ObjectReader reader) : base(reader) { _childOffsets = CalculateOffsets(this.children); } internal override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); // don't write offsets out, recompute them on construction } public override int GetSlotOffset(int index) { return _childOffsets[index]; } /// <summary> /// Find the slot that contains the given offset. /// </summary> /// <param name="offset">The target offset. Must be between 0 and <see cref="GreenNode.FullWidth"/>.</param> /// <returns>The slot index of the slot containing the given offset.</returns> /// <remarks> /// This implementation uses a binary search to find the first slot that contains /// the given offset. /// </remarks> public override int FindSlotIndexContainingOffset(int offset) { Debug.Assert(offset >= 0 && offset < FullWidth); return _childOffsets.BinarySearchUpperBound(offset) - 1; } private static int[] CalculateOffsets(ArrayElement<GreenNode>[] children) { int n = children.Length; var childOffsets = new int[n]; int offset = 0; for (int i = 0; i < n; i++) { childOffsets[i] = offset; offset += children[i].Value.FullWidth; } return childOffsets; } internal override GreenNode SetDiagnostics(DiagnosticInfo[]? errors) { return new WithLotsOfChildren(errors, this.GetAnnotations(), children, _childOffsets); } internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) { return new WithLotsOfChildren(GetDiagnostics(), annotations, children, _childOffsets); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { internal partial class SyntaxList { internal sealed class WithLotsOfChildren : WithManyChildrenBase { static WithLotsOfChildren() { ObjectBinder.RegisterTypeReader(typeof(WithLotsOfChildren), r => new WithLotsOfChildren(r)); } private readonly int[] _childOffsets; internal WithLotsOfChildren(ArrayElement<GreenNode>[] children) : base(children) { _childOffsets = CalculateOffsets(children); } internal WithLotsOfChildren(DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations, ArrayElement<GreenNode>[] children, int[] childOffsets) : base(diagnostics, annotations, children) { _childOffsets = childOffsets; } internal WithLotsOfChildren(ObjectReader reader) : base(reader) { _childOffsets = CalculateOffsets(this.children); } internal override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); // don't write offsets out, recompute them on construction } public override int GetSlotOffset(int index) { return _childOffsets[index]; } /// <summary> /// Find the slot that contains the given offset. /// </summary> /// <param name="offset">The target offset. Must be between 0 and <see cref="GreenNode.FullWidth"/>.</param> /// <returns>The slot index of the slot containing the given offset.</returns> /// <remarks> /// This implementation uses a binary search to find the first slot that contains /// the given offset. /// </remarks> public override int FindSlotIndexContainingOffset(int offset) { Debug.Assert(offset >= 0 && offset < FullWidth); return _childOffsets.BinarySearchUpperBound(offset) - 1; } private static int[] CalculateOffsets(ArrayElement<GreenNode>[] children) { int n = children.Length; var childOffsets = new int[n]; int offset = 0; for (int i = 0; i < n; i++) { childOffsets[i] = offset; offset += children[i].Value.FullWidth; } return childOffsets; } internal override GreenNode SetDiagnostics(DiagnosticInfo[]? errors) { return new WithLotsOfChildren(errors, this.GetAnnotations(), children, _childOffsets); } internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) { return new WithLotsOfChildren(GetDiagnostics(), annotations, children, _childOffsets); } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/CSharp/Impl/Options/Formatting/IndentationViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Windows.Controls; 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 FormattingIndentationOptionControl.xaml /// </summary> internal class IndentationViewModel : AbstractOptionPreviewViewModel { private const string BlockContentPreview = @" class C { //[ int Method() { int x; int y; } //] }"; private const string IndentBracePreview = @" class C { //[ int Method() { return 0; } //] }"; private const string SwitchCasePreview = @" class MyClass { int Method(int goo){ //[ switch (goo){ case 2: break; } //] } }"; private const string SwitchCaseWhenBlockPreview = @" class MyClass { int Method(int goo){ //[ switch (goo){ case 2: { break; } } //] } }"; private const string GotoLabelPreview = @" class MyClass { int Method(int goo){ //[ MyLabel: goto MyLabel; return 0; //] } }"; public IndentationViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp) { Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentBlock, CSharpVSResources.Indent_block_contents, BlockContentPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentBraces, CSharpVSResources.Indent_open_and_close_braces, IndentBracePreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentSwitchCaseSection, CSharpVSResources.Indent_case_contents, SwitchCasePreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentSwitchCaseSectionWhenBlock, CSharpVSResources.Indent_case_contents_when_block, SwitchCaseWhenBlockPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentSwitchSection, CSharpVSResources.Indent_case_labels, SwitchCasePreview, this, optionStore)); Items.Add(new TextBlock() { Text = CSharpVSResources.Label_Indentation }); Items.Add(new RadioButtonViewModel<LabelPositionOptions>(CSharpVSResources.Place_goto_labels_in_leftmost_column, GotoLabelPreview, "goto", LabelPositionOptions.LeftMost, CSharpFormattingOptions.LabelPositioning, this, optionStore)); Items.Add(new RadioButtonViewModel<LabelPositionOptions>(CSharpVSResources.Indent_labels_normally, GotoLabelPreview, "goto", LabelPositionOptions.NoIndent, CSharpFormattingOptions.LabelPositioning, this, optionStore)); Items.Add(new RadioButtonViewModel<LabelPositionOptions>(CSharpVSResources.Place_goto_labels_one_indent_less_than_current, GotoLabelPreview, "goto", LabelPositionOptions.OneLess, CSharpFormattingOptions.LabelPositioning, 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 System.Windows.Controls; 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 FormattingIndentationOptionControl.xaml /// </summary> internal class IndentationViewModel : AbstractOptionPreviewViewModel { private const string BlockContentPreview = @" class C { //[ int Method() { int x; int y; } //] }"; private const string IndentBracePreview = @" class C { //[ int Method() { return 0; } //] }"; private const string SwitchCasePreview = @" class MyClass { int Method(int goo){ //[ switch (goo){ case 2: break; } //] } }"; private const string SwitchCaseWhenBlockPreview = @" class MyClass { int Method(int goo){ //[ switch (goo){ case 2: { break; } } //] } }"; private const string GotoLabelPreview = @" class MyClass { int Method(int goo){ //[ MyLabel: goto MyLabel; return 0; //] } }"; public IndentationViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp) { Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentBlock, CSharpVSResources.Indent_block_contents, BlockContentPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentBraces, CSharpVSResources.Indent_open_and_close_braces, IndentBracePreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentSwitchCaseSection, CSharpVSResources.Indent_case_contents, SwitchCasePreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentSwitchCaseSectionWhenBlock, CSharpVSResources.Indent_case_contents_when_block, SwitchCaseWhenBlockPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentSwitchSection, CSharpVSResources.Indent_case_labels, SwitchCasePreview, this, optionStore)); Items.Add(new TextBlock() { Text = CSharpVSResources.Label_Indentation }); Items.Add(new RadioButtonViewModel<LabelPositionOptions>(CSharpVSResources.Place_goto_labels_in_leftmost_column, GotoLabelPreview, "goto", LabelPositionOptions.LeftMost, CSharpFormattingOptions.LabelPositioning, this, optionStore)); Items.Add(new RadioButtonViewModel<LabelPositionOptions>(CSharpVSResources.Indent_labels_normally, GotoLabelPreview, "goto", LabelPositionOptions.NoIndent, CSharpFormattingOptions.LabelPositioning, this, optionStore)); Items.Add(new RadioButtonViewModel<LabelPositionOptions>(CSharpVSResources.Place_goto_labels_one_indent_less_than_current, GotoLabelPreview, "goto", LabelPositionOptions.OneLess, CSharpFormattingOptions.LabelPositioning, this, optionStore)); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/CodeGeneration/CodeGenerationOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { /// <summary> /// Options for controlling the code produced by the <see cref="CodeGenerator"/>. /// </summary> internal class CodeGenerationOptions { public static readonly CodeGenerationOptions Default = new(); /// <summary> /// A location used to determine the best place to generate a member. This is only used for /// determining which part of a partial type to generate in. If a type only has one part, or /// an API is used that specifies the type, then this is not used. A part is preferred if /// it surrounds this context location. If no part surrounds this location then a part is /// preferred if it comes from the same SyntaxTree as this location. If there is no /// such part, then any part may be used for generation. /// /// This option is not necessary if <see cref="AfterThisLocation"/> or <see cref="BeforeThisLocation"/> are /// provided. /// </summary> public Location? ContextLocation { get; } /// <summary> /// A hint to the code generation service to specify where the generated code should be /// placed. Code will be generated after this location if the location is valid in the type /// or symbol being generated into, and it is possible to generate the code after it. /// /// If this option is provided, neither <see cref="ContextLocation"/> nor <see cref="BeforeThisLocation"/> are /// needed. /// </summary> public Location? AfterThisLocation { get; } /// <summary> /// A hint to the code generation service to specify where the generated code should be /// placed. Code will be generated before this location if the location is valid in the type /// or symbol being generated into, and it is possible to generate the code after it. /// /// If this option is provided, neither <see cref="ContextLocation"/> nor <see cref="AfterThisLocation"/> are /// needed. /// </summary> public Location? BeforeThisLocation { get; } /// <summary> /// True if the code generation service should add <see cref="Simplifier.AddImportsAnnotation"/>, /// and when not generating directly into a declaration, should try to automatically add imports to the file /// for any generated code. /// Defaults to true. /// </summary> public bool AddImports { get; } /// <summary> /// True if, when adding a System import, the import should be placed above non-System /// imports. Defaults to true. Only used if <see cref="AddImports"/> is true. /// </summary> public bool PlaceSystemNamespaceFirst { get; } /// <summary> /// Contains additional imports to be automatically added. This is useful for adding /// imports that are part of a list of statements. /// </summary> public IEnumerable<INamespaceSymbol> AdditionalImports { get; } /// <summary> /// True if members of a symbol should also be generated along with the declaration. If /// false, only the symbol's declaration will be generated. /// </summary> public bool GenerateMembers { get; } /// <summary> /// True if the code generator should merge namespaces which only contain other namespaces /// into a single declaration with a dotted name. False if the nesting should be preserved /// and each namespace declaration should be nested and should only have a single non-dotted /// name. /// /// Merging can only occur if the namespace only contains a single member that is also a /// namespace. /// </summary> public bool MergeNestedNamespaces { get; } /// <summary> /// True if the code generation should put multiple attributes in a single attribute /// declaration, or if should have a separate attribute declaration for each attribute. For /// example, in C# setting this to True this would produce "[Goo, Bar]" while setting it to /// False would produce "[Goo][Bar]" /// </summary> public bool MergeAttributes { get; } /// <summary> /// True if the code generator should always generate accessibility modifiers, even if they /// are the same as the defaults for that symbol. For example, a private field in C# does /// not need its accessibility specified as it will be private by default. However, if this /// option is set to true 'private' will still be generated. /// </summary> public bool GenerateDefaultAccessibility { get; } /// <summary> /// True if the code generator should generate empty bodies for methods along with the /// method declaration. If false, only method declarations will be generated. /// </summary> public bool GenerateMethodBodies { get; } /// <summary> /// True if the code generator should generate documentation comments where available /// </summary> public bool GenerateDocumentationComments { get; } /// <summary> /// True if the code generator should automatically attempt to choose the appropriate location /// to insert members. If false and a generation location is not specified by AfterThisLocation, /// or BeforeThisLocation, members will be inserted at the end of the destination definition. /// </summary> public bool AutoInsertionLocation { get; } /// <summary> /// If <see cref="AutoInsertionLocation"/> is <see langword="false"/>, determines if members will be /// sorted before being added to the end of the list of members. /// </summary> public bool SortMembers { get; } /// <summary> /// True if the code generator should attempt to reuse the syntax of the constituent entities, such as members, access modifier tokens, etc. while attempting to generate code. /// If any of the member symbols have zero declaring syntax references (non-source symbols) OR two or more declaring syntax references (partial definitions), then syntax is not reused. /// If false, then the code generator will always synthesize a new syntax node and ignore the declaring syntax references. /// </summary> public bool ReuseSyntax { get; } public OptionSet? Options { get; } public ParseOptions? ParseOptions { get; } public CodeGenerationOptions( Location? contextLocation = null, Location? afterThisLocation = null, Location? beforeThisLocation = null, bool addImports = true, bool placeSystemNamespaceFirst = true, IEnumerable<INamespaceSymbol>? additionalImports = null, bool generateMembers = true, bool mergeNestedNamespaces = true, bool mergeAttributes = true, bool generateDefaultAccessibility = true, bool generateMethodBodies = true, bool generateDocumentationComments = false, bool autoInsertionLocation = true, bool sortMembers = true, bool reuseSyntax = false, OptionSet? options = null, ParseOptions? parseOptions = null) { CheckLocation(contextLocation, nameof(contextLocation)); CheckLocation(afterThisLocation, nameof(afterThisLocation)); CheckLocation(beforeThisLocation, nameof(beforeThisLocation)); this.ContextLocation = contextLocation; this.AfterThisLocation = afterThisLocation; this.BeforeThisLocation = beforeThisLocation; this.AddImports = addImports; this.PlaceSystemNamespaceFirst = placeSystemNamespaceFirst; this.AdditionalImports = additionalImports ?? SpecializedCollections.EmptyEnumerable<INamespaceSymbol>(); this.GenerateMembers = generateMembers; this.MergeNestedNamespaces = mergeNestedNamespaces; this.MergeAttributes = mergeAttributes; this.GenerateDefaultAccessibility = generateDefaultAccessibility; this.GenerateMethodBodies = generateMethodBodies; this.GenerateDocumentationComments = generateDocumentationComments; this.AutoInsertionLocation = autoInsertionLocation; this.SortMembers = sortMembers; this.ReuseSyntax = reuseSyntax; this.Options = options; this.ParseOptions = parseOptions ?? this.BestLocation?.SourceTree?.Options; } private static void CheckLocation(Location? location, string name) { if (location != null && !location.IsInSource) { throw new ArgumentException(WorkspacesResources.Location_must_be_null_or_from_source, name); } } internal Location? BestLocation => this.AfterThisLocation ?? this.BeforeThisLocation ?? this.ContextLocation; public CodeGenerationOptions With( Optional<Location> contextLocation = default, Optional<Location?> afterThisLocation = default, Optional<Location?> beforeThisLocation = default, Optional<bool> addImports = default, Optional<bool> placeSystemNamespaceFirst = default, Optional<IEnumerable<INamespaceSymbol>> additionalImports = default, Optional<bool> generateMembers = default, Optional<bool> mergeNestedNamespaces = default, Optional<bool> mergeAttributes = default, Optional<bool> generateDefaultAccessibility = default, Optional<bool> generateMethodBodies = default, Optional<bool> generateDocumentationComments = default, Optional<bool> autoInsertionLocation = default, Optional<bool> sortMembers = default, Optional<bool> reuseSyntax = default, Optional<OptionSet> options = default, Optional<ParseOptions> parseOptions = default) { var newContextLocation = contextLocation.HasValue ? contextLocation.Value : this.ContextLocation; var newAfterThisLocation = afterThisLocation.HasValue ? afterThisLocation.Value : this.AfterThisLocation; var newBeforeThisLocation = beforeThisLocation.HasValue ? beforeThisLocation.Value : this.BeforeThisLocation; var newAddImports = addImports.HasValue ? addImports.Value : this.AddImports; var newPlaceSystemNamespaceFirst = placeSystemNamespaceFirst.HasValue ? placeSystemNamespaceFirst.Value : this.PlaceSystemNamespaceFirst; var newAdditionalImports = additionalImports.HasValue ? additionalImports.Value : this.AdditionalImports; var newGenerateMembers = generateMembers.HasValue ? generateMembers.Value : this.GenerateMembers; var newMergeNestedNamespaces = mergeNestedNamespaces.HasValue ? mergeNestedNamespaces.Value : this.MergeNestedNamespaces; var newMergeAttributes = mergeAttributes.HasValue ? mergeAttributes.Value : this.MergeAttributes; var newGenerateDefaultAccessibility = generateDefaultAccessibility.HasValue ? generateDefaultAccessibility.Value : this.GenerateDefaultAccessibility; var newGenerateMethodBodies = generateMethodBodies.HasValue ? generateMethodBodies.Value : this.GenerateMethodBodies; var newGenerateDocumentationComments = generateDocumentationComments.HasValue ? generateDocumentationComments.Value : this.GenerateDocumentationComments; var newAutoInsertionLocation = autoInsertionLocation.HasValue ? autoInsertionLocation.Value : this.AutoInsertionLocation; var newSortMembers = sortMembers.HasValue ? sortMembers.Value : this.SortMembers; var newReuseSyntax = reuseSyntax.HasValue ? reuseSyntax.Value : this.ReuseSyntax; var newOptions = options.HasValue ? options.Value : this.Options; var newParseOptions = parseOptions.HasValue ? parseOptions.Value : this.ParseOptions; return new CodeGenerationOptions( newContextLocation, newAfterThisLocation, newBeforeThisLocation, newAddImports, newPlaceSystemNamespaceFirst, newAdditionalImports, newGenerateMembers, newMergeNestedNamespaces, newMergeAttributes, newGenerateDefaultAccessibility, newGenerateMethodBodies, newGenerateDocumentationComments, newAutoInsertionLocation, newSortMembers, newReuseSyntax, newOptions, newParseOptions); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { /// <summary> /// Options for controlling the code produced by the <see cref="CodeGenerator"/>. /// </summary> internal class CodeGenerationOptions { public static readonly CodeGenerationOptions Default = new(); /// <summary> /// A location used to determine the best place to generate a member. This is only used for /// determining which part of a partial type to generate in. If a type only has one part, or /// an API is used that specifies the type, then this is not used. A part is preferred if /// it surrounds this context location. If no part surrounds this location then a part is /// preferred if it comes from the same SyntaxTree as this location. If there is no /// such part, then any part may be used for generation. /// /// This option is not necessary if <see cref="AfterThisLocation"/> or <see cref="BeforeThisLocation"/> are /// provided. /// </summary> public Location? ContextLocation { get; } /// <summary> /// A hint to the code generation service to specify where the generated code should be /// placed. Code will be generated after this location if the location is valid in the type /// or symbol being generated into, and it is possible to generate the code after it. /// /// If this option is provided, neither <see cref="ContextLocation"/> nor <see cref="BeforeThisLocation"/> are /// needed. /// </summary> public Location? AfterThisLocation { get; } /// <summary> /// A hint to the code generation service to specify where the generated code should be /// placed. Code will be generated before this location if the location is valid in the type /// or symbol being generated into, and it is possible to generate the code after it. /// /// If this option is provided, neither <see cref="ContextLocation"/> nor <see cref="AfterThisLocation"/> are /// needed. /// </summary> public Location? BeforeThisLocation { get; } /// <summary> /// True if the code generation service should add <see cref="Simplifier.AddImportsAnnotation"/>, /// and when not generating directly into a declaration, should try to automatically add imports to the file /// for any generated code. /// Defaults to true. /// </summary> public bool AddImports { get; } /// <summary> /// True if, when adding a System import, the import should be placed above non-System /// imports. Defaults to true. Only used if <see cref="AddImports"/> is true. /// </summary> public bool PlaceSystemNamespaceFirst { get; } /// <summary> /// Contains additional imports to be automatically added. This is useful for adding /// imports that are part of a list of statements. /// </summary> public IEnumerable<INamespaceSymbol> AdditionalImports { get; } /// <summary> /// True if members of a symbol should also be generated along with the declaration. If /// false, only the symbol's declaration will be generated. /// </summary> public bool GenerateMembers { get; } /// <summary> /// True if the code generator should merge namespaces which only contain other namespaces /// into a single declaration with a dotted name. False if the nesting should be preserved /// and each namespace declaration should be nested and should only have a single non-dotted /// name. /// /// Merging can only occur if the namespace only contains a single member that is also a /// namespace. /// </summary> public bool MergeNestedNamespaces { get; } /// <summary> /// True if the code generation should put multiple attributes in a single attribute /// declaration, or if should have a separate attribute declaration for each attribute. For /// example, in C# setting this to True this would produce "[Goo, Bar]" while setting it to /// False would produce "[Goo][Bar]" /// </summary> public bool MergeAttributes { get; } /// <summary> /// True if the code generator should always generate accessibility modifiers, even if they /// are the same as the defaults for that symbol. For example, a private field in C# does /// not need its accessibility specified as it will be private by default. However, if this /// option is set to true 'private' will still be generated. /// </summary> public bool GenerateDefaultAccessibility { get; } /// <summary> /// True if the code generator should generate empty bodies for methods along with the /// method declaration. If false, only method declarations will be generated. /// </summary> public bool GenerateMethodBodies { get; } /// <summary> /// True if the code generator should generate documentation comments where available /// </summary> public bool GenerateDocumentationComments { get; } /// <summary> /// True if the code generator should automatically attempt to choose the appropriate location /// to insert members. If false and a generation location is not specified by AfterThisLocation, /// or BeforeThisLocation, members will be inserted at the end of the destination definition. /// </summary> public bool AutoInsertionLocation { get; } /// <summary> /// If <see cref="AutoInsertionLocation"/> is <see langword="false"/>, determines if members will be /// sorted before being added to the end of the list of members. /// </summary> public bool SortMembers { get; } /// <summary> /// True if the code generator should attempt to reuse the syntax of the constituent entities, such as members, access modifier tokens, etc. while attempting to generate code. /// If any of the member symbols have zero declaring syntax references (non-source symbols) OR two or more declaring syntax references (partial definitions), then syntax is not reused. /// If false, then the code generator will always synthesize a new syntax node and ignore the declaring syntax references. /// </summary> public bool ReuseSyntax { get; } public OptionSet? Options { get; } public ParseOptions? ParseOptions { get; } public CodeGenerationOptions( Location? contextLocation = null, Location? afterThisLocation = null, Location? beforeThisLocation = null, bool addImports = true, bool placeSystemNamespaceFirst = true, IEnumerable<INamespaceSymbol>? additionalImports = null, bool generateMembers = true, bool mergeNestedNamespaces = true, bool mergeAttributes = true, bool generateDefaultAccessibility = true, bool generateMethodBodies = true, bool generateDocumentationComments = false, bool autoInsertionLocation = true, bool sortMembers = true, bool reuseSyntax = false, OptionSet? options = null, ParseOptions? parseOptions = null) { CheckLocation(contextLocation, nameof(contextLocation)); CheckLocation(afterThisLocation, nameof(afterThisLocation)); CheckLocation(beforeThisLocation, nameof(beforeThisLocation)); this.ContextLocation = contextLocation; this.AfterThisLocation = afterThisLocation; this.BeforeThisLocation = beforeThisLocation; this.AddImports = addImports; this.PlaceSystemNamespaceFirst = placeSystemNamespaceFirst; this.AdditionalImports = additionalImports ?? SpecializedCollections.EmptyEnumerable<INamespaceSymbol>(); this.GenerateMembers = generateMembers; this.MergeNestedNamespaces = mergeNestedNamespaces; this.MergeAttributes = mergeAttributes; this.GenerateDefaultAccessibility = generateDefaultAccessibility; this.GenerateMethodBodies = generateMethodBodies; this.GenerateDocumentationComments = generateDocumentationComments; this.AutoInsertionLocation = autoInsertionLocation; this.SortMembers = sortMembers; this.ReuseSyntax = reuseSyntax; this.Options = options; this.ParseOptions = parseOptions ?? this.BestLocation?.SourceTree?.Options; } private static void CheckLocation(Location? location, string name) { if (location != null && !location.IsInSource) { throw new ArgumentException(WorkspacesResources.Location_must_be_null_or_from_source, name); } } internal Location? BestLocation => this.AfterThisLocation ?? this.BeforeThisLocation ?? this.ContextLocation; public CodeGenerationOptions With( Optional<Location> contextLocation = default, Optional<Location?> afterThisLocation = default, Optional<Location?> beforeThisLocation = default, Optional<bool> addImports = default, Optional<bool> placeSystemNamespaceFirst = default, Optional<IEnumerable<INamespaceSymbol>> additionalImports = default, Optional<bool> generateMembers = default, Optional<bool> mergeNestedNamespaces = default, Optional<bool> mergeAttributes = default, Optional<bool> generateDefaultAccessibility = default, Optional<bool> generateMethodBodies = default, Optional<bool> generateDocumentationComments = default, Optional<bool> autoInsertionLocation = default, Optional<bool> sortMembers = default, Optional<bool> reuseSyntax = default, Optional<OptionSet> options = default, Optional<ParseOptions> parseOptions = default) { var newContextLocation = contextLocation.HasValue ? contextLocation.Value : this.ContextLocation; var newAfterThisLocation = afterThisLocation.HasValue ? afterThisLocation.Value : this.AfterThisLocation; var newBeforeThisLocation = beforeThisLocation.HasValue ? beforeThisLocation.Value : this.BeforeThisLocation; var newAddImports = addImports.HasValue ? addImports.Value : this.AddImports; var newPlaceSystemNamespaceFirst = placeSystemNamespaceFirst.HasValue ? placeSystemNamespaceFirst.Value : this.PlaceSystemNamespaceFirst; var newAdditionalImports = additionalImports.HasValue ? additionalImports.Value : this.AdditionalImports; var newGenerateMembers = generateMembers.HasValue ? generateMembers.Value : this.GenerateMembers; var newMergeNestedNamespaces = mergeNestedNamespaces.HasValue ? mergeNestedNamespaces.Value : this.MergeNestedNamespaces; var newMergeAttributes = mergeAttributes.HasValue ? mergeAttributes.Value : this.MergeAttributes; var newGenerateDefaultAccessibility = generateDefaultAccessibility.HasValue ? generateDefaultAccessibility.Value : this.GenerateDefaultAccessibility; var newGenerateMethodBodies = generateMethodBodies.HasValue ? generateMethodBodies.Value : this.GenerateMethodBodies; var newGenerateDocumentationComments = generateDocumentationComments.HasValue ? generateDocumentationComments.Value : this.GenerateDocumentationComments; var newAutoInsertionLocation = autoInsertionLocation.HasValue ? autoInsertionLocation.Value : this.AutoInsertionLocation; var newSortMembers = sortMembers.HasValue ? sortMembers.Value : this.SortMembers; var newReuseSyntax = reuseSyntax.HasValue ? reuseSyntax.Value : this.ReuseSyntax; var newOptions = options.HasValue ? options.Value : this.Options; var newParseOptions = parseOptions.HasValue ? parseOptions.Value : this.ParseOptions; return new CodeGenerationOptions( newContextLocation, newAfterThisLocation, newBeforeThisLocation, newAddImports, newPlaceSystemNamespaceFirst, newAdditionalImports, newGenerateMembers, newMergeNestedNamespaces, newMergeAttributes, newGenerateDefaultAccessibility, newGenerateMethodBodies, newGenerateDocumentationComments, newAutoInsertionLocation, newSortMembers, newReuseSyntax, newOptions, newParseOptions); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UseAutoProperty; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseAutoProperty { public class UseAutoPropertyTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseAutoPropertyTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseAutoPropertyAnalyzer(), GetCSharpUseAutoPropertyCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleGetterFromField() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } } }", @"class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleGetterFromField_FileScopedNamespace() { await TestInRegularAndScript1Async( @" namespace N; class Class { [|int i|]; int P { get { return i; } } }", @" namespace N; class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleGetterFromField_InRecord() { await TestInRegularAndScript1Async( @"record Class { [|int i|]; int P { get { return i; } } }", @"record Class { int P { get; } }", new TestParameters(TestOptions.RegularPreview)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestNullable1() { // ⚠ The expected outcome of this test should not change. await TestMissingInRegularAndScriptAsync( @"class Class { [|MutableInt? i|]; MutableInt? P { get { return i; } } } struct MutableInt { public int Value; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestNullable2() { await TestInRegularAndScript1Async( @"class Class { [|readonly MutableInt? i|]; MutableInt? P { get { return i; } } } struct MutableInt { public int Value; }", @"class Class { MutableInt? P { get; } } struct MutableInt { public int Value; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestNullable3() { await TestInRegularAndScript1Async( @"class Class { [|int? i|]; int? P { get { return i; } } }", @"class Class { int? P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestNullable4() { await TestInRegularAndScript1Async( @"class Class { [|readonly int? i|]; int? P { get { return i; } } }", @"class Class { int? P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestNullable5() { // Recursive type check await TestMissingInRegularAndScriptAsync( @"using System; class Class { [|Nullable<MutableInt?> i|]; Nullable<MutableInt?> P { get { return i; } } } struct MutableInt { public int Value; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestMutableValueType1() { await TestMissingInRegularAndScriptAsync( @"class Class { [|MutableInt i|]; MutableInt P { get { return i; } } } struct MutableInt { public int Value; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestMutableValueType2() { await TestInRegularAndScript1Async( @"class Class { [|readonly MutableInt i|]; MutableInt P { get { return i; } } } struct MutableInt { public int Value; }", @"class Class { MutableInt P { get; } } struct MutableInt { public int Value; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestMutableValueType3() { await TestMissingInRegularAndScriptAsync( @"class Class { [|MutableInt i|]; MutableInt P { get { return i; } } } struct MutableInt { public int Value { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestErrorType1() { await TestMissingInRegularAndScriptAsync( @"class Class { [|ErrorType i|]; ErrorType P { get { return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestErrorType2() { await TestInRegularAndScript1Async( @"class Class { [|readonly ErrorType i|]; ErrorType P { get { return i; } } }", @"class Class { ErrorType P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestErrorType3() { await TestMissingInRegularAndScriptAsync( @"class Class { [|ErrorType? i|]; ErrorType? P { get { return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestErrorType4() { await TestInRegularAndScript1Async( @"class Class { [|readonly ErrorType? i|]; ErrorType? P { get { return i; } } }", @"class Class { ErrorType? P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestErrorType5() { await TestInRegularAndScript1Async( @"class Class { [|ErrorType[] i|]; ErrorType[] P { get { return i; } } }", @"class Class { ErrorType[] P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestCSharp5_1() { await TestAsync( @"class Class { [|int i|]; public int P { get { return i; } } }", @"class Class { public int P { get; private set; } }", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestCSharp5_2() { await TestMissingAsync( @"class Class { [|readonly int i|]; int P { get { return i; } } }", new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestInitializer() { await TestInRegularAndScript1Async( @"class Class { [|int i = 1|]; int P { get { return i; } } }", @"class Class { int P { get; } = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestInitializer_CSharp5() { await TestMissingAsync( @"class Class { [|int i = 1|]; int P { get { return i; } } }", new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleGetterFromProperty() { await TestInRegularAndScript1Async( @"class Class { int i; [|int P { get { return i; } }|] }", @"class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleSetter() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { set { i = value; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestGetterAndSetter() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } set { i = value; } } }", @"class Class { int P { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleGetterWithThis() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return this.i; } } }", @"class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleSetterWithThis() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { set { this.i = value; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestGetterAndSetterWithThis() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return this.i; } set { this.i = value; } } }", @"class Class { int P { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestGetterWithMutipleStatements() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { ; return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSetterWithMutipleStatements() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { set { ; i = value; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSetterWithMultipleStatementsAndGetterWithSingleStatement() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { return i; } set { ; i = value; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestGetterAndSetterUseDifferentFields() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int j; int P { get { return i; } set { j = value; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestFieldAndPropertyHaveDifferentStaticInstance() { await TestMissingInRegularAndScriptAsync( @"class Class { [|static int i|]; int P { get { return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotIfFieldUsedInRefArgument1() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { return i; } } void M(ref int x) { M(ref i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotIfFieldUsedInRefArgument2() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { return i; } } void M(ref int x) { M(ref this.i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotIfFieldUsedInOutArgument() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { return i; } } void M(out int x) { M(out i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotIfFieldUsedInInArgument() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { return i; } } void M(in int x) { M(in i); } }"); } [WorkItem(25429, "https://github.com/dotnet/roslyn/issues/25429")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotIfFieldUsedInRefExpression() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { return i; } } void M() { ref int x = ref i; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotIfFieldUsedInRefExpression_AsCandidateSymbol() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { return i; } } void M() { // because we refer to 'i' statically, it only gets resolved as a candidate symbol // let's be conservative here and disable the analyzer if we're not sure ref int x = ref Class.i; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestIfUnrelatedSymbolUsedInRefExpression() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int j; int P { get { return i; } } void M() { int i; ref int x = ref i; ref int y = ref j; } }", @"class Class { int j; int P { get; } void M() { int i; ref int x = ref i; ref int y = ref j; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotWithVirtualProperty() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; public virtual int P { get { return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotWithConstField() { await TestMissingInRegularAndScriptAsync( @"class Class { [|const int i|]; int P { get { return i; } } }"); } [WorkItem(25379, "https://github.com/dotnet/roslyn/issues/25379")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotWithVolatileField() { await TestMissingInRegularAndScriptAsync( @"class Class { [|volatile int i|]; int P { get { return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestFieldWithMultipleDeclarators1() { await TestInRegularAndScript1Async( @"class Class { int [|i|], j, k; int P { get { return i; } } }", @"class Class { int j, k; int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestFieldWithMultipleDeclarators2() { await TestInRegularAndScript1Async( @"class Class { int i, [|j|], k; int P { get { return j; } } }", @"class Class { int i, k; int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestFieldWithMultipleDeclarators3() { await TestInRegularAndScript1Async( @"class Class { int i, j, [|k|]; int P { get { return k; } } }", @"class Class { int i, j; int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestFieldAndPropertyInDifferentParts() { await TestInRegularAndScript1Async( @"partial class Class { [|int i|]; } partial class Class { int P { get { return i; } } }", @"partial class Class { } partial class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotWithFieldWithAttribute() { await TestMissingInRegularAndScriptAsync( @"class Class { [|[A] int i|]; int P { get { return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestUpdateReferences() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } } public Class() { i = 1; } }", @"class Class { int P { get; } public Class() { P = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestUpdateReferencesConflictResolution() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } } public Class(int P) { i = 1; } }", @"class Class { int P { get; } public Class(int P) { this.P = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInConstructor() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } } public Class() { i = 1; } }", @"class Class { int P { get; } public Class() { P = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInNotInConstructor1() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } } public void Goo() { i = 1; } }", @"class Class { int P { get; set; } public void Goo() { P = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInNotInConstructor2() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; public int P { get { return i; } } public void Goo() { i = 1; } }", @"class Class { public int P { get; private set; } public void Goo() { P = 1; } }"); } [WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInSimpleExpressionLambdaInConstructor() { await TestInRegularAndScript1Async( @"using System; class C { [|int i|]; int P => i; C() { Action<int> x = _ => i = 1; } }", @"using System; class C { int P { get; set; } C() { Action<int> x = _ => P = 1; } }"); } [WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInSimpleBlockLambdaInConstructor() { await TestInRegularAndScript1Async( @"using System; class C { [|int i|]; int P => i; C() { Action<int> x = _ => { i = 1; }; } }", @"using System; class C { int P { get; set; } C() { Action<int> x = _ => { P = 1; }; } }"); } [WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInParenthesizedExpressionLambdaInConstructor() { await TestInRegularAndScript1Async( @"using System; class C { [|int i|]; int P => i; C() { Action x = () => i = 1; } }", @"using System; class C { int P { get; set; } C() { Action x = () => P = 1; } }"); } [WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInParenthesizedBlockLambdaInConstructor() { await TestInRegularAndScript1Async( @"using System; class C { [|int i|]; int P => i; C() { Action x = () => { i = 1; }; } }", @"using System; class C { int P { get; set; } C() { Action x = () => { P = 1; }; } }"); } [WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInAnonymousMethodInConstructor() { await TestInRegularAndScript1Async( @"using System; class C { [|int i|]; int P => i; C() { Action x = delegate () { i = 1; }; } }", @"using System; class C { int P { get; set; } C() { Action x = delegate () { P = 1; }; } }"); } [WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInLocalFunctionInConstructor() { await TestInRegularAndScript1Async( @"class C { [|int i|]; int P => i; C() { void F() { i = 1; } } }", @"class C { int P { get; set; } C() { void F() { P = 1; } } }"); } [WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInExpressionBodiedLocalFunctionInConstructor() { await TestInRegularAndScript1Async( @"class C { [|int i|]; int P => i; C() { void F() => i = 1; } }", @"class C { int P { get; set; } C() { void F() => P = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestReadInExpressionBodiedLocalFunctionInConstructor() { await TestInRegularAndScript1Async( @"class C { [|int i|]; int P => i; C() { bool F() => i == 1; } }", @"class C { int P { get; } C() { bool F() => P == 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestAlreadyAutoPropertyWithGetterWithNoBody() { await TestMissingInRegularAndScriptAsync( @"class Class { public int [|P|] { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestAlreadyAutoPropertyWithGetterAndSetterWithNoBody() { await TestMissingInRegularAndScriptAsync( @"class Class { public int [|P|] { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleLine1() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } } }", @"class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleLine2() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } } }", @"class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleLine3() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } set { i = value; } } }", @"class Class { int P { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task Tuple_SingleGetterFromField() { await TestInRegularAndScript1Async( @"class Class { [|readonly (int, string) i|]; (int, string) P { get { return i; } } }", @"class Class { (int, string) P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TupleWithNames_SingleGetterFromField() { await TestInRegularAndScript1Async( @"class Class { [|readonly (int a, string b) i|]; (int a, string b) P { get { return i; } } }", @"class Class { (int a, string b) P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TupleWithDifferentNames_SingleGetterFromField() { await TestMissingInRegularAndScriptAsync( @"class Class { [|readonly (int a, string b) i|]; (int c, string d) P { get { return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TupleWithOneName_SingleGetterFromField() { await TestInRegularAndScript1Async( @"class Class { [|readonly (int a, string) i|]; (int a, string) P { get { return i; } } }", @"class Class { (int a, string) P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task Tuple_Initializer() { await TestInRegularAndScript1Async( @"class Class { [|readonly (int, string) i = (1, ""hello"")|]; (int, string) P { get { return i; } } }", @"class Class { (int, string) P { get; } = (1, ""hello""); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task Tuple_GetterAndSetter() { await TestMissingInRegularAndScriptAsync( @"class Class { [|(int, string) i|]; (int, string) P { get { return i; } set { i = value; } } }"); } [WorkItem(23215, "https://github.com/dotnet/roslyn/issues/23215")] [WorkItem(23216, "https://github.com/dotnet/roslyn/issues/23216")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestFixAllInDocument() { await TestInRegularAndScript1Async( @"class Class { {|FixAllInDocument:int i|}; int P { get { return i; } } int j; int Q { get { return j; } } }", @"class Class { int P { get; } int Q { get; } }"); } [WorkItem(23735, "https://github.com/dotnet/roslyn/issues/23735")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExplicitInterfaceImplementationGetterOnly() { await TestMissingInRegularAndScriptAsync(@" namespace RoslynSandbox { public interface IFoo { object Bar { get; } } class Foo : IFoo { public Foo(object bar) { this.bar = bar; } readonly object [|bar|]; object IFoo.Bar { get { return bar; } } } }"); } [WorkItem(23735, "https://github.com/dotnet/roslyn/issues/23735")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExplicitInterfaceImplementationGetterAndSetter() { await TestMissingInRegularAndScriptAsync(@" namespace RoslynSandbox { public interface IFoo { object Bar { get; set; } } class Foo : IFoo { public Foo(object bar) { this.bar = bar; } object [|bar|]; object IFoo.Bar { get { return bar; } set { bar = value; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedMemberGetOnly() { await TestInRegularAndScript1Async( @"class Class { int [|i|]; int P { get => i; } }", @"class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedMemberGetOnlyWithInitializer() { await TestInRegularAndScript1Async( @"class Class { int [|i|] = 1; int P { get => i; } }", @"class Class { int P { get; } = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedMemberGetOnlyWithInitializerAndNeedsSetter() { await TestInRegularAndScript1Async( @"class Class { int [|i|] = 1; int P { get => i; } void M() { i = 2; } }", @"class Class { int P { get; set; } = 1; void M() { P = 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedMemberGetterAndSetter() { await TestInRegularAndScript1Async( @"class Class { int [|i|]; int P { get => i; set { i = value; } } }", @"class Class { int P { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedMemberGetter() { await TestInRegularAndScript1Async( @"class Class { int [|i|]; int P => i; }", @"class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedMemberGetterWithSetterNeeded() { await TestInRegularAndScript1Async( @"class Class { int [|i|]; int P => i; void M() { i = 1; } }", @"class Class { int P { get; set; } void M() { P = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedMemberGetterWithInitializer() { await TestInRegularAndScript1Async( @"class Class { int [|i|] = 1; int P => i; }", @"class Class { int P { get; } = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedGetterAndSetter() { await TestInRegularAndScript1Async( @"class Class { int [|i|]; int P { get => i; set => i = value; } }", @"class Class { int P { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedGetterAndSetterWithInitializer() { await TestInRegularAndScript1Async( @"class Class { int [|i|] = 1; int P { get => i; set => i = value; } }", @"class Class { int P { get; set; } = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(25401, "https://github.com/dotnet/roslyn/issues/25401")] public async Task TestGetterAccessibilityDiffers() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; public int P { protected get { return i; } set { i = value; } } }", @"class Class { public int P { protected get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(25401, "https://github.com/dotnet/roslyn/issues/25401")] public async Task TestSetterAccessibilityDiffers() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; public int P { get { return i; } protected set { i = value; } } }", @"class Class { public int P { get; protected set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")] public async Task TestPreserveTrailingTrivia1() { await TestInRegularAndScript1Async( @"class Goo { private readonly object [|bar|] = new object(); public object Bar => bar; public int Baz => 0; }", @"class Goo { public object Bar { get; } = new object(); public int Baz => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")] public async Task TestPreserveTrailingTrivia2() { await TestInRegularAndScript1Async( @"class Goo { private readonly object [|bar|] = new object(); public object Bar => bar; // prop comment public int Baz => 0; }", @"class Goo { public object Bar { get; } = new object(); // prop comment public int Baz => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")] public async Task TestPreserveTrailingTrivia3() { await TestInRegularAndScript1Async( @"class Goo { private readonly object [|bar|] = new object(); // doc public object Bar => bar; // prop comment public int Baz => 0; }", @"class Goo { // doc public object Bar { get; } = new object(); // prop comment public int Baz => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")] public async Task TestKeepLeadingBlank() { await TestInRegularAndScript1Async( @"class Goo { private readonly object [|bar|] = new object(); // doc public object Bar => bar; // prop comment public int Baz => 0; }", @"class Goo { // doc public object Bar { get; } = new object(); // prop comment public int Baz => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsAbove1() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int j; int P { get { return i; } } }", @"class Class { int j; int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsAbove2() { await TestInRegularAndScript1Async( @"class Class { int j; [|int i|]; int P { get { return i; } } }", @"class Class { int j; int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsAbove3() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int j; int P { get { return i; } } }", @"class Class { int j; int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsAbove4() { await TestInRegularAndScript1Async( @"class Class { int j; [|int i|]; int P { get { return i; } } }", @"class Class { int j; int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsBelow1() { await TestInRegularAndScript1Async( @"class Class { int P { get { return i; } } [|int i|]; int j; }", @"class Class { int P { get; } int j; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsBelow2() { await TestInRegularAndScript1Async( @"class Class { int P { get { return i; } } int j; [|int i|]; }", @"class Class { int P { get; } int j; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsBelow3() { await TestInRegularAndScript1Async( @"class Class { int P { get { return i; } } [|int i|]; int j; }", @"class Class { int P { get; } int j; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsBelow4() { await TestInRegularAndScript1Async( @"class Class { int P { get { return i; } } int j; [|int i|]; }", @"class Class { int P { get; } int j; }"); } [WorkItem(27675, "https://github.com/dotnet/roslyn/issues/27675")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleLineWithDirective() { await TestInRegularAndScript1Async( @"class Class { #region Test [|int i|]; #endregion int P { get { return i; } } }", @"class Class { #region Test #endregion int P { get; } }"); } [WorkItem(27675, "https://github.com/dotnet/roslyn/issues/27675")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsWithDirective() { await TestInRegularAndScript1Async( @"class Class { #region Test [|int i|]; int j; #endregion int P { get { return i; } } }", @"class Class { #region Test int j; #endregion int P { get; } }"); } [WorkItem(27675, "https://github.com/dotnet/roslyn/issues/27675")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleLineWithDoubleDirectives() { await TestInRegularAndScript1Async( @"class TestClass { #region Field [|int i|]; #endregion #region Property int P { get { return i; } } #endregion }", @"class TestClass { #region Field #endregion #region Property int P { get; } #endregion }"); } [WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestUseTabs() { await TestInRegularAndScript1Async( @"public class Foo { private readonly object o; [||]public object O => o; }", @"public class Foo { public object O { get; } }", new TestParameters(options: Option(FormattingOptions2.UseTabs, true))); } [WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestUseSpaces() { await TestInRegularAndScript1Async( @"public class Foo { private readonly object o; [||]public object O => o; }", @"public class Foo { public object O { get; } }", new TestParameters(options: Option(FormattingOptions2.UseTabs, false))); } [WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestUseTabs_Editorconfig() { await TestInRegularAndScript1Async( @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> public class Foo { private readonly object o; [||]public object O => o; } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig""> [*] indent_style = tab </AnalyzerConfigDocument> </Project> </Workspace>", @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> public class Foo { public object O { get; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig""> [*] indent_style = tab </AnalyzerConfigDocument> </Project> </Workspace>"); } [WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestUseSpaces_Editorconfig() { await TestInRegularAndScript1Async( @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> public class Foo { private readonly object o; [||]public object O => o; } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig""> [*] indent_style = space </AnalyzerConfigDocument> </Project> </Workspace>", @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> public class Foo { public object O { get; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig""> [*] indent_style = space </AnalyzerConfigDocument> </Project> </Workspace>"); } [WorkItem(34783, "https://github.com/dotnet/roslyn/issues/34783")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotOnSerializableType() { await TestMissingAsync( @" [System.Serializable] class Class { [|int i|]; int P { get { return i; } } }"); } [WorkItem(47999, "https://github.com/dotnet/roslyn/issues/47999")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestPropertyIsReadOnlyAndSetterNeeded() { await TestInRegularAndScript1Async( @"struct S { [|int i|]; public readonly int P => i; public void SetP(int value) => i = value; }", @"struct S { public int P { get; private set; } public void SetP(int value) => P = value; }"); } [WorkItem(47999, "https://github.com/dotnet/roslyn/issues/47999")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestPropertyIsReadOnlyWithNoAccessModifierAndSetterNeeded() { await TestInRegularAndScript1Async( @"struct S { [|int i|]; readonly int P => i; public void SetP(int value) => i = value; }", @"struct S { int P { get; set; } public void SetP(int value) => P = value; }"); } [WorkItem(47999, "https://github.com/dotnet/roslyn/issues/47999")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestPropertyIsReadOnlyAndSetterUnneeded() { await TestInRegularAndScript1Async( @"struct S { [|int i|]; public readonly int P => i; }", @"struct S { public readonly int P { get; } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UseAutoProperty; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseAutoProperty { public class UseAutoPropertyTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseAutoPropertyTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseAutoPropertyAnalyzer(), GetCSharpUseAutoPropertyCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleGetterFromField() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } } }", @"class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleGetterFromField_FileScopedNamespace() { await TestInRegularAndScript1Async( @" namespace N; class Class { [|int i|]; int P { get { return i; } } }", @" namespace N; class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleGetterFromField_InRecord() { await TestInRegularAndScript1Async( @"record Class { [|int i|]; int P { get { return i; } } }", @"record Class { int P { get; } }", new TestParameters(TestOptions.RegularPreview)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestNullable1() { // ⚠ The expected outcome of this test should not change. await TestMissingInRegularAndScriptAsync( @"class Class { [|MutableInt? i|]; MutableInt? P { get { return i; } } } struct MutableInt { public int Value; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestNullable2() { await TestInRegularAndScript1Async( @"class Class { [|readonly MutableInt? i|]; MutableInt? P { get { return i; } } } struct MutableInt { public int Value; }", @"class Class { MutableInt? P { get; } } struct MutableInt { public int Value; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestNullable3() { await TestInRegularAndScript1Async( @"class Class { [|int? i|]; int? P { get { return i; } } }", @"class Class { int? P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestNullable4() { await TestInRegularAndScript1Async( @"class Class { [|readonly int? i|]; int? P { get { return i; } } }", @"class Class { int? P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestNullable5() { // Recursive type check await TestMissingInRegularAndScriptAsync( @"using System; class Class { [|Nullable<MutableInt?> i|]; Nullable<MutableInt?> P { get { return i; } } } struct MutableInt { public int Value; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestMutableValueType1() { await TestMissingInRegularAndScriptAsync( @"class Class { [|MutableInt i|]; MutableInt P { get { return i; } } } struct MutableInt { public int Value; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestMutableValueType2() { await TestInRegularAndScript1Async( @"class Class { [|readonly MutableInt i|]; MutableInt P { get { return i; } } } struct MutableInt { public int Value; }", @"class Class { MutableInt P { get; } } struct MutableInt { public int Value; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestMutableValueType3() { await TestMissingInRegularAndScriptAsync( @"class Class { [|MutableInt i|]; MutableInt P { get { return i; } } } struct MutableInt { public int Value { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestErrorType1() { await TestMissingInRegularAndScriptAsync( @"class Class { [|ErrorType i|]; ErrorType P { get { return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestErrorType2() { await TestInRegularAndScript1Async( @"class Class { [|readonly ErrorType i|]; ErrorType P { get { return i; } } }", @"class Class { ErrorType P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestErrorType3() { await TestMissingInRegularAndScriptAsync( @"class Class { [|ErrorType? i|]; ErrorType? P { get { return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestErrorType4() { await TestInRegularAndScript1Async( @"class Class { [|readonly ErrorType? i|]; ErrorType? P { get { return i; } } }", @"class Class { ErrorType? P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")] public async Task TestErrorType5() { await TestInRegularAndScript1Async( @"class Class { [|ErrorType[] i|]; ErrorType[] P { get { return i; } } }", @"class Class { ErrorType[] P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestCSharp5_1() { await TestAsync( @"class Class { [|int i|]; public int P { get { return i; } } }", @"class Class { public int P { get; private set; } }", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestCSharp5_2() { await TestMissingAsync( @"class Class { [|readonly int i|]; int P { get { return i; } } }", new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestInitializer() { await TestInRegularAndScript1Async( @"class Class { [|int i = 1|]; int P { get { return i; } } }", @"class Class { int P { get; } = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestInitializer_CSharp5() { await TestMissingAsync( @"class Class { [|int i = 1|]; int P { get { return i; } } }", new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleGetterFromProperty() { await TestInRegularAndScript1Async( @"class Class { int i; [|int P { get { return i; } }|] }", @"class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleSetter() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { set { i = value; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestGetterAndSetter() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } set { i = value; } } }", @"class Class { int P { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleGetterWithThis() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return this.i; } } }", @"class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleSetterWithThis() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { set { this.i = value; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestGetterAndSetterWithThis() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return this.i; } set { this.i = value; } } }", @"class Class { int P { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestGetterWithMutipleStatements() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { ; return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSetterWithMutipleStatements() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { set { ; i = value; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSetterWithMultipleStatementsAndGetterWithSingleStatement() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { return i; } set { ; i = value; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestGetterAndSetterUseDifferentFields() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int j; int P { get { return i; } set { j = value; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestFieldAndPropertyHaveDifferentStaticInstance() { await TestMissingInRegularAndScriptAsync( @"class Class { [|static int i|]; int P { get { return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotIfFieldUsedInRefArgument1() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { return i; } } void M(ref int x) { M(ref i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotIfFieldUsedInRefArgument2() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { return i; } } void M(ref int x) { M(ref this.i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotIfFieldUsedInOutArgument() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { return i; } } void M(out int x) { M(out i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotIfFieldUsedInInArgument() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { return i; } } void M(in int x) { M(in i); } }"); } [WorkItem(25429, "https://github.com/dotnet/roslyn/issues/25429")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotIfFieldUsedInRefExpression() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { return i; } } void M() { ref int x = ref i; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotIfFieldUsedInRefExpression_AsCandidateSymbol() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; int P { get { return i; } } void M() { // because we refer to 'i' statically, it only gets resolved as a candidate symbol // let's be conservative here and disable the analyzer if we're not sure ref int x = ref Class.i; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestIfUnrelatedSymbolUsedInRefExpression() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int j; int P { get { return i; } } void M() { int i; ref int x = ref i; ref int y = ref j; } }", @"class Class { int j; int P { get; } void M() { int i; ref int x = ref i; ref int y = ref j; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotWithVirtualProperty() { await TestMissingInRegularAndScriptAsync( @"class Class { [|int i|]; public virtual int P { get { return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotWithConstField() { await TestMissingInRegularAndScriptAsync( @"class Class { [|const int i|]; int P { get { return i; } } }"); } [WorkItem(25379, "https://github.com/dotnet/roslyn/issues/25379")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotWithVolatileField() { await TestMissingInRegularAndScriptAsync( @"class Class { [|volatile int i|]; int P { get { return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestFieldWithMultipleDeclarators1() { await TestInRegularAndScript1Async( @"class Class { int [|i|], j, k; int P { get { return i; } } }", @"class Class { int j, k; int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestFieldWithMultipleDeclarators2() { await TestInRegularAndScript1Async( @"class Class { int i, [|j|], k; int P { get { return j; } } }", @"class Class { int i, k; int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestFieldWithMultipleDeclarators3() { await TestInRegularAndScript1Async( @"class Class { int i, j, [|k|]; int P { get { return k; } } }", @"class Class { int i, j; int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestFieldAndPropertyInDifferentParts() { await TestInRegularAndScript1Async( @"partial class Class { [|int i|]; } partial class Class { int P { get { return i; } } }", @"partial class Class { } partial class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotWithFieldWithAttribute() { await TestMissingInRegularAndScriptAsync( @"class Class { [|[A] int i|]; int P { get { return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestUpdateReferences() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } } public Class() { i = 1; } }", @"class Class { int P { get; } public Class() { P = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestUpdateReferencesConflictResolution() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } } public Class(int P) { i = 1; } }", @"class Class { int P { get; } public Class(int P) { this.P = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInConstructor() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } } public Class() { i = 1; } }", @"class Class { int P { get; } public Class() { P = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInNotInConstructor1() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } } public void Goo() { i = 1; } }", @"class Class { int P { get; set; } public void Goo() { P = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInNotInConstructor2() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; public int P { get { return i; } } public void Goo() { i = 1; } }", @"class Class { public int P { get; private set; } public void Goo() { P = 1; } }"); } [WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInSimpleExpressionLambdaInConstructor() { await TestInRegularAndScript1Async( @"using System; class C { [|int i|]; int P => i; C() { Action<int> x = _ => i = 1; } }", @"using System; class C { int P { get; set; } C() { Action<int> x = _ => P = 1; } }"); } [WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInSimpleBlockLambdaInConstructor() { await TestInRegularAndScript1Async( @"using System; class C { [|int i|]; int P => i; C() { Action<int> x = _ => { i = 1; }; } }", @"using System; class C { int P { get; set; } C() { Action<int> x = _ => { P = 1; }; } }"); } [WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInParenthesizedExpressionLambdaInConstructor() { await TestInRegularAndScript1Async( @"using System; class C { [|int i|]; int P => i; C() { Action x = () => i = 1; } }", @"using System; class C { int P { get; set; } C() { Action x = () => P = 1; } }"); } [WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInParenthesizedBlockLambdaInConstructor() { await TestInRegularAndScript1Async( @"using System; class C { [|int i|]; int P => i; C() { Action x = () => { i = 1; }; } }", @"using System; class C { int P { get; set; } C() { Action x = () => { P = 1; }; } }"); } [WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInAnonymousMethodInConstructor() { await TestInRegularAndScript1Async( @"using System; class C { [|int i|]; int P => i; C() { Action x = delegate () { i = 1; }; } }", @"using System; class C { int P { get; set; } C() { Action x = delegate () { P = 1; }; } }"); } [WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInLocalFunctionInConstructor() { await TestInRegularAndScript1Async( @"class C { [|int i|]; int P => i; C() { void F() { i = 1; } } }", @"class C { int P { get; set; } C() { void F() { P = 1; } } }"); } [WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestWriteInExpressionBodiedLocalFunctionInConstructor() { await TestInRegularAndScript1Async( @"class C { [|int i|]; int P => i; C() { void F() => i = 1; } }", @"class C { int P { get; set; } C() { void F() => P = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestReadInExpressionBodiedLocalFunctionInConstructor() { await TestInRegularAndScript1Async( @"class C { [|int i|]; int P => i; C() { bool F() => i == 1; } }", @"class C { int P { get; } C() { bool F() => P == 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestAlreadyAutoPropertyWithGetterWithNoBody() { await TestMissingInRegularAndScriptAsync( @"class Class { public int [|P|] { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestAlreadyAutoPropertyWithGetterAndSetterWithNoBody() { await TestMissingInRegularAndScriptAsync( @"class Class { public int [|P|] { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleLine1() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } } }", @"class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleLine2() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } } }", @"class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleLine3() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int P { get { return i; } set { i = value; } } }", @"class Class { int P { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task Tuple_SingleGetterFromField() { await TestInRegularAndScript1Async( @"class Class { [|readonly (int, string) i|]; (int, string) P { get { return i; } } }", @"class Class { (int, string) P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TupleWithNames_SingleGetterFromField() { await TestInRegularAndScript1Async( @"class Class { [|readonly (int a, string b) i|]; (int a, string b) P { get { return i; } } }", @"class Class { (int a, string b) P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TupleWithDifferentNames_SingleGetterFromField() { await TestMissingInRegularAndScriptAsync( @"class Class { [|readonly (int a, string b) i|]; (int c, string d) P { get { return i; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TupleWithOneName_SingleGetterFromField() { await TestInRegularAndScript1Async( @"class Class { [|readonly (int a, string) i|]; (int a, string) P { get { return i; } } }", @"class Class { (int a, string) P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task Tuple_Initializer() { await TestInRegularAndScript1Async( @"class Class { [|readonly (int, string) i = (1, ""hello"")|]; (int, string) P { get { return i; } } }", @"class Class { (int, string) P { get; } = (1, ""hello""); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task Tuple_GetterAndSetter() { await TestMissingInRegularAndScriptAsync( @"class Class { [|(int, string) i|]; (int, string) P { get { return i; } set { i = value; } } }"); } [WorkItem(23215, "https://github.com/dotnet/roslyn/issues/23215")] [WorkItem(23216, "https://github.com/dotnet/roslyn/issues/23216")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestFixAllInDocument() { await TestInRegularAndScript1Async( @"class Class { {|FixAllInDocument:int i|}; int P { get { return i; } } int j; int Q { get { return j; } } }", @"class Class { int P { get; } int Q { get; } }"); } [WorkItem(23735, "https://github.com/dotnet/roslyn/issues/23735")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExplicitInterfaceImplementationGetterOnly() { await TestMissingInRegularAndScriptAsync(@" namespace RoslynSandbox { public interface IFoo { object Bar { get; } } class Foo : IFoo { public Foo(object bar) { this.bar = bar; } readonly object [|bar|]; object IFoo.Bar { get { return bar; } } } }"); } [WorkItem(23735, "https://github.com/dotnet/roslyn/issues/23735")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExplicitInterfaceImplementationGetterAndSetter() { await TestMissingInRegularAndScriptAsync(@" namespace RoslynSandbox { public interface IFoo { object Bar { get; set; } } class Foo : IFoo { public Foo(object bar) { this.bar = bar; } object [|bar|]; object IFoo.Bar { get { return bar; } set { bar = value; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedMemberGetOnly() { await TestInRegularAndScript1Async( @"class Class { int [|i|]; int P { get => i; } }", @"class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedMemberGetOnlyWithInitializer() { await TestInRegularAndScript1Async( @"class Class { int [|i|] = 1; int P { get => i; } }", @"class Class { int P { get; } = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedMemberGetOnlyWithInitializerAndNeedsSetter() { await TestInRegularAndScript1Async( @"class Class { int [|i|] = 1; int P { get => i; } void M() { i = 2; } }", @"class Class { int P { get; set; } = 1; void M() { P = 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedMemberGetterAndSetter() { await TestInRegularAndScript1Async( @"class Class { int [|i|]; int P { get => i; set { i = value; } } }", @"class Class { int P { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedMemberGetter() { await TestInRegularAndScript1Async( @"class Class { int [|i|]; int P => i; }", @"class Class { int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedMemberGetterWithSetterNeeded() { await TestInRegularAndScript1Async( @"class Class { int [|i|]; int P => i; void M() { i = 1; } }", @"class Class { int P { get; set; } void M() { P = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedMemberGetterWithInitializer() { await TestInRegularAndScript1Async( @"class Class { int [|i|] = 1; int P => i; }", @"class Class { int P { get; } = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedGetterAndSetter() { await TestInRegularAndScript1Async( @"class Class { int [|i|]; int P { get => i; set => i = value; } }", @"class Class { int P { get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task ExpressionBodiedGetterAndSetterWithInitializer() { await TestInRegularAndScript1Async( @"class Class { int [|i|] = 1; int P { get => i; set => i = value; } }", @"class Class { int P { get; set; } = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(25401, "https://github.com/dotnet/roslyn/issues/25401")] public async Task TestGetterAccessibilityDiffers() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; public int P { protected get { return i; } set { i = value; } } }", @"class Class { public int P { protected get; set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(25401, "https://github.com/dotnet/roslyn/issues/25401")] public async Task TestSetterAccessibilityDiffers() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; public int P { get { return i; } protected set { i = value; } } }", @"class Class { public int P { get; protected set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")] public async Task TestPreserveTrailingTrivia1() { await TestInRegularAndScript1Async( @"class Goo { private readonly object [|bar|] = new object(); public object Bar => bar; public int Baz => 0; }", @"class Goo { public object Bar { get; } = new object(); public int Baz => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")] public async Task TestPreserveTrailingTrivia2() { await TestInRegularAndScript1Async( @"class Goo { private readonly object [|bar|] = new object(); public object Bar => bar; // prop comment public int Baz => 0; }", @"class Goo { public object Bar { get; } = new object(); // prop comment public int Baz => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")] public async Task TestPreserveTrailingTrivia3() { await TestInRegularAndScript1Async( @"class Goo { private readonly object [|bar|] = new object(); // doc public object Bar => bar; // prop comment public int Baz => 0; }", @"class Goo { // doc public object Bar { get; } = new object(); // prop comment public int Baz => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] [WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")] public async Task TestKeepLeadingBlank() { await TestInRegularAndScript1Async( @"class Goo { private readonly object [|bar|] = new object(); // doc public object Bar => bar; // prop comment public int Baz => 0; }", @"class Goo { // doc public object Bar { get; } = new object(); // prop comment public int Baz => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsAbove1() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int j; int P { get { return i; } } }", @"class Class { int j; int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsAbove2() { await TestInRegularAndScript1Async( @"class Class { int j; [|int i|]; int P { get { return i; } } }", @"class Class { int j; int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsAbove3() { await TestInRegularAndScript1Async( @"class Class { [|int i|]; int j; int P { get { return i; } } }", @"class Class { int j; int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsAbove4() { await TestInRegularAndScript1Async( @"class Class { int j; [|int i|]; int P { get { return i; } } }", @"class Class { int j; int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsBelow1() { await TestInRegularAndScript1Async( @"class Class { int P { get { return i; } } [|int i|]; int j; }", @"class Class { int P { get; } int j; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsBelow2() { await TestInRegularAndScript1Async( @"class Class { int P { get { return i; } } int j; [|int i|]; }", @"class Class { int P { get; } int j; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsBelow3() { await TestInRegularAndScript1Async( @"class Class { int P { get { return i; } } [|int i|]; int j; }", @"class Class { int P { get; } int j; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsBelow4() { await TestInRegularAndScript1Async( @"class Class { int P { get { return i; } } int j; [|int i|]; }", @"class Class { int P { get; } int j; }"); } [WorkItem(27675, "https://github.com/dotnet/roslyn/issues/27675")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleLineWithDirective() { await TestInRegularAndScript1Async( @"class Class { #region Test [|int i|]; #endregion int P { get { return i; } } }", @"class Class { #region Test #endregion int P { get; } }"); } [WorkItem(27675, "https://github.com/dotnet/roslyn/issues/27675")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestMultipleFieldsWithDirective() { await TestInRegularAndScript1Async( @"class Class { #region Test [|int i|]; int j; #endregion int P { get { return i; } } }", @"class Class { #region Test int j; #endregion int P { get; } }"); } [WorkItem(27675, "https://github.com/dotnet/roslyn/issues/27675")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestSingleLineWithDoubleDirectives() { await TestInRegularAndScript1Async( @"class TestClass { #region Field [|int i|]; #endregion #region Property int P { get { return i; } } #endregion }", @"class TestClass { #region Field #endregion #region Property int P { get; } #endregion }"); } [WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestUseTabs() { await TestInRegularAndScript1Async( @"public class Foo { private readonly object o; [||]public object O => o; }", @"public class Foo { public object O { get; } }", new TestParameters(options: Option(FormattingOptions2.UseTabs, true))); } [WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestUseSpaces() { await TestInRegularAndScript1Async( @"public class Foo { private readonly object o; [||]public object O => o; }", @"public class Foo { public object O { get; } }", new TestParameters(options: Option(FormattingOptions2.UseTabs, false))); } [WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestUseTabs_Editorconfig() { await TestInRegularAndScript1Async( @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> public class Foo { private readonly object o; [||]public object O => o; } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig""> [*] indent_style = tab </AnalyzerConfigDocument> </Project> </Workspace>", @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> public class Foo { public object O { get; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig""> [*] indent_style = tab </AnalyzerConfigDocument> </Project> </Workspace>"); } [WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestUseSpaces_Editorconfig() { await TestInRegularAndScript1Async( @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> public class Foo { private readonly object o; [||]public object O => o; } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig""> [*] indent_style = space </AnalyzerConfigDocument> </Project> </Workspace>", @"<Workspace> <Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath = ""z:\\file.cs""> public class Foo { public object O { get; } } </Document> <AnalyzerConfigDocument FilePath = ""z:\\.editorconfig""> [*] indent_style = space </AnalyzerConfigDocument> </Project> </Workspace>"); } [WorkItem(34783, "https://github.com/dotnet/roslyn/issues/34783")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestNotOnSerializableType() { await TestMissingAsync( @" [System.Serializable] class Class { [|int i|]; int P { get { return i; } } }"); } [WorkItem(47999, "https://github.com/dotnet/roslyn/issues/47999")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestPropertyIsReadOnlyAndSetterNeeded() { await TestInRegularAndScript1Async( @"struct S { [|int i|]; public readonly int P => i; public void SetP(int value) => i = value; }", @"struct S { public int P { get; private set; } public void SetP(int value) => P = value; }"); } [WorkItem(47999, "https://github.com/dotnet/roslyn/issues/47999")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestPropertyIsReadOnlyWithNoAccessModifierAndSetterNeeded() { await TestInRegularAndScript1Async( @"struct S { [|int i|]; readonly int P => i; public void SetP(int value) => i = value; }", @"struct S { int P { get; set; } public void SetP(int value) => P = value; }"); } [WorkItem(47999, "https://github.com/dotnet/roslyn/issues/47999")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)] public async Task TestPropertyIsReadOnlyAndSetterUnneeded() { await TestInRegularAndScript1Async( @"struct S { [|int i|]; public readonly int P => i; }", @"struct S { public readonly int P { get; } }"); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharp/CommentSelection/CSharpToggleBlockCommentCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.CommentSelection { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.CSharpContentType)] [Name(PredefinedCommandHandlerNames.ToggleBlockComment)] internal class CSharpToggleBlockCommentCommandHandler : ToggleBlockCommentCommandHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpToggleBlockCommentCommandHandler( ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService, ITextStructureNavigatorSelectorService navigatorSelectorService) : base(undoHistoryRegistry, editorOperationsFactoryService, navigatorSelectorService) { } /// <summary> /// Retrieves block comments near the selection in the document. /// Uses the CSharp syntax tree to find the commented spans. /// </summary> protected override async Task<ImmutableArray<TextSpan>> GetBlockCommentsInDocumentAsync(Document document, ITextSnapshot snapshot, TextSpan linesContainingSelections, CommentSelectionInfo commentInfo, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // Only search for block comments intersecting the lines in the selections. return root.DescendantTrivia(linesContainingSelections) .Where(trivia => trivia.IsKind(SyntaxKind.MultiLineCommentTrivia) || trivia.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia)) .SelectAsArray(blockCommentTrivia => blockCommentTrivia.Span); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.CommentSelection { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.CSharpContentType)] [Name(PredefinedCommandHandlerNames.ToggleBlockComment)] internal class CSharpToggleBlockCommentCommandHandler : ToggleBlockCommentCommandHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpToggleBlockCommentCommandHandler( ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService, ITextStructureNavigatorSelectorService navigatorSelectorService) : base(undoHistoryRegistry, editorOperationsFactoryService, navigatorSelectorService) { } /// <summary> /// Retrieves block comments near the selection in the document. /// Uses the CSharp syntax tree to find the commented spans. /// </summary> protected override async Task<ImmutableArray<TextSpan>> GetBlockCommentsInDocumentAsync(Document document, ITextSnapshot snapshot, TextSpan linesContainingSelections, CommentSelectionInfo commentInfo, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // Only search for block comments intersecting the lines in the selections. return root.DescendantTrivia(linesContainingSelections) .Where(trivia => trivia.IsKind(SyntaxKind.MultiLineCommentTrivia) || trivia.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia)) .SelectAsArray(blockCommentTrivia => blockCommentTrivia.Span); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/TestUtilities/EditAndContinue/ActiveStatementTestHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal static class ActiveStatementTestHelpers { public static ImmutableArray<ManagedActiveStatementDebugInfo> GetActiveStatementDebugInfosCSharp( string[] markedSources, string[]? filePaths = null, int[]? methodRowIds = null, Guid[]? modules = null, int[]? methodVersions = null, int[]? ilOffsets = null, ActiveStatementFlags[]? flags = null) { return ActiveStatementsDescription.GetActiveStatementDebugInfos( (source, path) => SyntaxFactory.ParseSyntaxTree(source, path: path), markedSources, filePaths, extension: ".cs", methodRowIds, modules, methodVersions, ilOffsets, flags); } public static string Delete(string src, string marker) { while (true) { var startStr = "/*delete" + marker; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var end = src.IndexOf(endStr, start + startStr.Length) + endStr.Length; src = src.Substring(0, start) + src.Substring(end); } } /// <summary> /// Inserts new lines into the text at the position indicated by /*insert<paramref name="marker"/>[{number-of-lines-to-insert}]*/. /// </summary> public static string InsertNewLines(string src, string marker) { while (true) { var startStr = "/*insert" + marker + "["; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var startOfLineCount = start + startStr.Length; var endOfLineCount = src.IndexOf(']', startOfLineCount); var lineCount = int.Parse(src.Substring(startOfLineCount, endOfLineCount - startOfLineCount)); var end = src.IndexOf(endStr, endOfLineCount) + endStr.Length; src = src.Substring(0, start) + string.Join("", Enumerable.Repeat(Environment.NewLine, lineCount)) + src.Substring(end); } } public static string Update(string src, string marker) => InsertNewLines(Delete(src, marker), marker); public static string InspectActiveStatement(ActiveStatement statement) => $"{statement.Ordinal}: {statement.FileSpan} flags=[{statement.Flags}]"; public static string InspectActiveStatementAndInstruction(ActiveStatement statement) => InspectActiveStatement(statement) + " " + statement.InstructionId.GetDebuggerDisplay(); public static string InspectActiveStatementAndInstruction(ActiveStatement statement, SourceText text) => InspectActiveStatementAndInstruction(statement) + $" '{GetFirstLineText(statement.Span, text)}'"; public static string InspectActiveStatementUpdate(ManagedActiveStatementUpdate update) => $"{update.Method.GetDebuggerDisplay()} IL_{update.ILOffset:X4}: {update.NewSpan.GetDebuggerDisplay()}"; public static IEnumerable<string> InspectNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> regions) => regions.OrderBy(r => r.Key.Token).Select(r => $"{r.Key.Method.GetDebuggerDisplay()} | {string.Join(", ", r.Value.Select(r => r.GetDebuggerDisplay()))}"); public static string InspectExceptionRegionUpdate(ManagedExceptionRegionUpdate r) => $"{r.Method.GetDebuggerDisplay()} | {r.NewSpan.GetDebuggerDisplay()} Delta={r.Delta}"; public static string GetFirstLineText(LinePositionSpan span, SourceText text) => text.Lines[span.Start.Line].ToString().Trim(); public static string InspectSequencePointUpdates(SequencePointUpdates updates) => $"{updates.FileName}: [{string.Join(", ", updates.LineUpdates.Select(u => $"{u.OldLine} -> {u.NewLine}"))}]"; public static IEnumerable<string> Inspect(this IEnumerable<SequencePointUpdates> updates) => updates.Select(InspectSequencePointUpdates); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal static class ActiveStatementTestHelpers { public static ImmutableArray<ManagedActiveStatementDebugInfo> GetActiveStatementDebugInfosCSharp( string[] markedSources, string[]? filePaths = null, int[]? methodRowIds = null, Guid[]? modules = null, int[]? methodVersions = null, int[]? ilOffsets = null, ActiveStatementFlags[]? flags = null) { return ActiveStatementsDescription.GetActiveStatementDebugInfos( (source, path) => SyntaxFactory.ParseSyntaxTree(source, path: path), markedSources, filePaths, extension: ".cs", methodRowIds, modules, methodVersions, ilOffsets, flags); } public static string Delete(string src, string marker) { while (true) { var startStr = "/*delete" + marker; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var end = src.IndexOf(endStr, start + startStr.Length) + endStr.Length; src = src.Substring(0, start) + src.Substring(end); } } /// <summary> /// Inserts new lines into the text at the position indicated by /*insert<paramref name="marker"/>[{number-of-lines-to-insert}]*/. /// </summary> public static string InsertNewLines(string src, string marker) { while (true) { var startStr = "/*insert" + marker + "["; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var startOfLineCount = start + startStr.Length; var endOfLineCount = src.IndexOf(']', startOfLineCount); var lineCount = int.Parse(src.Substring(startOfLineCount, endOfLineCount - startOfLineCount)); var end = src.IndexOf(endStr, endOfLineCount) + endStr.Length; src = src.Substring(0, start) + string.Join("", Enumerable.Repeat(Environment.NewLine, lineCount)) + src.Substring(end); } } public static string Update(string src, string marker) => InsertNewLines(Delete(src, marker), marker); public static string InspectActiveStatement(ActiveStatement statement) => $"{statement.Ordinal}: {statement.FileSpan} flags=[{statement.Flags}]"; public static string InspectActiveStatementAndInstruction(ActiveStatement statement) => InspectActiveStatement(statement) + " " + statement.InstructionId.GetDebuggerDisplay(); public static string InspectActiveStatementAndInstruction(ActiveStatement statement, SourceText text) => InspectActiveStatementAndInstruction(statement) + $" '{GetFirstLineText(statement.Span, text)}'"; public static string InspectActiveStatementUpdate(ManagedActiveStatementUpdate update) => $"{update.Method.GetDebuggerDisplay()} IL_{update.ILOffset:X4}: {update.NewSpan.GetDebuggerDisplay()}"; public static IEnumerable<string> InspectNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> regions) => regions.OrderBy(r => r.Key.Token).Select(r => $"{r.Key.Method.GetDebuggerDisplay()} | {string.Join(", ", r.Value.Select(r => r.GetDebuggerDisplay()))}"); public static string InspectExceptionRegionUpdate(ManagedExceptionRegionUpdate r) => $"{r.Method.GetDebuggerDisplay()} | {r.NewSpan.GetDebuggerDisplay()} Delta={r.Delta}"; public static string GetFirstLineText(LinePositionSpan span, SourceText text) => text.Lines[span.Start.Line].ToString().Trim(); public static string InspectSequencePointUpdates(SequencePointUpdates updates) => $"{updates.FileName}: [{string.Join(", ", updates.LineUpdates.Select(u => $"{u.OldLine} -> {u.NewLine}"))}]"; public static IEnumerable<string> Inspect(this IEnumerable<SequencePointUpdates> updates) => updates.Select(InspectSequencePointUpdates); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo.Node.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class SymbolTreeInfo { private const int RootNodeParentIndex = -1; /// <summary> /// <see cref="BuilderNode"/>s are produced when initially creating our indices. /// They store Names of symbols and the index of their parent symbol. When we /// produce the final <see cref="SymbolTreeInfo"/> though we will then convert /// these to <see cref="Node"/>s. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] private struct BuilderNode { public static readonly BuilderNode RootNode = new("", RootNodeParentIndex, default); public readonly string Name; public readonly int ParentIndex; public readonly MultiDictionary<MetadataNode, ParameterTypeInfo>.ValueSet ParameterTypeInfos; public BuilderNode(string name, int parentIndex, MultiDictionary<MetadataNode, ParameterTypeInfo>.ValueSet parameterTypeInfos = default) { Name = name; ParentIndex = parentIndex; ParameterTypeInfos = parameterTypeInfos; } public bool IsRoot => ParentIndex == RootNodeParentIndex; private string GetDebuggerDisplay() => Name + ", " + ParentIndex; } [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] private struct Node { /// <summary> /// The Name of this Node. /// </summary> public readonly string Name; /// <summary> /// Index in <see cref="_nodes"/> of the parent Node of this Node. /// Value will be <see cref="RootNodeParentIndex"/> if this is the /// Node corresponding to the root symbol. /// </summary> public readonly int ParentIndex; public Node(string name, int parentIndex) { Name = name; ParentIndex = parentIndex; } public bool IsRoot => ParentIndex == RootNodeParentIndex; public void AssertEquivalentTo(Node node) { Debug.Assert(node.Name == this.Name); Debug.Assert(node.ParentIndex == this.ParentIndex); } private string GetDebuggerDisplay() => Name + ", " + ParentIndex; } private readonly struct ParameterTypeInfo { /// <summary> /// This is the type name of the parameter when <see cref="IsComplexType"/> is false. /// For array types, this is just the elemtent type name. /// e.g. `int` for `int[][,]` /// </summary> public readonly string Name; /// <summary> /// Indicate if the type of parameter is any kind of array. /// This is relevant for both simple and complex types. For example: /// - array of simple type like int[], int[][], int[][,], etc. are all ultimately represented as "int[]" in index. /// - array of complex type like T[], T[][], etc are all represented as "[]" in index, /// in contrast to just "" for non-array types. /// </summary> public readonly bool IsArray; /// <summary> /// Similar to <see cref="SyntaxTreeIndex.ExtensionMethodInfo"/>, we divide extension methods into simple /// and complex categories for filtering purpose. Whether a method is simple is determined based on if we /// can determine it's receiver type easily with a pure text matching. For complex methods, we will need to /// rely on symbol to decide if it's feasible. /// /// Simple types include: /// - Primitive types /// - Types which is not a generic method parameter /// - By reference type of any types above /// - Array types with element of any types above /// </summary> public readonly bool IsComplexType; public ParameterTypeInfo(string name, bool isComplex, bool isArray) { Name = name; IsComplexType = isComplex; IsArray = isArray; } } public readonly struct ExtensionMethodInfo { /// <summary> /// Name of the extension method. /// This can be used to retrive corresponding symbols via <see cref="INamespaceOrTypeSymbol.GetMembers(string)"/> /// </summary> public readonly string Name; /// <summary> /// Fully qualified name for the type that contains this extension method. /// </summary> public readonly string FullyQualifiedContainerName; public ExtensionMethodInfo(string fullyQualifiedContainerName, string name) { FullyQualifiedContainerName = fullyQualifiedContainerName; Name = name; } } private sealed class ParameterTypeInfoProvider : ISignatureTypeProvider<ParameterTypeInfo, object> { public static readonly ParameterTypeInfoProvider Instance = new(); private static ParameterTypeInfo ComplexInfo => new(string.Empty, isComplex: true, isArray: false); public ParameterTypeInfo GetPrimitiveType(PrimitiveTypeCode typeCode) => new(typeCode.ToString(), isComplex: false, isArray: false); public ParameterTypeInfo GetGenericInstantiation(ParameterTypeInfo genericType, ImmutableArray<ParameterTypeInfo> typeArguments) => genericType.IsComplexType ? ComplexInfo : new ParameterTypeInfo(genericType.Name, isComplex: false, isArray: false); public ParameterTypeInfo GetByReferenceType(ParameterTypeInfo elementType) => elementType; public ParameterTypeInfo GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) { var type = reader.GetTypeDefinition(handle); var name = reader.GetString(type.Name); return new ParameterTypeInfo(name, isComplex: false, isArray: false); } public ParameterTypeInfo GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) { var type = reader.GetTypeReference(handle); var name = reader.GetString(type.Name); return new ParameterTypeInfo(name, isComplex: false, isArray: false); } public ParameterTypeInfo GetTypeFromSpecification(MetadataReader reader, object genericContext, TypeSpecificationHandle handle, byte rawTypeKind) { var sigReader = reader.GetBlobReader(reader.GetTypeSpecification(handle).Signature); return new SignatureDecoder<ParameterTypeInfo, object>(Instance, reader, genericContext).DecodeType(ref sigReader); } public ParameterTypeInfo GetArrayType(ParameterTypeInfo elementType, ArrayShape shape) => GetArrayTypeInfo(elementType); public ParameterTypeInfo GetSZArrayType(ParameterTypeInfo elementType) => GetArrayTypeInfo(elementType); private static ParameterTypeInfo GetArrayTypeInfo(ParameterTypeInfo elementType) => elementType.IsComplexType ? new ParameterTypeInfo(string.Empty, isComplex: true, isArray: true) : new ParameterTypeInfo(elementType.Name, isComplex: false, isArray: true); public ParameterTypeInfo GetFunctionPointerType(MethodSignature<ParameterTypeInfo> signature) => ComplexInfo; public ParameterTypeInfo GetGenericMethodParameter(object genericContext, int index) => ComplexInfo; public ParameterTypeInfo GetGenericTypeParameter(object genericContext, int index) => ComplexInfo; public ParameterTypeInfo GetModifiedType(ParameterTypeInfo modifier, ParameterTypeInfo unmodifiedType, bool isRequired) => ComplexInfo; public ParameterTypeInfo GetPinnedType(ParameterTypeInfo elementType) => ComplexInfo; public ParameterTypeInfo GetPointerType(ParameterTypeInfo elementType) => ComplexInfo; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class SymbolTreeInfo { private const int RootNodeParentIndex = -1; /// <summary> /// <see cref="BuilderNode"/>s are produced when initially creating our indices. /// They store Names of symbols and the index of their parent symbol. When we /// produce the final <see cref="SymbolTreeInfo"/> though we will then convert /// these to <see cref="Node"/>s. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] private struct BuilderNode { public static readonly BuilderNode RootNode = new("", RootNodeParentIndex, default); public readonly string Name; public readonly int ParentIndex; public readonly MultiDictionary<MetadataNode, ParameterTypeInfo>.ValueSet ParameterTypeInfos; public BuilderNode(string name, int parentIndex, MultiDictionary<MetadataNode, ParameterTypeInfo>.ValueSet parameterTypeInfos = default) { Name = name; ParentIndex = parentIndex; ParameterTypeInfos = parameterTypeInfos; } public bool IsRoot => ParentIndex == RootNodeParentIndex; private string GetDebuggerDisplay() => Name + ", " + ParentIndex; } [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] private struct Node { /// <summary> /// The Name of this Node. /// </summary> public readonly string Name; /// <summary> /// Index in <see cref="_nodes"/> of the parent Node of this Node. /// Value will be <see cref="RootNodeParentIndex"/> if this is the /// Node corresponding to the root symbol. /// </summary> public readonly int ParentIndex; public Node(string name, int parentIndex) { Name = name; ParentIndex = parentIndex; } public bool IsRoot => ParentIndex == RootNodeParentIndex; public void AssertEquivalentTo(Node node) { Debug.Assert(node.Name == this.Name); Debug.Assert(node.ParentIndex == this.ParentIndex); } private string GetDebuggerDisplay() => Name + ", " + ParentIndex; } private readonly struct ParameterTypeInfo { /// <summary> /// This is the type name of the parameter when <see cref="IsComplexType"/> is false. /// For array types, this is just the elemtent type name. /// e.g. `int` for `int[][,]` /// </summary> public readonly string Name; /// <summary> /// Indicate if the type of parameter is any kind of array. /// This is relevant for both simple and complex types. For example: /// - array of simple type like int[], int[][], int[][,], etc. are all ultimately represented as "int[]" in index. /// - array of complex type like T[], T[][], etc are all represented as "[]" in index, /// in contrast to just "" for non-array types. /// </summary> public readonly bool IsArray; /// <summary> /// Similar to <see cref="SyntaxTreeIndex.ExtensionMethodInfo"/>, we divide extension methods into simple /// and complex categories for filtering purpose. Whether a method is simple is determined based on if we /// can determine it's receiver type easily with a pure text matching. For complex methods, we will need to /// rely on symbol to decide if it's feasible. /// /// Simple types include: /// - Primitive types /// - Types which is not a generic method parameter /// - By reference type of any types above /// - Array types with element of any types above /// </summary> public readonly bool IsComplexType; public ParameterTypeInfo(string name, bool isComplex, bool isArray) { Name = name; IsComplexType = isComplex; IsArray = isArray; } } public readonly struct ExtensionMethodInfo { /// <summary> /// Name of the extension method. /// This can be used to retrive corresponding symbols via <see cref="INamespaceOrTypeSymbol.GetMembers(string)"/> /// </summary> public readonly string Name; /// <summary> /// Fully qualified name for the type that contains this extension method. /// </summary> public readonly string FullyQualifiedContainerName; public ExtensionMethodInfo(string fullyQualifiedContainerName, string name) { FullyQualifiedContainerName = fullyQualifiedContainerName; Name = name; } } private sealed class ParameterTypeInfoProvider : ISignatureTypeProvider<ParameterTypeInfo, object> { public static readonly ParameterTypeInfoProvider Instance = new(); private static ParameterTypeInfo ComplexInfo => new(string.Empty, isComplex: true, isArray: false); public ParameterTypeInfo GetPrimitiveType(PrimitiveTypeCode typeCode) => new(typeCode.ToString(), isComplex: false, isArray: false); public ParameterTypeInfo GetGenericInstantiation(ParameterTypeInfo genericType, ImmutableArray<ParameterTypeInfo> typeArguments) => genericType.IsComplexType ? ComplexInfo : new ParameterTypeInfo(genericType.Name, isComplex: false, isArray: false); public ParameterTypeInfo GetByReferenceType(ParameterTypeInfo elementType) => elementType; public ParameterTypeInfo GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) { var type = reader.GetTypeDefinition(handle); var name = reader.GetString(type.Name); return new ParameterTypeInfo(name, isComplex: false, isArray: false); } public ParameterTypeInfo GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) { var type = reader.GetTypeReference(handle); var name = reader.GetString(type.Name); return new ParameterTypeInfo(name, isComplex: false, isArray: false); } public ParameterTypeInfo GetTypeFromSpecification(MetadataReader reader, object genericContext, TypeSpecificationHandle handle, byte rawTypeKind) { var sigReader = reader.GetBlobReader(reader.GetTypeSpecification(handle).Signature); return new SignatureDecoder<ParameterTypeInfo, object>(Instance, reader, genericContext).DecodeType(ref sigReader); } public ParameterTypeInfo GetArrayType(ParameterTypeInfo elementType, ArrayShape shape) => GetArrayTypeInfo(elementType); public ParameterTypeInfo GetSZArrayType(ParameterTypeInfo elementType) => GetArrayTypeInfo(elementType); private static ParameterTypeInfo GetArrayTypeInfo(ParameterTypeInfo elementType) => elementType.IsComplexType ? new ParameterTypeInfo(string.Empty, isComplex: true, isArray: true) : new ParameterTypeInfo(elementType.Name, isComplex: false, isArray: true); public ParameterTypeInfo GetFunctionPointerType(MethodSignature<ParameterTypeInfo> signature) => ComplexInfo; public ParameterTypeInfo GetGenericMethodParameter(object genericContext, int index) => ComplexInfo; public ParameterTypeInfo GetGenericTypeParameter(object genericContext, int index) => ComplexInfo; public ParameterTypeInfo GetModifiedType(ParameterTypeInfo modifier, ParameterTypeInfo unmodifiedType, bool isRequired) => ComplexInfo; public ParameterTypeInfo GetPinnedType(ParameterTypeInfo elementType) => ComplexInfo; public ParameterTypeInfo GetPointerType(ParameterTypeInfo elementType) => ComplexInfo; } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Lsif/Generator/Writing/LsifConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; using Newtonsoft.Json; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing { internal sealed class LsifConverter : JsonConverter { public override bool CanConvert(Type objectType) { return typeof(ISerializableId).IsAssignableFrom(objectType) || objectType == typeof(Uri); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { switch (value) { case ISerializableId id: writer.WriteValue(id.NumericId); break; case Uri uri: writer.WriteValue(uri.AbsoluteUri); break; default: throw new NotSupportedException(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; using Newtonsoft.Json; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing { internal sealed class LsifConverter : JsonConverter { public override bool CanConvert(Type objectType) { return typeof(ISerializableId).IsAssignableFrom(objectType) || objectType == typeof(Uri); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { switch (value) { case ISerializableId id: writer.WriteValue(id.NumericId); break; case Uri uri: writer.WriteValue(uri.AbsoluteUri); break; default: throw new NotSupportedException(); } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/ArgumentGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class ArgumentGenerator { public static ArgumentSyntax GenerateArgument(SyntaxNode argument) { if (argument is ExpressionSyntax expression) { return SyntaxFactory.Argument(expression); } return (ArgumentSyntax)argument; } public static ArgumentListSyntax GenerateArgumentList(IList<SyntaxNode> arguments) => SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments.Select(GenerateArgument))); public static BracketedArgumentListSyntax GenerateBracketedArgumentList(IList<SyntaxNode> arguments) => SyntaxFactory.BracketedArgumentList(SyntaxFactory.SeparatedList(arguments.Select(GenerateArgument))); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class ArgumentGenerator { public static ArgumentSyntax GenerateArgument(SyntaxNode argument) { if (argument is ExpressionSyntax expression) { return SyntaxFactory.Argument(expression); } return (ArgumentSyntax)argument; } public static ArgumentListSyntax GenerateArgumentList(IList<SyntaxNode> arguments) => SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments.Select(GenerateArgument))); public static BracketedArgumentListSyntax GenerateBracketedArgumentList(IList<SyntaxNode> arguments) => SyntaxFactory.BracketedArgumentList(SyntaxFactory.SeparatedList(arguments.Select(GenerateArgument))); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractFormatEngine.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { // TODO : two alternative design possible for formatting engine // // 1. use AAL (TPL Dataflow) in .NET 4.5 to run things concurrently in sequential order // * this has a problem of the new TPL lib being not released yet and possibility of not using all cores. // // 2. create dependency graph between operations, and format them in topological order and // run chunks that don't have dependency in parallel (kirill's idea) // * this requires defining dependencies on each operations. can't use dependency between tokens since // that would create too big graph. key for this approach is how to reduce size of graph. internal abstract partial class AbstractFormatEngine { private readonly ChainedFormattingRules _formattingRules; private readonly SyntaxNode _commonRoot; private readonly SyntaxToken _token1; private readonly SyntaxToken _token2; protected readonly TextSpan SpanToFormat; internal readonly AnalyzerConfigOptions Options; internal readonly TreeData TreeData; public AbstractFormatEngine( TreeData treeData, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> formattingRules, SyntaxToken token1, SyntaxToken token2) : this( treeData, options, new ChainedFormattingRules(formattingRules, options), token1, token2) { } internal AbstractFormatEngine( TreeData treeData, AnalyzerConfigOptions options, ChainedFormattingRules formattingRules, SyntaxToken token1, SyntaxToken token2) { Contract.ThrowIfNull(options); Contract.ThrowIfNull(treeData); Contract.ThrowIfNull(formattingRules); Contract.ThrowIfTrue(treeData.Root.IsInvalidTokenRange(token1, token2)); this.Options = options; this.TreeData = treeData; _formattingRules = formattingRules; _token1 = token1; _token2 = token2; // get span and common root this.SpanToFormat = GetSpanToFormat(); _commonRoot = token1.GetCommonRoot(token2) ?? throw ExceptionUtilities.Unreachable; } internal abstract ISyntaxFacts SyntaxFacts { get; } protected abstract AbstractTriviaDataFactory CreateTriviaFactory(); protected abstract AbstractFormattingResult CreateFormattingResult(TokenStream tokenStream); public AbstractFormattingResult Format(CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Formatting_Format, FormatSummary, cancellationToken)) { // setup environment var nodeOperations = CreateNodeOperations(cancellationToken); var tokenStream = new TokenStream(this.TreeData, this.Options, this.SpanToFormat, CreateTriviaFactory()); var tokenOperation = CreateTokenOperation(tokenStream, cancellationToken); // initialize context var context = CreateFormattingContext(tokenStream, cancellationToken); // start anchor task that will be used later cancellationToken.ThrowIfCancellationRequested(); var anchorContext = nodeOperations.AnchorIndentationOperations.Do(context.AddAnchorIndentationOperation); BuildContext(context, nodeOperations, cancellationToken); ApplyBeginningOfTreeTriviaOperation(context, cancellationToken); ApplyTokenOperations(context, nodeOperations, tokenOperation, cancellationToken); ApplyTriviaOperations(context, cancellationToken); ApplyEndOfTreeTriviaOperation(context, cancellationToken); return CreateFormattingResult(tokenStream); } } protected virtual FormattingContext CreateFormattingContext(TokenStream tokenStream, CancellationToken cancellationToken) { // initialize context var context = new FormattingContext(this, tokenStream); context.Initialize(_formattingRules, _token1, _token2, cancellationToken); return context; } protected virtual NodeOperations CreateNodeOperations(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // iterating tree is very expensive. do it once and cache it to list SegmentedList<SyntaxNode> nodeIterator; using (Logger.LogBlock(FunctionId.Formatting_IterateNodes, cancellationToken)) { const int magicLengthToNodesRatio = 5; var result = new SegmentedList<SyntaxNode>(Math.Max(this.SpanToFormat.Length / magicLengthToNodesRatio, 4)); foreach (var node in _commonRoot.DescendantNodesAndSelf(this.SpanToFormat)) { cancellationToken.ThrowIfCancellationRequested(); result.Add(node); } nodeIterator = result; } // iterate through each operation using index to not create any unnecessary object cancellationToken.ThrowIfCancellationRequested(); List<IndentBlockOperation> indentBlockOperation; using (Logger.LogBlock(FunctionId.Formatting_CollectIndentBlock, cancellationToken)) { indentBlockOperation = AddOperations<IndentBlockOperation>(nodeIterator, (l, n) => _formattingRules.AddIndentBlockOperations(l, n), cancellationToken); } cancellationToken.ThrowIfCancellationRequested(); List<SuppressOperation> suppressOperation; using (Logger.LogBlock(FunctionId.Formatting_CollectSuppressOperation, cancellationToken)) { suppressOperation = AddOperations<SuppressOperation>(nodeIterator, (l, n) => _formattingRules.AddSuppressOperations(l, n), cancellationToken); } cancellationToken.ThrowIfCancellationRequested(); List<AlignTokensOperation> alignmentOperation; using (Logger.LogBlock(FunctionId.Formatting_CollectAlignOperation, cancellationToken)) { var operations = AddOperations<AlignTokensOperation>(nodeIterator, (l, n) => _formattingRules.AddAlignTokensOperations(l, n), cancellationToken); // make sure we order align operation from left to right operations.Sort((o1, o2) => o1.BaseToken.Span.CompareTo(o2.BaseToken.Span)); alignmentOperation = operations; } cancellationToken.ThrowIfCancellationRequested(); List<AnchorIndentationOperation> anchorIndentationOperations; using (Logger.LogBlock(FunctionId.Formatting_CollectAnchorOperation, cancellationToken)) { anchorIndentationOperations = AddOperations<AnchorIndentationOperation>(nodeIterator, (l, n) => _formattingRules.AddAnchorIndentationOperations(l, n), cancellationToken); } return new NodeOperations(indentBlockOperation, suppressOperation, anchorIndentationOperations, alignmentOperation); } private static List<T> AddOperations<T>(SegmentedList<SyntaxNode> nodes, Action<List<T>, SyntaxNode> addOperations, CancellationToken cancellationToken) { var operations = new List<T>(); var list = new List<T>(); foreach (var n in nodes) { cancellationToken.ThrowIfCancellationRequested(); addOperations(list, n); list.RemoveAll(item => item == null); operations.AddRange(list); list.Clear(); } return operations; } private SegmentedArray<TokenPairWithOperations> CreateTokenOperation( TokenStream tokenStream, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using (Logger.LogBlock(FunctionId.Formatting_CollectTokenOperation, cancellationToken)) { // pre-allocate list once. this is cheaper than re-adjusting list as items are added. var list = new SegmentedArray<TokenPairWithOperations>(tokenStream.TokenCount - 1); foreach (var (index, currentToken, nextToken) in tokenStream.TokenIterator) { cancellationToken.ThrowIfCancellationRequested(); var spaceOperation = _formattingRules.GetAdjustSpacesOperation(currentToken, nextToken); var lineOperation = _formattingRules.GetAdjustNewLinesOperation(currentToken, nextToken); list[index] = new TokenPairWithOperations(tokenStream, index, spaceOperation, lineOperation); } return list; } } private void ApplyTokenOperations( FormattingContext context, NodeOperations nodeOperations, SegmentedArray<TokenPairWithOperations> tokenOperations, CancellationToken cancellationToken) { var applier = new OperationApplier(context, _formattingRules); ApplySpaceAndWrappingOperations(context, tokenOperations, applier, cancellationToken); ApplyAnchorOperations(context, tokenOperations, applier, cancellationToken); ApplySpecialOperations(context, nodeOperations, applier, cancellationToken); } private void ApplyBeginningOfTreeTriviaOperation( FormattingContext context, CancellationToken cancellationToken) { if (!context.TokenStream.FormatBeginningOfTree) { return; } // remove all leading indentation var triviaInfo = context.TokenStream.GetTriviaDataAtBeginningOfTree().WithIndentation(0, context, _formattingRules, cancellationToken); triviaInfo.Format(context, _formattingRules, BeginningOfTreeTriviaInfoApplier, cancellationToken); return; // local functions static void BeginningOfTreeTriviaInfoApplier(int i, TokenStream ts, TriviaData info) => ts.ApplyBeginningOfTreeChange(info); } private void ApplyEndOfTreeTriviaOperation( FormattingContext context, CancellationToken cancellationToken) { if (!context.TokenStream.FormatEndOfTree) { return; } if (context.IsFormattingDisabled(new TextSpan(context.TokenStream.LastTokenInStream.Token.SpanStart, 0))) { // Formatting is suppressed in the document, and not restored before the end return; } // remove all trailing indentation var triviaInfo = context.TokenStream.GetTriviaDataAtEndOfTree().WithIndentation(0, context, _formattingRules, cancellationToken); triviaInfo.Format(context, _formattingRules, EndOfTreeTriviaInfoApplier, cancellationToken); return; // local functions static void EndOfTreeTriviaInfoApplier(int i, TokenStream ts, TriviaData info) => ts.ApplyEndOfTreeChange(info); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowCaptures = false)] private void ApplyTriviaOperations(FormattingContext context, CancellationToken cancellationToken) { for (var i = 0; i < context.TokenStream.TokenCount - 1; i++) { cancellationToken.ThrowIfCancellationRequested(); TriviaFormatter(i, context, _formattingRules, cancellationToken); } return; // local functions static void RegularApplier(int tokenPairIndex, TokenStream ts, TriviaData info) => ts.ApplyChange(tokenPairIndex, info); static void TriviaFormatter(int tokenPairIndex, FormattingContext ctx, ChainedFormattingRules formattingRules, CancellationToken ct) { if (ctx.IsFormattingDisabled(tokenPairIndex)) { return; } var triviaInfo = ctx.TokenStream.GetTriviaData(tokenPairIndex); triviaInfo.Format( ctx, formattingRules, (tokenPairIndex1, ts, info) => RegularApplier(tokenPairIndex1, ts, info), ct, tokenPairIndex); } } private TextSpan GetSpanToFormat() { var startPosition = this.TreeData.IsFirstToken(_token1) ? this.TreeData.StartPosition : _token1.SpanStart; var endPosition = this.TreeData.IsLastToken(_token2) ? this.TreeData.EndPosition : _token2.Span.End; return TextSpan.FromBounds(startPosition, endPosition); } private static void ApplySpecialOperations( FormattingContext context, NodeOperations nodeOperationsCollector, OperationApplier applier, CancellationToken cancellationToken) { // apply alignment operation using (Logger.LogBlock(FunctionId.Formatting_CollectAlignOperation, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); // TODO : figure out a way to run alignment operations in parallel. probably find // unions and run each chunk in separate tasks var previousChangesMap = new Dictionary<SyntaxToken, int>(); var alignmentOperations = nodeOperationsCollector.AlignmentOperation; alignmentOperations.Do(operation => { cancellationToken.ThrowIfCancellationRequested(); applier.ApplyAlignment(operation, previousChangesMap, cancellationToken); }); // go through all relative indent block operation, and see whether it is affected by previous operations context.GetAllRelativeIndentBlockOperations().Do(o => { cancellationToken.ThrowIfCancellationRequested(); applier.ApplyBaseTokenIndentationChangesFromTo(FindCorrectBaseTokenOfRelativeIndentBlockOperation(o, context.TokenStream), o.StartToken, o.EndToken, previousChangesMap, cancellationToken); }); } } private static void ApplyAnchorOperations( FormattingContext context, SegmentedArray<TokenPairWithOperations> tokenOperations, OperationApplier applier, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Formatting_ApplyAnchorOperation, cancellationToken)) { // TODO: find out a way to apply anchor operation concurrently if possible var previousChangesMap = new Dictionary<SyntaxToken, int>(); foreach (var p in tokenOperations) { cancellationToken.ThrowIfCancellationRequested(); if (!AnchorOperationCandidate(p)) { continue; } var pairIndex = p.PairIndex; applier.ApplyAnchorIndentation(pairIndex, previousChangesMap, cancellationToken); } // go through all relative indent block operation, and see whether it is affected by the anchor operation context.GetAllRelativeIndentBlockOperations().Do(o => { cancellationToken.ThrowIfCancellationRequested(); applier.ApplyBaseTokenIndentationChangesFromTo(FindCorrectBaseTokenOfRelativeIndentBlockOperation(o, context.TokenStream), o.StartToken, o.EndToken, previousChangesMap, cancellationToken); }); } } private static bool AnchorOperationCandidate(TokenPairWithOperations pair) { if (pair.LineOperation == null) { return pair.TokenStream.GetTriviaData(pair.PairIndex).SecondTokenIsFirstTokenOnLine; } if (pair.LineOperation.Option == AdjustNewLinesOption.ForceLinesIfOnSingleLine) { return !pair.TokenStream.TwoTokensOriginallyOnSameLine(pair.Token1, pair.Token2) && pair.TokenStream.GetTriviaData(pair.PairIndex).SecondTokenIsFirstTokenOnLine; } return false; } private static SyntaxToken FindCorrectBaseTokenOfRelativeIndentBlockOperation(IndentBlockOperation operation, TokenStream tokenStream) { if (operation.Option.IsOn(IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine)) { return tokenStream.FirstTokenOfBaseTokenLine(operation.BaseToken); } return operation.BaseToken; } private static void ApplySpaceAndWrappingOperations( FormattingContext context, SegmentedArray<TokenPairWithOperations> tokenOperations, OperationApplier applier, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Formatting_ApplySpaceAndLine, cancellationToken)) { // go through each token pairs and apply operations foreach (var operationPair in tokenOperations) { ApplySpaceAndWrappingOperationsBody(context, operationPair, applier, cancellationToken); } } } private static void ApplySpaceAndWrappingOperationsBody( FormattingContext context, TokenPairWithOperations operation, OperationApplier applier, CancellationToken cancellationToken) { var token1 = operation.Token1; var token2 = operation.Token2; // check whether one of tokens is missing (which means syntax error exist around two tokens) // in error case, we leave code as user wrote if (token1.IsMissing || token2.IsMissing) { return; } var triviaInfo = context.TokenStream.GetTriviaData(operation.PairIndex); var spanBetweenTokens = TextSpan.FromBounds(token1.Span.End, token2.SpanStart); if (operation.LineOperation != null) { if (!context.IsWrappingSuppressed(spanBetweenTokens, triviaInfo.TreatAsElastic)) { // TODO : need to revisit later for the case where line and space operations // are conflicting each other by forcing new lines and removing new lines. // // if wrapping operation applied, no need to run any other operation if (applier.Apply(operation.LineOperation, operation.PairIndex, cancellationToken)) { return; } } } if (operation.SpaceOperation != null) { if (!context.IsSpacingSuppressed(spanBetweenTokens, triviaInfo.TreatAsElastic)) { applier.Apply(operation.SpaceOperation, operation.PairIndex); } } } private static void BuildContext( FormattingContext context, NodeOperations nodeOperations, CancellationToken cancellationToken) { // add scope operation (run each kind sequentially) using (Logger.LogBlock(FunctionId.Formatting_BuildContext, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); context.AddIndentBlockOperations(nodeOperations.IndentBlockOperation, cancellationToken); context.AddSuppressOperations(nodeOperations.SuppressOperation, cancellationToken); } } /// <summary> /// return summary for current formatting work /// </summary> private string FormatSummary() { return string.Format("({0}) ({1} - {2})", this.SpanToFormat, _token1.ToString().Replace("\r\n", "\\r\\n"), _token2.ToString().Replace("\r\n", "\\r\\n")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { // TODO : two alternative design possible for formatting engine // // 1. use AAL (TPL Dataflow) in .NET 4.5 to run things concurrently in sequential order // * this has a problem of the new TPL lib being not released yet and possibility of not using all cores. // // 2. create dependency graph between operations, and format them in topological order and // run chunks that don't have dependency in parallel (kirill's idea) // * this requires defining dependencies on each operations. can't use dependency between tokens since // that would create too big graph. key for this approach is how to reduce size of graph. internal abstract partial class AbstractFormatEngine { private readonly ChainedFormattingRules _formattingRules; private readonly SyntaxNode _commonRoot; private readonly SyntaxToken _token1; private readonly SyntaxToken _token2; protected readonly TextSpan SpanToFormat; internal readonly AnalyzerConfigOptions Options; internal readonly TreeData TreeData; public AbstractFormatEngine( TreeData treeData, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> formattingRules, SyntaxToken token1, SyntaxToken token2) : this( treeData, options, new ChainedFormattingRules(formattingRules, options), token1, token2) { } internal AbstractFormatEngine( TreeData treeData, AnalyzerConfigOptions options, ChainedFormattingRules formattingRules, SyntaxToken token1, SyntaxToken token2) { Contract.ThrowIfNull(options); Contract.ThrowIfNull(treeData); Contract.ThrowIfNull(formattingRules); Contract.ThrowIfTrue(treeData.Root.IsInvalidTokenRange(token1, token2)); this.Options = options; this.TreeData = treeData; _formattingRules = formattingRules; _token1 = token1; _token2 = token2; // get span and common root this.SpanToFormat = GetSpanToFormat(); _commonRoot = token1.GetCommonRoot(token2) ?? throw ExceptionUtilities.Unreachable; } internal abstract ISyntaxFacts SyntaxFacts { get; } protected abstract AbstractTriviaDataFactory CreateTriviaFactory(); protected abstract AbstractFormattingResult CreateFormattingResult(TokenStream tokenStream); public AbstractFormattingResult Format(CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Formatting_Format, FormatSummary, cancellationToken)) { // setup environment var nodeOperations = CreateNodeOperations(cancellationToken); var tokenStream = new TokenStream(this.TreeData, this.Options, this.SpanToFormat, CreateTriviaFactory()); var tokenOperation = CreateTokenOperation(tokenStream, cancellationToken); // initialize context var context = CreateFormattingContext(tokenStream, cancellationToken); // start anchor task that will be used later cancellationToken.ThrowIfCancellationRequested(); var anchorContext = nodeOperations.AnchorIndentationOperations.Do(context.AddAnchorIndentationOperation); BuildContext(context, nodeOperations, cancellationToken); ApplyBeginningOfTreeTriviaOperation(context, cancellationToken); ApplyTokenOperations(context, nodeOperations, tokenOperation, cancellationToken); ApplyTriviaOperations(context, cancellationToken); ApplyEndOfTreeTriviaOperation(context, cancellationToken); return CreateFormattingResult(tokenStream); } } protected virtual FormattingContext CreateFormattingContext(TokenStream tokenStream, CancellationToken cancellationToken) { // initialize context var context = new FormattingContext(this, tokenStream); context.Initialize(_formattingRules, _token1, _token2, cancellationToken); return context; } protected virtual NodeOperations CreateNodeOperations(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // iterating tree is very expensive. do it once and cache it to list SegmentedList<SyntaxNode> nodeIterator; using (Logger.LogBlock(FunctionId.Formatting_IterateNodes, cancellationToken)) { const int magicLengthToNodesRatio = 5; var result = new SegmentedList<SyntaxNode>(Math.Max(this.SpanToFormat.Length / magicLengthToNodesRatio, 4)); foreach (var node in _commonRoot.DescendantNodesAndSelf(this.SpanToFormat)) { cancellationToken.ThrowIfCancellationRequested(); result.Add(node); } nodeIterator = result; } // iterate through each operation using index to not create any unnecessary object cancellationToken.ThrowIfCancellationRequested(); List<IndentBlockOperation> indentBlockOperation; using (Logger.LogBlock(FunctionId.Formatting_CollectIndentBlock, cancellationToken)) { indentBlockOperation = AddOperations<IndentBlockOperation>(nodeIterator, (l, n) => _formattingRules.AddIndentBlockOperations(l, n), cancellationToken); } cancellationToken.ThrowIfCancellationRequested(); List<SuppressOperation> suppressOperation; using (Logger.LogBlock(FunctionId.Formatting_CollectSuppressOperation, cancellationToken)) { suppressOperation = AddOperations<SuppressOperation>(nodeIterator, (l, n) => _formattingRules.AddSuppressOperations(l, n), cancellationToken); } cancellationToken.ThrowIfCancellationRequested(); List<AlignTokensOperation> alignmentOperation; using (Logger.LogBlock(FunctionId.Formatting_CollectAlignOperation, cancellationToken)) { var operations = AddOperations<AlignTokensOperation>(nodeIterator, (l, n) => _formattingRules.AddAlignTokensOperations(l, n), cancellationToken); // make sure we order align operation from left to right operations.Sort((o1, o2) => o1.BaseToken.Span.CompareTo(o2.BaseToken.Span)); alignmentOperation = operations; } cancellationToken.ThrowIfCancellationRequested(); List<AnchorIndentationOperation> anchorIndentationOperations; using (Logger.LogBlock(FunctionId.Formatting_CollectAnchorOperation, cancellationToken)) { anchorIndentationOperations = AddOperations<AnchorIndentationOperation>(nodeIterator, (l, n) => _formattingRules.AddAnchorIndentationOperations(l, n), cancellationToken); } return new NodeOperations(indentBlockOperation, suppressOperation, anchorIndentationOperations, alignmentOperation); } private static List<T> AddOperations<T>(SegmentedList<SyntaxNode> nodes, Action<List<T>, SyntaxNode> addOperations, CancellationToken cancellationToken) { var operations = new List<T>(); var list = new List<T>(); foreach (var n in nodes) { cancellationToken.ThrowIfCancellationRequested(); addOperations(list, n); list.RemoveAll(item => item == null); operations.AddRange(list); list.Clear(); } return operations; } private SegmentedArray<TokenPairWithOperations> CreateTokenOperation( TokenStream tokenStream, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using (Logger.LogBlock(FunctionId.Formatting_CollectTokenOperation, cancellationToken)) { // pre-allocate list once. this is cheaper than re-adjusting list as items are added. var list = new SegmentedArray<TokenPairWithOperations>(tokenStream.TokenCount - 1); foreach (var (index, currentToken, nextToken) in tokenStream.TokenIterator) { cancellationToken.ThrowIfCancellationRequested(); var spaceOperation = _formattingRules.GetAdjustSpacesOperation(currentToken, nextToken); var lineOperation = _formattingRules.GetAdjustNewLinesOperation(currentToken, nextToken); list[index] = new TokenPairWithOperations(tokenStream, index, spaceOperation, lineOperation); } return list; } } private void ApplyTokenOperations( FormattingContext context, NodeOperations nodeOperations, SegmentedArray<TokenPairWithOperations> tokenOperations, CancellationToken cancellationToken) { var applier = new OperationApplier(context, _formattingRules); ApplySpaceAndWrappingOperations(context, tokenOperations, applier, cancellationToken); ApplyAnchorOperations(context, tokenOperations, applier, cancellationToken); ApplySpecialOperations(context, nodeOperations, applier, cancellationToken); } private void ApplyBeginningOfTreeTriviaOperation( FormattingContext context, CancellationToken cancellationToken) { if (!context.TokenStream.FormatBeginningOfTree) { return; } // remove all leading indentation var triviaInfo = context.TokenStream.GetTriviaDataAtBeginningOfTree().WithIndentation(0, context, _formattingRules, cancellationToken); triviaInfo.Format(context, _formattingRules, BeginningOfTreeTriviaInfoApplier, cancellationToken); return; // local functions static void BeginningOfTreeTriviaInfoApplier(int i, TokenStream ts, TriviaData info) => ts.ApplyBeginningOfTreeChange(info); } private void ApplyEndOfTreeTriviaOperation( FormattingContext context, CancellationToken cancellationToken) { if (!context.TokenStream.FormatEndOfTree) { return; } if (context.IsFormattingDisabled(new TextSpan(context.TokenStream.LastTokenInStream.Token.SpanStart, 0))) { // Formatting is suppressed in the document, and not restored before the end return; } // remove all trailing indentation var triviaInfo = context.TokenStream.GetTriviaDataAtEndOfTree().WithIndentation(0, context, _formattingRules, cancellationToken); triviaInfo.Format(context, _formattingRules, EndOfTreeTriviaInfoApplier, cancellationToken); return; // local functions static void EndOfTreeTriviaInfoApplier(int i, TokenStream ts, TriviaData info) => ts.ApplyEndOfTreeChange(info); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowCaptures = false)] private void ApplyTriviaOperations(FormattingContext context, CancellationToken cancellationToken) { for (var i = 0; i < context.TokenStream.TokenCount - 1; i++) { cancellationToken.ThrowIfCancellationRequested(); TriviaFormatter(i, context, _formattingRules, cancellationToken); } return; // local functions static void RegularApplier(int tokenPairIndex, TokenStream ts, TriviaData info) => ts.ApplyChange(tokenPairIndex, info); static void TriviaFormatter(int tokenPairIndex, FormattingContext ctx, ChainedFormattingRules formattingRules, CancellationToken ct) { if (ctx.IsFormattingDisabled(tokenPairIndex)) { return; } var triviaInfo = ctx.TokenStream.GetTriviaData(tokenPairIndex); triviaInfo.Format( ctx, formattingRules, (tokenPairIndex1, ts, info) => RegularApplier(tokenPairIndex1, ts, info), ct, tokenPairIndex); } } private TextSpan GetSpanToFormat() { var startPosition = this.TreeData.IsFirstToken(_token1) ? this.TreeData.StartPosition : _token1.SpanStart; var endPosition = this.TreeData.IsLastToken(_token2) ? this.TreeData.EndPosition : _token2.Span.End; return TextSpan.FromBounds(startPosition, endPosition); } private static void ApplySpecialOperations( FormattingContext context, NodeOperations nodeOperationsCollector, OperationApplier applier, CancellationToken cancellationToken) { // apply alignment operation using (Logger.LogBlock(FunctionId.Formatting_CollectAlignOperation, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); // TODO : figure out a way to run alignment operations in parallel. probably find // unions and run each chunk in separate tasks var previousChangesMap = new Dictionary<SyntaxToken, int>(); var alignmentOperations = nodeOperationsCollector.AlignmentOperation; alignmentOperations.Do(operation => { cancellationToken.ThrowIfCancellationRequested(); applier.ApplyAlignment(operation, previousChangesMap, cancellationToken); }); // go through all relative indent block operation, and see whether it is affected by previous operations context.GetAllRelativeIndentBlockOperations().Do(o => { cancellationToken.ThrowIfCancellationRequested(); applier.ApplyBaseTokenIndentationChangesFromTo(FindCorrectBaseTokenOfRelativeIndentBlockOperation(o, context.TokenStream), o.StartToken, o.EndToken, previousChangesMap, cancellationToken); }); } } private static void ApplyAnchorOperations( FormattingContext context, SegmentedArray<TokenPairWithOperations> tokenOperations, OperationApplier applier, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Formatting_ApplyAnchorOperation, cancellationToken)) { // TODO: find out a way to apply anchor operation concurrently if possible var previousChangesMap = new Dictionary<SyntaxToken, int>(); foreach (var p in tokenOperations) { cancellationToken.ThrowIfCancellationRequested(); if (!AnchorOperationCandidate(p)) { continue; } var pairIndex = p.PairIndex; applier.ApplyAnchorIndentation(pairIndex, previousChangesMap, cancellationToken); } // go through all relative indent block operation, and see whether it is affected by the anchor operation context.GetAllRelativeIndentBlockOperations().Do(o => { cancellationToken.ThrowIfCancellationRequested(); applier.ApplyBaseTokenIndentationChangesFromTo(FindCorrectBaseTokenOfRelativeIndentBlockOperation(o, context.TokenStream), o.StartToken, o.EndToken, previousChangesMap, cancellationToken); }); } } private static bool AnchorOperationCandidate(TokenPairWithOperations pair) { if (pair.LineOperation == null) { return pair.TokenStream.GetTriviaData(pair.PairIndex).SecondTokenIsFirstTokenOnLine; } if (pair.LineOperation.Option == AdjustNewLinesOption.ForceLinesIfOnSingleLine) { return !pair.TokenStream.TwoTokensOriginallyOnSameLine(pair.Token1, pair.Token2) && pair.TokenStream.GetTriviaData(pair.PairIndex).SecondTokenIsFirstTokenOnLine; } return false; } private static SyntaxToken FindCorrectBaseTokenOfRelativeIndentBlockOperation(IndentBlockOperation operation, TokenStream tokenStream) { if (operation.Option.IsOn(IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine)) { return tokenStream.FirstTokenOfBaseTokenLine(operation.BaseToken); } return operation.BaseToken; } private static void ApplySpaceAndWrappingOperations( FormattingContext context, SegmentedArray<TokenPairWithOperations> tokenOperations, OperationApplier applier, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Formatting_ApplySpaceAndLine, cancellationToken)) { // go through each token pairs and apply operations foreach (var operationPair in tokenOperations) { ApplySpaceAndWrappingOperationsBody(context, operationPair, applier, cancellationToken); } } } private static void ApplySpaceAndWrappingOperationsBody( FormattingContext context, TokenPairWithOperations operation, OperationApplier applier, CancellationToken cancellationToken) { var token1 = operation.Token1; var token2 = operation.Token2; // check whether one of tokens is missing (which means syntax error exist around two tokens) // in error case, we leave code as user wrote if (token1.IsMissing || token2.IsMissing) { return; } var triviaInfo = context.TokenStream.GetTriviaData(operation.PairIndex); var spanBetweenTokens = TextSpan.FromBounds(token1.Span.End, token2.SpanStart); if (operation.LineOperation != null) { if (!context.IsWrappingSuppressed(spanBetweenTokens, triviaInfo.TreatAsElastic)) { // TODO : need to revisit later for the case where line and space operations // are conflicting each other by forcing new lines and removing new lines. // // if wrapping operation applied, no need to run any other operation if (applier.Apply(operation.LineOperation, operation.PairIndex, cancellationToken)) { return; } } } if (operation.SpaceOperation != null) { if (!context.IsSpacingSuppressed(spanBetweenTokens, triviaInfo.TreatAsElastic)) { applier.Apply(operation.SpaceOperation, operation.PairIndex); } } } private static void BuildContext( FormattingContext context, NodeOperations nodeOperations, CancellationToken cancellationToken) { // add scope operation (run each kind sequentially) using (Logger.LogBlock(FunctionId.Formatting_BuildContext, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); context.AddIndentBlockOperations(nodeOperations.IndentBlockOperation, cancellationToken); context.AddSuppressOperations(nodeOperations.SuppressOperation, cancellationToken); } } /// <summary> /// return summary for current formatting work /// </summary> private string FormatSummary() { return string.Format("({0}) ({1} - {2})", this.SpanToFormat, _token1.ToString().Replace("\r\n", "\\r\\n"), _token2.ToString().Replace("\r\n", "\\r\\n")); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/CodeRefactorings/ConvertLocalFunctionToMethod/CSharpConvertLocalFunctionToMethodCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ConvertLocalFunctionToMethod { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertLocalFunctionToMethod), Shared] internal sealed class CSharpConvertLocalFunctionToMethodCodeRefactoringProvider : CodeRefactoringProvider { private static readonly SyntaxAnnotation s_delegateToReplaceAnnotation = new SyntaxAnnotation(); private static readonly SyntaxGenerator s_generator = CSharpSyntaxGenerator.Instance; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertLocalFunctionToMethodCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var localFunction = await context.TryGetRelevantNodeAsync<LocalFunctionStatementSyntax>().ConfigureAwait(false); if (localFunction == null) { return; } if (!localFunction.Parent.IsKind(SyntaxKind.Block, out BlockSyntax parentBlock)) { return; } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); context.RegisterRefactoring( new MyCodeAction( c => UpdateDocumentAsync(root, document, parentBlock, localFunction, c)), localFunction.Span); } private static async Task<Document> UpdateDocumentAsync( SyntaxNode root, Document document, BlockSyntax parentBlock, LocalFunctionStatementSyntax localFunction, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var declaredSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(localFunction, cancellationToken); var dataFlow = semanticModel.AnalyzeDataFlow( localFunction.Body ?? (SyntaxNode)localFunction.ExpressionBody.Expression); // Exclude local function parameters in case they were captured inside the function body var captures = dataFlow.CapturedInside.Except(dataFlow.VariablesDeclared).Except(declaredSymbol.Parameters).ToList(); // First, create a parameter per each capture so that we can pass them as arguments to the final method // Filter out `this` because it doesn't need a parameter, we will just make a non-static method for that // We also make a `ref` parameter here for each capture that is being written into inside the function var capturesAsParameters = captures .Where(capture => !capture.IsThisParameter()) .Select(capture => CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: dataFlow.WrittenInside.Contains(capture) ? RefKind.Ref : RefKind.None, isParams: false, type: capture.GetSymbolType(), name: capture.Name)).ToList(); // Find all enclosing type parameters e.g. from outer local functions and the containing member // We exclude the containing type itself which has type parameters accessible to all members var typeParameters = new List<ITypeParameterSymbol>(); GetCapturedTypeParameters(declaredSymbol, typeParameters); // We're going to remove unreferenced type parameters but we explicitly preserve // captures' types, just in case that they were not spelt out in the function body var captureTypes = captures.SelectMany(capture => capture.GetSymbolType().GetReferencedTypeParameters()); RemoveUnusedTypeParameters(localFunction, semanticModel, typeParameters, reservedTypeParameters: captureTypes); var container = localFunction.GetAncestor<MemberDeclarationSyntax>(); var containerSymbol = semanticModel.GetDeclaredSymbol(container, cancellationToken); var isStatic = containerSymbol.IsStatic || captures.All(capture => !capture.IsThisParameter()); // GetSymbolModifiers actually checks if the local function needs to be unsafe, not whether // it is declared as such, so this check we don't need to worry about whether the containing method // is unsafe, this will just work regardless. var needsUnsafe = declaredSymbol.GetSymbolModifiers().IsUnsafe; var methodName = GenerateUniqueMethodName(declaredSymbol); var parameters = declaredSymbol.Parameters; var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( containingType: declaredSymbol.ContainingType, attributes: default, accessibility: Accessibility.Private, modifiers: new DeclarationModifiers(isStatic, isAsync: declaredSymbol.IsAsync, isUnsafe: needsUnsafe), returnType: declaredSymbol.ReturnType, refKind: default, explicitInterfaceImplementations: default, name: methodName, typeParameters: typeParameters.ToImmutableArray(), parameters: parameters.AddRange(capturesAsParameters)); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var defaultOptions = new CodeGenerationOptions(options: options); var method = MethodGenerator.GenerateMethodDeclaration(methodSymbol, CodeGenerationDestination.Unspecified, defaultOptions, root.SyntaxTree.Options); var generator = s_generator; var editor = new SyntaxEditor(root, generator); var needsRename = methodName != declaredSymbol.Name; var identifierToken = needsRename ? methodName.ToIdentifierToken() : default; var supportsNonTrailing = SupportsNonTrailingNamedArguments(root.SyntaxTree.Options); var hasAdditionalArguments = !capturesAsParameters.IsEmpty(); var additionalTypeParameters = typeParameters.Except(declaredSymbol.TypeParameters).ToList(); var hasAdditionalTypeArguments = !additionalTypeParameters.IsEmpty(); var additionalTypeArguments = hasAdditionalTypeArguments ? additionalTypeParameters.Select(p => (TypeSyntax)p.Name.ToIdentifierName()).ToArray() : null; var anyDelegatesToReplace = false; // Update callers' name, arguments and type arguments foreach (var node in parentBlock.DescendantNodes()) { // A local function reference can only be an identifier or a generic name. switch (node.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: break; default: continue; } // Using symbol to get type arguments, since it could be inferred and not present in the source var symbol = semanticModel.GetSymbolInfo(node, cancellationToken).Symbol as IMethodSymbol; if (!Equals(symbol?.OriginalDefinition, declaredSymbol)) { continue; } var currentNode = node; if (needsRename) { currentNode = ((SimpleNameSyntax)currentNode).WithIdentifier(identifierToken); } if (hasAdditionalTypeArguments) { var existingTypeArguments = symbol.TypeArguments.Select(s => s.GenerateTypeSyntax()); // Prepend additional type arguments to preserve lexical order in which they are defined var typeArguments = additionalTypeArguments.Concat(existingTypeArguments); currentNode = generator.WithTypeArguments(currentNode, typeArguments); currentNode = currentNode.WithAdditionalAnnotations(Simplifier.Annotation); } if (node.Parent.IsKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax invocation)) { if (hasAdditionalArguments) { var shouldUseNamedArguments = !supportsNonTrailing && invocation.ArgumentList.Arguments.Any(arg => arg.NameColon != null); var additionalArguments = capturesAsParameters.Select(p => (ArgumentSyntax)GenerateArgument(p, p.Name, shouldUseNamedArguments)).ToArray(); editor.ReplaceNode(invocation.ArgumentList, invocation.ArgumentList.AddArguments(additionalArguments)); } } else if (hasAdditionalArguments || hasAdditionalTypeArguments) { // Convert local function delegates to lambda if the signature no longer matches currentNode = currentNode.WithAdditionalAnnotations(s_delegateToReplaceAnnotation); anyDelegatesToReplace = true; } editor.ReplaceNode(node, currentNode); } editor.TrackNode(localFunction); editor.TrackNode(container); root = editor.GetChangedRoot(); localFunction = root.GetCurrentNode(localFunction); container = root.GetCurrentNode(container); method = WithBodyFrom(method, localFunction); editor = new SyntaxEditor(root, generator); editor.InsertAfter(container, method); editor.RemoveNode(localFunction, SyntaxRemoveOptions.KeepNoTrivia); if (anyDelegatesToReplace) { document = document.WithSyntaxRoot(editor.GetChangedRoot()); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); editor = new SyntaxEditor(root, generator); foreach (var node in root.GetAnnotatedNodes(s_delegateToReplaceAnnotation)) { var reservedNames = GetReservedNames(node, semanticModel, cancellationToken); var parameterNames = GenerateUniqueParameterNames(parameters, reservedNames); var lambdaParameters = parameters.Zip(parameterNames, (p, name) => GenerateParameter(p, name)); var lambdaArguments = parameters.Zip(parameterNames, (p, name) => GenerateArgument(p, name)); var additionalArguments = capturesAsParameters.Select(p => GenerateArgument(p, p.Name)); var newNode = generator.ValueReturningLambdaExpression(lambdaParameters, generator.InvocationExpression(node, lambdaArguments.Concat(additionalArguments))); newNode = newNode.WithAdditionalAnnotations(Simplifier.Annotation); if (node.IsParentKind(SyntaxKind.CastExpression)) { newNode = ((ExpressionSyntax)newNode).Parenthesize(); } editor.ReplaceNode(node, newNode); } } return document.WithSyntaxRoot(editor.GetChangedRoot()); } private static bool SupportsNonTrailingNamedArguments(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7_2; private static SyntaxNode GenerateArgument(IParameterSymbol p, string name, bool shouldUseNamedArguments = false) => s_generator.Argument(shouldUseNamedArguments ? name : null, p.RefKind, name.ToIdentifierName()); private static List<string> GenerateUniqueParameterNames(ImmutableArray<IParameterSymbol> parameters, List<string> reservedNames) => parameters.Select(p => NameGenerator.EnsureUniqueness(p.Name, reservedNames)).ToList(); private static List<string> GetReservedNames(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) => semanticModel.GetAllDeclaredSymbols(node.GetAncestor<MemberDeclarationSyntax>(), cancellationToken).Select(s => s.Name).ToList(); private static ParameterSyntax GenerateParameter(IParameterSymbol p, string name) { return SyntaxFactory.Parameter(name.ToIdentifierToken()) .WithModifiers(CSharpSyntaxGeneratorInternal.GetParameterModifiers(p.RefKind)) .WithType(p.Type.GenerateTypeSyntax()); } private static MethodDeclarationSyntax WithBodyFrom( MethodDeclarationSyntax method, LocalFunctionStatementSyntax localFunction) { return method .WithExpressionBody(localFunction.ExpressionBody) .WithSemicolonToken(localFunction.SemicolonToken) .WithBody(localFunction.Body); } private static void GetCapturedTypeParameters(ISymbol symbol, List<ITypeParameterSymbol> typeParameters) { var containingSymbol = symbol.ContainingSymbol; if (containingSymbol != null && containingSymbol.Kind != SymbolKind.NamedType) { GetCapturedTypeParameters(containingSymbol, typeParameters); } typeParameters.AddRange(symbol.GetTypeParameters()); } private static void RemoveUnusedTypeParameters( SyntaxNode localFunction, SemanticModel semanticModel, List<ITypeParameterSymbol> typeParameters, IEnumerable<ITypeParameterSymbol> reservedTypeParameters) { var unusedTypeParameters = typeParameters.ToList(); foreach (var id in localFunction.DescendantNodes().OfType<IdentifierNameSyntax>()) { var symbol = semanticModel.GetSymbolInfo(id).Symbol; if (symbol != null && symbol.OriginalDefinition is ITypeParameterSymbol typeParameter) { unusedTypeParameters.Remove(typeParameter); } } typeParameters.RemoveRange(unusedTypeParameters.Except(reservedTypeParameters)); } private static string GenerateUniqueMethodName(ISymbol declaredSymbol) { return NameGenerator.EnsureUniqueness( baseName: declaredSymbol.Name, reservedNames: declaredSymbol.ContainingType.GetMembers().Select(m => m.Name)); } private sealed class MyCodeAction : CodeActions.CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Convert_to_method, createChangedDocument, nameof(CSharpFeaturesResources.Convert_to_method)) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ConvertLocalFunctionToMethod { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertLocalFunctionToMethod), Shared] internal sealed class CSharpConvertLocalFunctionToMethodCodeRefactoringProvider : CodeRefactoringProvider { private static readonly SyntaxAnnotation s_delegateToReplaceAnnotation = new SyntaxAnnotation(); private static readonly SyntaxGenerator s_generator = CSharpSyntaxGenerator.Instance; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertLocalFunctionToMethodCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var localFunction = await context.TryGetRelevantNodeAsync<LocalFunctionStatementSyntax>().ConfigureAwait(false); if (localFunction == null) { return; } if (!localFunction.Parent.IsKind(SyntaxKind.Block, out BlockSyntax parentBlock)) { return; } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); context.RegisterRefactoring( new MyCodeAction( c => UpdateDocumentAsync(root, document, parentBlock, localFunction, c)), localFunction.Span); } private static async Task<Document> UpdateDocumentAsync( SyntaxNode root, Document document, BlockSyntax parentBlock, LocalFunctionStatementSyntax localFunction, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var declaredSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(localFunction, cancellationToken); var dataFlow = semanticModel.AnalyzeDataFlow( localFunction.Body ?? (SyntaxNode)localFunction.ExpressionBody.Expression); // Exclude local function parameters in case they were captured inside the function body var captures = dataFlow.CapturedInside.Except(dataFlow.VariablesDeclared).Except(declaredSymbol.Parameters).ToList(); // First, create a parameter per each capture so that we can pass them as arguments to the final method // Filter out `this` because it doesn't need a parameter, we will just make a non-static method for that // We also make a `ref` parameter here for each capture that is being written into inside the function var capturesAsParameters = captures .Where(capture => !capture.IsThisParameter()) .Select(capture => CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: dataFlow.WrittenInside.Contains(capture) ? RefKind.Ref : RefKind.None, isParams: false, type: capture.GetSymbolType(), name: capture.Name)).ToList(); // Find all enclosing type parameters e.g. from outer local functions and the containing member // We exclude the containing type itself which has type parameters accessible to all members var typeParameters = new List<ITypeParameterSymbol>(); GetCapturedTypeParameters(declaredSymbol, typeParameters); // We're going to remove unreferenced type parameters but we explicitly preserve // captures' types, just in case that they were not spelt out in the function body var captureTypes = captures.SelectMany(capture => capture.GetSymbolType().GetReferencedTypeParameters()); RemoveUnusedTypeParameters(localFunction, semanticModel, typeParameters, reservedTypeParameters: captureTypes); var container = localFunction.GetAncestor<MemberDeclarationSyntax>(); var containerSymbol = semanticModel.GetDeclaredSymbol(container, cancellationToken); var isStatic = containerSymbol.IsStatic || captures.All(capture => !capture.IsThisParameter()); // GetSymbolModifiers actually checks if the local function needs to be unsafe, not whether // it is declared as such, so this check we don't need to worry about whether the containing method // is unsafe, this will just work regardless. var needsUnsafe = declaredSymbol.GetSymbolModifiers().IsUnsafe; var methodName = GenerateUniqueMethodName(declaredSymbol); var parameters = declaredSymbol.Parameters; var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( containingType: declaredSymbol.ContainingType, attributes: default, accessibility: Accessibility.Private, modifiers: new DeclarationModifiers(isStatic, isAsync: declaredSymbol.IsAsync, isUnsafe: needsUnsafe), returnType: declaredSymbol.ReturnType, refKind: default, explicitInterfaceImplementations: default, name: methodName, typeParameters: typeParameters.ToImmutableArray(), parameters: parameters.AddRange(capturesAsParameters)); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var defaultOptions = new CodeGenerationOptions(options: options); var method = MethodGenerator.GenerateMethodDeclaration(methodSymbol, CodeGenerationDestination.Unspecified, defaultOptions, root.SyntaxTree.Options); var generator = s_generator; var editor = new SyntaxEditor(root, generator); var needsRename = methodName != declaredSymbol.Name; var identifierToken = needsRename ? methodName.ToIdentifierToken() : default; var supportsNonTrailing = SupportsNonTrailingNamedArguments(root.SyntaxTree.Options); var hasAdditionalArguments = !capturesAsParameters.IsEmpty(); var additionalTypeParameters = typeParameters.Except(declaredSymbol.TypeParameters).ToList(); var hasAdditionalTypeArguments = !additionalTypeParameters.IsEmpty(); var additionalTypeArguments = hasAdditionalTypeArguments ? additionalTypeParameters.Select(p => (TypeSyntax)p.Name.ToIdentifierName()).ToArray() : null; var anyDelegatesToReplace = false; // Update callers' name, arguments and type arguments foreach (var node in parentBlock.DescendantNodes()) { // A local function reference can only be an identifier or a generic name. switch (node.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: break; default: continue; } // Using symbol to get type arguments, since it could be inferred and not present in the source var symbol = semanticModel.GetSymbolInfo(node, cancellationToken).Symbol as IMethodSymbol; if (!Equals(symbol?.OriginalDefinition, declaredSymbol)) { continue; } var currentNode = node; if (needsRename) { currentNode = ((SimpleNameSyntax)currentNode).WithIdentifier(identifierToken); } if (hasAdditionalTypeArguments) { var existingTypeArguments = symbol.TypeArguments.Select(s => s.GenerateTypeSyntax()); // Prepend additional type arguments to preserve lexical order in which they are defined var typeArguments = additionalTypeArguments.Concat(existingTypeArguments); currentNode = generator.WithTypeArguments(currentNode, typeArguments); currentNode = currentNode.WithAdditionalAnnotations(Simplifier.Annotation); } if (node.Parent.IsKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax invocation)) { if (hasAdditionalArguments) { var shouldUseNamedArguments = !supportsNonTrailing && invocation.ArgumentList.Arguments.Any(arg => arg.NameColon != null); var additionalArguments = capturesAsParameters.Select(p => (ArgumentSyntax)GenerateArgument(p, p.Name, shouldUseNamedArguments)).ToArray(); editor.ReplaceNode(invocation.ArgumentList, invocation.ArgumentList.AddArguments(additionalArguments)); } } else if (hasAdditionalArguments || hasAdditionalTypeArguments) { // Convert local function delegates to lambda if the signature no longer matches currentNode = currentNode.WithAdditionalAnnotations(s_delegateToReplaceAnnotation); anyDelegatesToReplace = true; } editor.ReplaceNode(node, currentNode); } editor.TrackNode(localFunction); editor.TrackNode(container); root = editor.GetChangedRoot(); localFunction = root.GetCurrentNode(localFunction); container = root.GetCurrentNode(container); method = WithBodyFrom(method, localFunction); editor = new SyntaxEditor(root, generator); editor.InsertAfter(container, method); editor.RemoveNode(localFunction, SyntaxRemoveOptions.KeepNoTrivia); if (anyDelegatesToReplace) { document = document.WithSyntaxRoot(editor.GetChangedRoot()); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); editor = new SyntaxEditor(root, generator); foreach (var node in root.GetAnnotatedNodes(s_delegateToReplaceAnnotation)) { var reservedNames = GetReservedNames(node, semanticModel, cancellationToken); var parameterNames = GenerateUniqueParameterNames(parameters, reservedNames); var lambdaParameters = parameters.Zip(parameterNames, (p, name) => GenerateParameter(p, name)); var lambdaArguments = parameters.Zip(parameterNames, (p, name) => GenerateArgument(p, name)); var additionalArguments = capturesAsParameters.Select(p => GenerateArgument(p, p.Name)); var newNode = generator.ValueReturningLambdaExpression(lambdaParameters, generator.InvocationExpression(node, lambdaArguments.Concat(additionalArguments))); newNode = newNode.WithAdditionalAnnotations(Simplifier.Annotation); if (node.IsParentKind(SyntaxKind.CastExpression)) { newNode = ((ExpressionSyntax)newNode).Parenthesize(); } editor.ReplaceNode(node, newNode); } } return document.WithSyntaxRoot(editor.GetChangedRoot()); } private static bool SupportsNonTrailingNamedArguments(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7_2; private static SyntaxNode GenerateArgument(IParameterSymbol p, string name, bool shouldUseNamedArguments = false) => s_generator.Argument(shouldUseNamedArguments ? name : null, p.RefKind, name.ToIdentifierName()); private static List<string> GenerateUniqueParameterNames(ImmutableArray<IParameterSymbol> parameters, List<string> reservedNames) => parameters.Select(p => NameGenerator.EnsureUniqueness(p.Name, reservedNames)).ToList(); private static List<string> GetReservedNames(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) => semanticModel.GetAllDeclaredSymbols(node.GetAncestor<MemberDeclarationSyntax>(), cancellationToken).Select(s => s.Name).ToList(); private static ParameterSyntax GenerateParameter(IParameterSymbol p, string name) { return SyntaxFactory.Parameter(name.ToIdentifierToken()) .WithModifiers(CSharpSyntaxGeneratorInternal.GetParameterModifiers(p.RefKind)) .WithType(p.Type.GenerateTypeSyntax()); } private static MethodDeclarationSyntax WithBodyFrom( MethodDeclarationSyntax method, LocalFunctionStatementSyntax localFunction) { return method .WithExpressionBody(localFunction.ExpressionBody) .WithSemicolonToken(localFunction.SemicolonToken) .WithBody(localFunction.Body); } private static void GetCapturedTypeParameters(ISymbol symbol, List<ITypeParameterSymbol> typeParameters) { var containingSymbol = symbol.ContainingSymbol; if (containingSymbol != null && containingSymbol.Kind != SymbolKind.NamedType) { GetCapturedTypeParameters(containingSymbol, typeParameters); } typeParameters.AddRange(symbol.GetTypeParameters()); } private static void RemoveUnusedTypeParameters( SyntaxNode localFunction, SemanticModel semanticModel, List<ITypeParameterSymbol> typeParameters, IEnumerable<ITypeParameterSymbol> reservedTypeParameters) { var unusedTypeParameters = typeParameters.ToList(); foreach (var id in localFunction.DescendantNodes().OfType<IdentifierNameSyntax>()) { var symbol = semanticModel.GetSymbolInfo(id).Symbol; if (symbol != null && symbol.OriginalDefinition is ITypeParameterSymbol typeParameter) { unusedTypeParameters.Remove(typeParameter); } } typeParameters.RemoveRange(unusedTypeParameters.Except(reservedTypeParameters)); } private static string GenerateUniqueMethodName(ISymbol declaredSymbol) { return NameGenerator.EnsureUniqueness( baseName: declaredSymbol.Name, reservedNames: declaredSymbol.ContainingType.GetMembers().Select(m => m.Name)); } private sealed class MyCodeAction : CodeActions.CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Convert_to_method, createChangedDocument, nameof(CSharpFeaturesResources.Convert_to_method)) { } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest2/Recommendations/ConstKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ConstKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass() { await VerifyKeywordAsync( @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement() { await VerifyKeywordAsync( @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration() { await VerifyKeywordAsync( @"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 = $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInEmptyStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync(@"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync(@"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync(@"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync(@"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync(@"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script, Skip = "https://github.com/dotnet/roslyn/issues/9880")] public async Task TestNotBeforeUsing(SourceCodeKind sourceCodeKind) { await VerifyAbsenceAsync(sourceCodeKind, @"$$ using Goo;"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script, Skip = "https://github.com/dotnet/roslyn/issues/9880")] public async Task TestNotBeforeGlobalUsing(SourceCodeKind sourceCodeKind) { await VerifyAbsenceAsync(sourceCodeKind, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync(@"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRootAttribute() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideEnum() { await VerifyAbsenceAsync(@"enum E { $$"); } [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 TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternal() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"internal $$"); [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 TestNotAfterPublic() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"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 TestNotAfterPrivate() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate_Script() { await VerifyKeywordAsync(SourceCodeKind.Script, @"private $$"); } [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 TestNotAfterProtected() { await VerifyAbsenceAsync( @"protected $$"); } [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 TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedSealed() { await VerifyAbsenceAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedStatic() { await VerifyAbsenceAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticPublic() => await VerifyAbsenceAsync(@"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedStaticPublic() { await VerifyAbsenceAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEvent() { await VerifyAbsenceAsync( @"class C { event $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterConst() { await VerifyAbsenceAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNew() { await VerifyAbsenceAsync( @"new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMethod() { await VerifyKeywordAsync( @"class C { void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMethodNotAfterConst() { await VerifyAbsenceAsync( @"class C { void Goo() { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInProperty() { await VerifyKeywordAsync( @"class C { int Goo { get { $$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ConstKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass() { await VerifyKeywordAsync( @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement() { await VerifyKeywordAsync( @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration() { await VerifyKeywordAsync( @"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 = $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInEmptyStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync(@"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync(@"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync(@"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync(@"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync(@"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script, Skip = "https://github.com/dotnet/roslyn/issues/9880")] public async Task TestNotBeforeUsing(SourceCodeKind sourceCodeKind) { await VerifyAbsenceAsync(sourceCodeKind, @"$$ using Goo;"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script, Skip = "https://github.com/dotnet/roslyn/issues/9880")] public async Task TestNotBeforeGlobalUsing(SourceCodeKind sourceCodeKind) { await VerifyAbsenceAsync(sourceCodeKind, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync(@"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRootAttribute() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideEnum() { await VerifyAbsenceAsync(@"enum E { $$"); } [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 TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternal() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"internal $$"); [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 TestNotAfterPublic() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"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 TestNotAfterPrivate() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate_Script() { await VerifyKeywordAsync(SourceCodeKind.Script, @"private $$"); } [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 TestNotAfterProtected() { await VerifyAbsenceAsync( @"protected $$"); } [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 TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedSealed() { await VerifyAbsenceAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedStatic() { await VerifyAbsenceAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticPublic() => await VerifyAbsenceAsync(@"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedStaticPublic() { await VerifyAbsenceAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEvent() { await VerifyAbsenceAsync( @"class C { event $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterConst() { await VerifyAbsenceAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNew() { await VerifyAbsenceAsync( @"new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMethod() { await VerifyKeywordAsync( @"class C { void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMethodNotAfterConst() { await VerifyAbsenceAsync( @"class C { void Goo() { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInProperty() { await VerifyKeywordAsync( @"class C { int Goo { get { $$"); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOptions2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Options; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeStyle.CodeStyleHelpers; namespace Microsoft.CodeAnalysis.CodeStyle { internal static class CodeStyleOptions2 { private static readonly ImmutableArray<IOption2>.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder<IOption2>(); internal static ImmutableArray<IOption2> AllOptions { get; } private static PerLanguageOption2<T> CreateOption<T>(OptionGroup group, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) { var option = new PerLanguageOption2<T>("CodeStyleOptions", group, name, defaultValue, storageLocations); s_allOptionsBuilder.Add(option); return option; } private static Option2<T> CreateCommonOption<T>(OptionGroup group, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) { var option = new Option2<T>("CodeStyleOptions", group, name, defaultValue, storageLocations); s_allOptionsBuilder.Add(option); return option; } private static PerLanguageOption2<CodeStyleOption2<bool>> CreateOption(OptionGroup group, string name, CodeStyleOption2<bool> defaultValue, string editorconfigKeyName, string roamingProfileStorageKeyName) => CreateOption(group, name, defaultValue, EditorConfigStorageLocation.ForBoolCodeStyleOption(editorconfigKeyName, defaultValue), new RoamingProfileStorageLocation(roamingProfileStorageKeyName)); /// <remarks> /// When user preferences are not yet set for a style, we fall back to the default value. /// One such default(s), is that the feature is turned on, so that codegen consumes it, /// but with silent enforcement, so that the user is not prompted about their usage. /// </remarks> internal static readonly CodeStyleOption2<bool> TrueWithSilentEnforcement = new(value: true, notification: NotificationOption2.Silent); internal static readonly CodeStyleOption2<bool> FalseWithSilentEnforcement = new(value: false, notification: NotificationOption2.Silent); internal static readonly CodeStyleOption2<bool> TrueWithSuggestionEnforcement = new(value: true, notification: NotificationOption2.Suggestion); internal static readonly CodeStyleOption2<bool> FalseWithSuggestionEnforcement = new(value: false, notification: NotificationOption2.Suggestion); private static PerLanguageOption2<CodeStyleOption2<bool>> CreateQualifyAccessOption(string optionName, string editorconfigKeyName) => CreateOption( CodeStyleOptionGroups.ThisOrMe, optionName, defaultValue: CodeStyleOption2<bool>.Default, editorconfigKeyName, $"TextEditor.%LANGUAGE%.Specific.{optionName}"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in field access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyFieldAccess = CreateQualifyAccessOption( nameof(QualifyFieldAccess), "dotnet_style_qualification_for_field"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in property access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyPropertyAccess = CreateQualifyAccessOption( nameof(QualifyPropertyAccess), "dotnet_style_qualification_for_property"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in method access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyMethodAccess = CreateQualifyAccessOption( nameof(QualifyMethodAccess), "dotnet_style_qualification_for_method"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in event access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyEventAccess = CreateQualifyAccessOption( nameof(QualifyEventAccess), "dotnet_style_qualification_for_event"); /// <summary> /// This option says if we should prefer keyword for Intrinsic Predefined Types in Declarations /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIntrinsicPredefinedTypeKeywordInDeclaration = CreateOption( CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInDeclaration), defaultValue: TrueWithSilentEnforcement, "dotnet_style_predefined_type_for_locals_parameters_members", "TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInDeclaration.CodeStyle"); /// <summary> /// This option says if we should prefer keyword for Intrinsic Predefined Types in Member Access Expression /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIntrinsicPredefinedTypeKeywordInMemberAccess = CreateOption( CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInMemberAccess), defaultValue: TrueWithSilentEnforcement, "dotnet_style_predefined_type_for_member_access", "TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInMemberAccess.CodeStyle"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferObjectInitializer = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferObjectInitializer), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_object_initializer", "TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCollectionInitializer = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCollectionInitializer), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_collection_initializer", "TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer"); // TODO: Should both the below "_FadeOutCode" options be added to AllOptions? internal static readonly PerLanguageOption2<bool> PreferObjectInitializer_FadeOutCode = new( "CodeStyleOptions", nameof(PreferObjectInitializer_FadeOutCode), defaultValue: false, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer_FadeOutCode")); internal static readonly PerLanguageOption2<bool> PreferCollectionInitializer_FadeOutCode = new( "CodeStyleOptions", nameof(PreferCollectionInitializer_FadeOutCode), defaultValue: false, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer_FadeOutCode")); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSimplifiedBooleanExpressions = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedBooleanExpressions), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_simplified_boolean_expressions", "TextEditor.%LANGUAGE%.Specific.PreferSimplifiedBooleanExpressions"); internal static readonly PerLanguageOption2<OperatorPlacementWhenWrappingPreference> OperatorPlacementWhenWrapping = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(OperatorPlacementWhenWrapping), defaultValue: OperatorPlacementWhenWrappingPreference.BeginningOfLine, storageLocations: new EditorConfigStorageLocation<OperatorPlacementWhenWrappingPreference>( "dotnet_style_operator_placement_when_wrapping", OperatorPlacementUtilities.Parse, OperatorPlacementUtilities.GetEditorConfigString)); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCoalesceExpression = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCoalesceExpression), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_coalesce_expression", "TextEditor.%LANGUAGE%.Specific.PreferCoalesceExpression"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferNullPropagation = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNullPropagation), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_null_propagation", "TextEditor.%LANGUAGE%.Specific.PreferNullPropagation"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferExplicitTupleNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferExplicitTupleNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_explicit_tuple_names", "TextEditor.%LANGUAGE%.Specific.PreferExplicitTupleNames"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferAutoProperties = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferAutoProperties), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_auto_properties", "TextEditor.%LANGUAGE%.Specific.PreferAutoProperties"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferInferredTupleNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredTupleNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_inferred_tuple_names", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredTupleNames)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferInferredAnonymousTypeMemberNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredAnonymousTypeMemberNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_inferred_anonymous_type_member_names", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredAnonymousTypeMemberNames)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIsNullCheckOverReferenceEqualityMethod = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferIsNullCheckOverReferenceEqualityMethod), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_is_null_check_over_reference_equality_method", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferIsNullCheckOverReferenceEqualityMethod)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferConditionalExpressionOverAssignment = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverAssignment), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_conditional_expression_over_assignment", "TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverAssignment"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferConditionalExpressionOverReturn = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverReturn), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_conditional_expression_over_return", "TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverReturn"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCompoundAssignment = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCompoundAssignment), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_compound_assignment", "TextEditor.%LANGUAGE%.Specific.PreferCompoundAssignment"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSimplifiedInterpolation = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedInterpolation), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_simplified_interpolation", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferSimplifiedInterpolation)}"); private static readonly CodeStyleOption2<UnusedParametersPreference> s_preferAllMethodsUnusedParametersPreference = new(UnusedParametersPreference.AllMethods, NotificationOption2.Suggestion); // TODO: https://github.com/dotnet/roslyn/issues/31225 tracks adding CodeQualityOption<T> and CodeQualityOptions // and moving this option to CodeQualityOptions. internal static readonly PerLanguageOption2<CodeStyleOption2<UnusedParametersPreference>> UnusedParameters = CreateOption( CodeStyleOptionGroups.Parameter, nameof(UnusedParameters), defaultValue: s_preferAllMethodsUnusedParametersPreference, storageLocations: new OptionStorageLocation2[]{ new EditorConfigStorageLocation<CodeStyleOption2<UnusedParametersPreference>>( "dotnet_code_quality_unused_parameters", s => ParseUnusedParametersPreference(s, s_preferAllMethodsUnusedParametersPreference), o => GetUnusedParametersPreferenceEditorConfigString(o, s_preferAllMethodsUnusedParametersPreference)), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(UnusedParameters)}Preference") }); private static readonly CodeStyleOption2<AccessibilityModifiersRequired> s_requireAccessibilityModifiersDefault = new(AccessibilityModifiersRequired.ForNonInterfaceMembers, NotificationOption2.Silent); internal static readonly PerLanguageOption2<CodeStyleOption2<AccessibilityModifiersRequired>> RequireAccessibilityModifiers = CreateOption( CodeStyleOptionGroups.Modifier, nameof(RequireAccessibilityModifiers), defaultValue: s_requireAccessibilityModifiersDefault, storageLocations: new OptionStorageLocation2[]{ new EditorConfigStorageLocation<CodeStyleOption2<AccessibilityModifiersRequired>>( "dotnet_style_require_accessibility_modifiers", s => ParseAccessibilityModifiersRequired(s, s_requireAccessibilityModifiersDefault), v => GetAccessibilityModifiersRequiredEditorConfigString(v, s_requireAccessibilityModifiersDefault)), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RequireAccessibilityModifiers")}); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferReadonly = CreateOption( CodeStyleOptionGroups.Field, nameof(PreferReadonly), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_readonly_field", "TextEditor.%LANGUAGE%.Specific.PreferReadonly"); internal static readonly Option2<string> FileHeaderTemplate = CreateCommonOption( CodeStyleOptionGroups.Usings, nameof(FileHeaderTemplate), defaultValue: "", EditorConfigStorageLocation.ForStringOption("file_header_template", emptyStringRepresentation: "unset")); internal static readonly Option2<string> RemoveUnnecessarySuppressionExclusions = CreateCommonOption( CodeStyleOptionGroups.Suppressions, nameof(RemoveUnnecessarySuppressionExclusions), defaultValue: "", storageLocations: new OptionStorageLocation2[]{ EditorConfigStorageLocation.ForStringOption("dotnet_remove_unnecessary_suppression_exclusions", emptyStringRepresentation: "none"), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RemoveUnnecessarySuppressionExclusions") }); private static readonly BidirectionalMap<string, AccessibilityModifiersRequired> s_accessibilityModifiersRequiredMap = new(new[] { KeyValuePairUtil.Create("never", AccessibilityModifiersRequired.Never), KeyValuePairUtil.Create("always", AccessibilityModifiersRequired.Always), KeyValuePairUtil.Create("for_non_interface_members", AccessibilityModifiersRequired.ForNonInterfaceMembers), KeyValuePairUtil.Create("omit_if_default", AccessibilityModifiersRequired.OmitIfDefault), }); private static CodeStyleOption2<AccessibilityModifiersRequired> ParseAccessibilityModifiersRequired(string optionString, CodeStyleOption2<AccessibilityModifiersRequired> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notificationOpt)) { Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsKey(value)); return new CodeStyleOption2<AccessibilityModifiersRequired>(s_accessibilityModifiersRequiredMap.GetValueOrDefault(value), notificationOpt); } return s_requireAccessibilityModifiersDefault; } private static string GetAccessibilityModifiersRequiredEditorConfigString(CodeStyleOption2<AccessibilityModifiersRequired> option, CodeStyleOption2<AccessibilityModifiersRequired> defaultValue) { // If they provide 'never', they don't need a notification level. if (option.Notification == null) { Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(AccessibilityModifiersRequired.Never)); return s_accessibilityModifiersRequiredMap.GetKeyOrDefault(AccessibilityModifiersRequired.Never)!; } Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(option.Value)); return $"{s_accessibilityModifiersRequiredMap.GetKeyOrDefault(option.Value)}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } private static readonly CodeStyleOption2<ParenthesesPreference> s_alwaysForClarityPreference = new(ParenthesesPreference.AlwaysForClarity, NotificationOption2.Silent); private static readonly CodeStyleOption2<ParenthesesPreference> s_neverIfUnnecessaryPreference = new(ParenthesesPreference.NeverIfUnnecessary, NotificationOption2.Silent); private static PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> CreateParenthesesOption( string fieldName, CodeStyleOption2<ParenthesesPreference> defaultValue, string styleName) { return CreateOption( CodeStyleOptionGroups.Parentheses, fieldName, defaultValue, storageLocations: new OptionStorageLocation2[]{ new EditorConfigStorageLocation<CodeStyleOption2<ParenthesesPreference>>( styleName, s => ParseParenthesesPreference(s, defaultValue), v => GetParenthesesPreferenceEditorConfigString(v, defaultValue)), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{fieldName}Preference")}); } internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> ArithmeticBinaryParentheses = CreateParenthesesOption( nameof(ArithmeticBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_arithmetic_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> OtherBinaryParentheses = CreateParenthesesOption( nameof(OtherBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_other_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> RelationalBinaryParentheses = CreateParenthesesOption( nameof(RelationalBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_relational_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> OtherParentheses = CreateParenthesesOption( nameof(OtherParentheses), s_neverIfUnnecessaryPreference, "dotnet_style_parentheses_in_other_operators"); private static readonly BidirectionalMap<string, ParenthesesPreference> s_parenthesesPreferenceMap = new(new[] { KeyValuePairUtil.Create("always_for_clarity", ParenthesesPreference.AlwaysForClarity), KeyValuePairUtil.Create("never_if_unnecessary", ParenthesesPreference.NeverIfUnnecessary), }); private static readonly BidirectionalMap<string, UnusedParametersPreference> s_unusedParametersPreferenceMap = new(new[] { KeyValuePairUtil.Create("non_public", UnusedParametersPreference.NonPublicMethods), KeyValuePairUtil.Create("all", UnusedParametersPreference.AllMethods), }); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSystemHashCode = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSystemHashCode), defaultValue: TrueWithSuggestionEnforcement, storageLocations: new OptionStorageLocation2[]{ new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferSystemHashCode") }); public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferNamespaceAndFolderMatchStructure = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNamespaceAndFolderMatchStructure), defaultValue: TrueWithSuggestionEnforcement, editorconfigKeyName: "dotnet_style_namespace_match_folder", roamingProfileStorageKeyName: $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferNamespaceAndFolderMatchStructure)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> AllowMultipleBlankLines = CreateOption( CodeStyleOptionGroups.NewLinePreferences, nameof(AllowMultipleBlankLines), defaultValue: TrueWithSilentEnforcement, "dotnet_style_allow_multiple_blank_lines_experimental", "TextEditor.%LANGUAGE%.Specific.AllowMultipleBlankLines"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> AllowStatementImmediatelyAfterBlock = CreateOption( CodeStyleOptionGroups.NewLinePreferences, nameof(AllowStatementImmediatelyAfterBlock), defaultValue: TrueWithSilentEnforcement, "dotnet_style_allow_statement_immediately_after_block_experimental", "TextEditor.%LANGUAGE%.Specific.AllowStatementImmediatelyAfterBlock"); static CodeStyleOptions2() { // Note that the static constructor executes after all the static field initializers for the options have executed, // and each field initializer adds the created option to s_allOptionsBuilder. AllOptions = s_allOptionsBuilder.ToImmutable(); } private static CodeStyleOption2<ParenthesesPreference> ParseParenthesesPreference( string optionString, CodeStyleOption2<ParenthesesPreference> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notification)) { Debug.Assert(s_parenthesesPreferenceMap.ContainsKey(value)); return new CodeStyleOption2<ParenthesesPreference>(s_parenthesesPreferenceMap.GetValueOrDefault(value), notification); } return defaultValue; } private static string GetParenthesesPreferenceEditorConfigString(CodeStyleOption2<ParenthesesPreference> option, CodeStyleOption2<ParenthesesPreference> defaultValue) { Debug.Assert(s_parenthesesPreferenceMap.ContainsValue(option.Value)); var value = s_parenthesesPreferenceMap.GetKeyOrDefault(option.Value) ?? s_parenthesesPreferenceMap.GetKeyOrDefault(ParenthesesPreference.AlwaysForClarity); return option.Notification == null ? value! : $"{value}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } private static CodeStyleOption2<UnusedParametersPreference> ParseUnusedParametersPreference(string optionString, CodeStyleOption2<UnusedParametersPreference> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notification)) { return new CodeStyleOption2<UnusedParametersPreference>(s_unusedParametersPreferenceMap.GetValueOrDefault(value), notification); } return defaultValue; } private static string GetUnusedParametersPreferenceEditorConfigString(CodeStyleOption2<UnusedParametersPreference> option, CodeStyleOption2<UnusedParametersPreference> defaultValue) { Debug.Assert(s_unusedParametersPreferenceMap.ContainsValue(option.Value)); var value = s_unusedParametersPreferenceMap.GetKeyOrDefault(option.Value) ?? s_unusedParametersPreferenceMap.GetKeyOrDefault(defaultValue.Value); return option.Notification == null ? value! : $"{value}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } } internal static class CodeStyleOptionGroups { public static readonly OptionGroup Usings = new(CompilerExtensionsResources.Organize_usings, priority: 1); public static readonly OptionGroup ThisOrMe = new(CompilerExtensionsResources.this_dot_and_Me_dot_preferences, priority: 2); public static readonly OptionGroup PredefinedTypeNameUsage = new(CompilerExtensionsResources.Language_keywords_vs_BCL_types_preferences, priority: 3); public static readonly OptionGroup Parentheses = new(CompilerExtensionsResources.Parentheses_preferences, priority: 4); public static readonly OptionGroup Modifier = new(CompilerExtensionsResources.Modifier_preferences, priority: 5); public static readonly OptionGroup ExpressionLevelPreferences = new(CompilerExtensionsResources.Expression_level_preferences, priority: 6); public static readonly OptionGroup Field = new(CompilerExtensionsResources.Field_preferences, priority: 7); public static readonly OptionGroup Parameter = new(CompilerExtensionsResources.Parameter_preferences, priority: 8); public static readonly OptionGroup Suppressions = new(CompilerExtensionsResources.Suppression_preferences, priority: 9); public static readonly OptionGroup NewLinePreferences = new(CompilerExtensionsResources.New_line_preferences, priority: 10); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Options; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeStyle.CodeStyleHelpers; namespace Microsoft.CodeAnalysis.CodeStyle { internal static class CodeStyleOptions2 { private static readonly ImmutableArray<IOption2>.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder<IOption2>(); internal static ImmutableArray<IOption2> AllOptions { get; } private static PerLanguageOption2<T> CreateOption<T>(OptionGroup group, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) { var option = new PerLanguageOption2<T>("CodeStyleOptions", group, name, defaultValue, storageLocations); s_allOptionsBuilder.Add(option); return option; } private static Option2<T> CreateCommonOption<T>(OptionGroup group, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) { var option = new Option2<T>("CodeStyleOptions", group, name, defaultValue, storageLocations); s_allOptionsBuilder.Add(option); return option; } private static PerLanguageOption2<CodeStyleOption2<bool>> CreateOption(OptionGroup group, string name, CodeStyleOption2<bool> defaultValue, string editorconfigKeyName, string roamingProfileStorageKeyName) => CreateOption(group, name, defaultValue, EditorConfigStorageLocation.ForBoolCodeStyleOption(editorconfigKeyName, defaultValue), new RoamingProfileStorageLocation(roamingProfileStorageKeyName)); /// <remarks> /// When user preferences are not yet set for a style, we fall back to the default value. /// One such default(s), is that the feature is turned on, so that codegen consumes it, /// but with silent enforcement, so that the user is not prompted about their usage. /// </remarks> internal static readonly CodeStyleOption2<bool> TrueWithSilentEnforcement = new(value: true, notification: NotificationOption2.Silent); internal static readonly CodeStyleOption2<bool> FalseWithSilentEnforcement = new(value: false, notification: NotificationOption2.Silent); internal static readonly CodeStyleOption2<bool> TrueWithSuggestionEnforcement = new(value: true, notification: NotificationOption2.Suggestion); internal static readonly CodeStyleOption2<bool> FalseWithSuggestionEnforcement = new(value: false, notification: NotificationOption2.Suggestion); private static PerLanguageOption2<CodeStyleOption2<bool>> CreateQualifyAccessOption(string optionName, string editorconfigKeyName) => CreateOption( CodeStyleOptionGroups.ThisOrMe, optionName, defaultValue: CodeStyleOption2<bool>.Default, editorconfigKeyName, $"TextEditor.%LANGUAGE%.Specific.{optionName}"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in field access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyFieldAccess = CreateQualifyAccessOption( nameof(QualifyFieldAccess), "dotnet_style_qualification_for_field"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in property access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyPropertyAccess = CreateQualifyAccessOption( nameof(QualifyPropertyAccess), "dotnet_style_qualification_for_property"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in method access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyMethodAccess = CreateQualifyAccessOption( nameof(QualifyMethodAccess), "dotnet_style_qualification_for_method"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in event access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyEventAccess = CreateQualifyAccessOption( nameof(QualifyEventAccess), "dotnet_style_qualification_for_event"); /// <summary> /// This option says if we should prefer keyword for Intrinsic Predefined Types in Declarations /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIntrinsicPredefinedTypeKeywordInDeclaration = CreateOption( CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInDeclaration), defaultValue: TrueWithSilentEnforcement, "dotnet_style_predefined_type_for_locals_parameters_members", "TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInDeclaration.CodeStyle"); /// <summary> /// This option says if we should prefer keyword for Intrinsic Predefined Types in Member Access Expression /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIntrinsicPredefinedTypeKeywordInMemberAccess = CreateOption( CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInMemberAccess), defaultValue: TrueWithSilentEnforcement, "dotnet_style_predefined_type_for_member_access", "TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInMemberAccess.CodeStyle"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferObjectInitializer = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferObjectInitializer), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_object_initializer", "TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCollectionInitializer = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCollectionInitializer), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_collection_initializer", "TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer"); // TODO: Should both the below "_FadeOutCode" options be added to AllOptions? internal static readonly PerLanguageOption2<bool> PreferObjectInitializer_FadeOutCode = new( "CodeStyleOptions", nameof(PreferObjectInitializer_FadeOutCode), defaultValue: false, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer_FadeOutCode")); internal static readonly PerLanguageOption2<bool> PreferCollectionInitializer_FadeOutCode = new( "CodeStyleOptions", nameof(PreferCollectionInitializer_FadeOutCode), defaultValue: false, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer_FadeOutCode")); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSimplifiedBooleanExpressions = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedBooleanExpressions), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_simplified_boolean_expressions", "TextEditor.%LANGUAGE%.Specific.PreferSimplifiedBooleanExpressions"); internal static readonly PerLanguageOption2<OperatorPlacementWhenWrappingPreference> OperatorPlacementWhenWrapping = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(OperatorPlacementWhenWrapping), defaultValue: OperatorPlacementWhenWrappingPreference.BeginningOfLine, storageLocations: new EditorConfigStorageLocation<OperatorPlacementWhenWrappingPreference>( "dotnet_style_operator_placement_when_wrapping", OperatorPlacementUtilities.Parse, OperatorPlacementUtilities.GetEditorConfigString)); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCoalesceExpression = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCoalesceExpression), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_coalesce_expression", "TextEditor.%LANGUAGE%.Specific.PreferCoalesceExpression"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferNullPropagation = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNullPropagation), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_null_propagation", "TextEditor.%LANGUAGE%.Specific.PreferNullPropagation"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferExplicitTupleNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferExplicitTupleNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_explicit_tuple_names", "TextEditor.%LANGUAGE%.Specific.PreferExplicitTupleNames"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferAutoProperties = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferAutoProperties), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_auto_properties", "TextEditor.%LANGUAGE%.Specific.PreferAutoProperties"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferInferredTupleNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredTupleNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_inferred_tuple_names", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredTupleNames)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferInferredAnonymousTypeMemberNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredAnonymousTypeMemberNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_inferred_anonymous_type_member_names", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredAnonymousTypeMemberNames)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIsNullCheckOverReferenceEqualityMethod = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferIsNullCheckOverReferenceEqualityMethod), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_is_null_check_over_reference_equality_method", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferIsNullCheckOverReferenceEqualityMethod)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferConditionalExpressionOverAssignment = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverAssignment), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_conditional_expression_over_assignment", "TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverAssignment"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferConditionalExpressionOverReturn = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverReturn), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_conditional_expression_over_return", "TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverReturn"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCompoundAssignment = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCompoundAssignment), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_compound_assignment", "TextEditor.%LANGUAGE%.Specific.PreferCompoundAssignment"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSimplifiedInterpolation = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedInterpolation), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_simplified_interpolation", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferSimplifiedInterpolation)}"); private static readonly CodeStyleOption2<UnusedParametersPreference> s_preferAllMethodsUnusedParametersPreference = new(UnusedParametersPreference.AllMethods, NotificationOption2.Suggestion); // TODO: https://github.com/dotnet/roslyn/issues/31225 tracks adding CodeQualityOption<T> and CodeQualityOptions // and moving this option to CodeQualityOptions. internal static readonly PerLanguageOption2<CodeStyleOption2<UnusedParametersPreference>> UnusedParameters = CreateOption( CodeStyleOptionGroups.Parameter, nameof(UnusedParameters), defaultValue: s_preferAllMethodsUnusedParametersPreference, storageLocations: new OptionStorageLocation2[]{ new EditorConfigStorageLocation<CodeStyleOption2<UnusedParametersPreference>>( "dotnet_code_quality_unused_parameters", s => ParseUnusedParametersPreference(s, s_preferAllMethodsUnusedParametersPreference), o => GetUnusedParametersPreferenceEditorConfigString(o, s_preferAllMethodsUnusedParametersPreference)), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(UnusedParameters)}Preference") }); private static readonly CodeStyleOption2<AccessibilityModifiersRequired> s_requireAccessibilityModifiersDefault = new(AccessibilityModifiersRequired.ForNonInterfaceMembers, NotificationOption2.Silent); internal static readonly PerLanguageOption2<CodeStyleOption2<AccessibilityModifiersRequired>> RequireAccessibilityModifiers = CreateOption( CodeStyleOptionGroups.Modifier, nameof(RequireAccessibilityModifiers), defaultValue: s_requireAccessibilityModifiersDefault, storageLocations: new OptionStorageLocation2[]{ new EditorConfigStorageLocation<CodeStyleOption2<AccessibilityModifiersRequired>>( "dotnet_style_require_accessibility_modifiers", s => ParseAccessibilityModifiersRequired(s, s_requireAccessibilityModifiersDefault), v => GetAccessibilityModifiersRequiredEditorConfigString(v, s_requireAccessibilityModifiersDefault)), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RequireAccessibilityModifiers")}); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferReadonly = CreateOption( CodeStyleOptionGroups.Field, nameof(PreferReadonly), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_readonly_field", "TextEditor.%LANGUAGE%.Specific.PreferReadonly"); internal static readonly Option2<string> FileHeaderTemplate = CreateCommonOption( CodeStyleOptionGroups.Usings, nameof(FileHeaderTemplate), defaultValue: "", EditorConfigStorageLocation.ForStringOption("file_header_template", emptyStringRepresentation: "unset")); internal static readonly Option2<string> RemoveUnnecessarySuppressionExclusions = CreateCommonOption( CodeStyleOptionGroups.Suppressions, nameof(RemoveUnnecessarySuppressionExclusions), defaultValue: "", storageLocations: new OptionStorageLocation2[]{ EditorConfigStorageLocation.ForStringOption("dotnet_remove_unnecessary_suppression_exclusions", emptyStringRepresentation: "none"), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RemoveUnnecessarySuppressionExclusions") }); private static readonly BidirectionalMap<string, AccessibilityModifiersRequired> s_accessibilityModifiersRequiredMap = new(new[] { KeyValuePairUtil.Create("never", AccessibilityModifiersRequired.Never), KeyValuePairUtil.Create("always", AccessibilityModifiersRequired.Always), KeyValuePairUtil.Create("for_non_interface_members", AccessibilityModifiersRequired.ForNonInterfaceMembers), KeyValuePairUtil.Create("omit_if_default", AccessibilityModifiersRequired.OmitIfDefault), }); private static CodeStyleOption2<AccessibilityModifiersRequired> ParseAccessibilityModifiersRequired(string optionString, CodeStyleOption2<AccessibilityModifiersRequired> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notificationOpt)) { Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsKey(value)); return new CodeStyleOption2<AccessibilityModifiersRequired>(s_accessibilityModifiersRequiredMap.GetValueOrDefault(value), notificationOpt); } return s_requireAccessibilityModifiersDefault; } private static string GetAccessibilityModifiersRequiredEditorConfigString(CodeStyleOption2<AccessibilityModifiersRequired> option, CodeStyleOption2<AccessibilityModifiersRequired> defaultValue) { // If they provide 'never', they don't need a notification level. if (option.Notification == null) { Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(AccessibilityModifiersRequired.Never)); return s_accessibilityModifiersRequiredMap.GetKeyOrDefault(AccessibilityModifiersRequired.Never)!; } Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(option.Value)); return $"{s_accessibilityModifiersRequiredMap.GetKeyOrDefault(option.Value)}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } private static readonly CodeStyleOption2<ParenthesesPreference> s_alwaysForClarityPreference = new(ParenthesesPreference.AlwaysForClarity, NotificationOption2.Silent); private static readonly CodeStyleOption2<ParenthesesPreference> s_neverIfUnnecessaryPreference = new(ParenthesesPreference.NeverIfUnnecessary, NotificationOption2.Silent); private static PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> CreateParenthesesOption( string fieldName, CodeStyleOption2<ParenthesesPreference> defaultValue, string styleName) { return CreateOption( CodeStyleOptionGroups.Parentheses, fieldName, defaultValue, storageLocations: new OptionStorageLocation2[]{ new EditorConfigStorageLocation<CodeStyleOption2<ParenthesesPreference>>( styleName, s => ParseParenthesesPreference(s, defaultValue), v => GetParenthesesPreferenceEditorConfigString(v, defaultValue)), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{fieldName}Preference")}); } internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> ArithmeticBinaryParentheses = CreateParenthesesOption( nameof(ArithmeticBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_arithmetic_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> OtherBinaryParentheses = CreateParenthesesOption( nameof(OtherBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_other_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> RelationalBinaryParentheses = CreateParenthesesOption( nameof(RelationalBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_relational_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> OtherParentheses = CreateParenthesesOption( nameof(OtherParentheses), s_neverIfUnnecessaryPreference, "dotnet_style_parentheses_in_other_operators"); private static readonly BidirectionalMap<string, ParenthesesPreference> s_parenthesesPreferenceMap = new(new[] { KeyValuePairUtil.Create("always_for_clarity", ParenthesesPreference.AlwaysForClarity), KeyValuePairUtil.Create("never_if_unnecessary", ParenthesesPreference.NeverIfUnnecessary), }); private static readonly BidirectionalMap<string, UnusedParametersPreference> s_unusedParametersPreferenceMap = new(new[] { KeyValuePairUtil.Create("non_public", UnusedParametersPreference.NonPublicMethods), KeyValuePairUtil.Create("all", UnusedParametersPreference.AllMethods), }); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSystemHashCode = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSystemHashCode), defaultValue: TrueWithSuggestionEnforcement, storageLocations: new OptionStorageLocation2[]{ new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferSystemHashCode") }); public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferNamespaceAndFolderMatchStructure = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNamespaceAndFolderMatchStructure), defaultValue: TrueWithSuggestionEnforcement, editorconfigKeyName: "dotnet_style_namespace_match_folder", roamingProfileStorageKeyName: $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferNamespaceAndFolderMatchStructure)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> AllowMultipleBlankLines = CreateOption( CodeStyleOptionGroups.NewLinePreferences, nameof(AllowMultipleBlankLines), defaultValue: TrueWithSilentEnforcement, "dotnet_style_allow_multiple_blank_lines_experimental", "TextEditor.%LANGUAGE%.Specific.AllowMultipleBlankLines"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> AllowStatementImmediatelyAfterBlock = CreateOption( CodeStyleOptionGroups.NewLinePreferences, nameof(AllowStatementImmediatelyAfterBlock), defaultValue: TrueWithSilentEnforcement, "dotnet_style_allow_statement_immediately_after_block_experimental", "TextEditor.%LANGUAGE%.Specific.AllowStatementImmediatelyAfterBlock"); static CodeStyleOptions2() { // Note that the static constructor executes after all the static field initializers for the options have executed, // and each field initializer adds the created option to s_allOptionsBuilder. AllOptions = s_allOptionsBuilder.ToImmutable(); } private static CodeStyleOption2<ParenthesesPreference> ParseParenthesesPreference( string optionString, CodeStyleOption2<ParenthesesPreference> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notification)) { Debug.Assert(s_parenthesesPreferenceMap.ContainsKey(value)); return new CodeStyleOption2<ParenthesesPreference>(s_parenthesesPreferenceMap.GetValueOrDefault(value), notification); } return defaultValue; } private static string GetParenthesesPreferenceEditorConfigString(CodeStyleOption2<ParenthesesPreference> option, CodeStyleOption2<ParenthesesPreference> defaultValue) { Debug.Assert(s_parenthesesPreferenceMap.ContainsValue(option.Value)); var value = s_parenthesesPreferenceMap.GetKeyOrDefault(option.Value) ?? s_parenthesesPreferenceMap.GetKeyOrDefault(ParenthesesPreference.AlwaysForClarity); return option.Notification == null ? value! : $"{value}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } private static CodeStyleOption2<UnusedParametersPreference> ParseUnusedParametersPreference(string optionString, CodeStyleOption2<UnusedParametersPreference> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notification)) { return new CodeStyleOption2<UnusedParametersPreference>(s_unusedParametersPreferenceMap.GetValueOrDefault(value), notification); } return defaultValue; } private static string GetUnusedParametersPreferenceEditorConfigString(CodeStyleOption2<UnusedParametersPreference> option, CodeStyleOption2<UnusedParametersPreference> defaultValue) { Debug.Assert(s_unusedParametersPreferenceMap.ContainsValue(option.Value)); var value = s_unusedParametersPreferenceMap.GetKeyOrDefault(option.Value) ?? s_unusedParametersPreferenceMap.GetKeyOrDefault(defaultValue.Value); return option.Notification == null ? value! : $"{value}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } } internal static class CodeStyleOptionGroups { public static readonly OptionGroup Usings = new(CompilerExtensionsResources.Organize_usings, priority: 1); public static readonly OptionGroup ThisOrMe = new(CompilerExtensionsResources.this_dot_and_Me_dot_preferences, priority: 2); public static readonly OptionGroup PredefinedTypeNameUsage = new(CompilerExtensionsResources.Language_keywords_vs_BCL_types_preferences, priority: 3); public static readonly OptionGroup Parentheses = new(CompilerExtensionsResources.Parentheses_preferences, priority: 4); public static readonly OptionGroup Modifier = new(CompilerExtensionsResources.Modifier_preferences, priority: 5); public static readonly OptionGroup ExpressionLevelPreferences = new(CompilerExtensionsResources.Expression_level_preferences, priority: 6); public static readonly OptionGroup Field = new(CompilerExtensionsResources.Field_preferences, priority: 7); public static readonly OptionGroup Parameter = new(CompilerExtensionsResources.Parameter_preferences, priority: 8); public static readonly OptionGroup Suppressions = new(CompilerExtensionsResources.Suppression_preferences, priority: 9); public static readonly OptionGroup NewLinePreferences = new(CompilerExtensionsResources.New_line_preferences, priority: 10); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Syntax/InternalSyntax/SyntaxFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { using Microsoft.CodeAnalysis.Syntax.InternalSyntax; internal static partial class SyntaxFactory { private const string CrLf = "\r\n"; internal static readonly SyntaxTrivia CarriageReturnLineFeed = EndOfLine(CrLf); internal static readonly SyntaxTrivia LineFeed = EndOfLine("\n"); internal static readonly SyntaxTrivia CarriageReturn = EndOfLine("\r"); internal static readonly SyntaxTrivia Space = Whitespace(" "); internal static readonly SyntaxTrivia Tab = Whitespace("\t"); internal static readonly SyntaxTrivia ElasticCarriageReturnLineFeed = EndOfLine(CrLf, elastic: true); internal static readonly SyntaxTrivia ElasticLineFeed = EndOfLine("\n", elastic: true); internal static readonly SyntaxTrivia ElasticCarriageReturn = EndOfLine("\r", elastic: true); internal static readonly SyntaxTrivia ElasticSpace = Whitespace(" ", elastic: true); internal static readonly SyntaxTrivia ElasticTab = Whitespace("\t", elastic: true); internal static readonly SyntaxTrivia ElasticZeroSpace = Whitespace(string.Empty, elastic: true); private static SyntaxToken s_xmlCarriageReturnLineFeed; private static SyntaxToken XmlCarriageReturnLineFeed { get { return s_xmlCarriageReturnLineFeed ?? (s_xmlCarriageReturnLineFeed = XmlTextNewLine(CrLf)); } } // NOTE: it would be nice to have constants for OmittedArraySizeException and OmittedTypeArgument, // but it's non-trivial to introduce such constants, since they would make this class take a dependency // on the static fields of SyntaxToken (specifically, TokensWithNoTrivia via SyntaxToken.Create). That // could cause unpredictable behavior, since SyntaxToken's static constructor already depends on the // static fields of this class (specifically, ElasticZeroSpace). internal static SyntaxTrivia EndOfLine(string text, bool elastic = false) { SyntaxTrivia trivia = null; // use predefined trivia switch (text) { case "\r": trivia = elastic ? SyntaxFactory.ElasticCarriageReturn : SyntaxFactory.CarriageReturn; break; case "\n": trivia = elastic ? SyntaxFactory.ElasticLineFeed : SyntaxFactory.LineFeed; break; case "\r\n": trivia = elastic ? SyntaxFactory.ElasticCarriageReturnLineFeed : SyntaxFactory.CarriageReturnLineFeed; break; } // note: predefined trivia might not yet be defined during initialization if (trivia != null) { return trivia; } trivia = SyntaxTrivia.Create(SyntaxKind.EndOfLineTrivia, text); if (!elastic) { return trivia; } return trivia.WithAnnotationsGreen(new[] { SyntaxAnnotation.ElasticAnnotation }); } internal static SyntaxTrivia Whitespace(string text, bool elastic = false) { var trivia = SyntaxTrivia.Create(SyntaxKind.WhitespaceTrivia, text); if (!elastic) { return trivia; } return trivia.WithAnnotationsGreen(new[] { SyntaxAnnotation.ElasticAnnotation }); } internal static SyntaxTrivia Comment(string text) { if (text.StartsWith("/*", StringComparison.Ordinal)) { return SyntaxTrivia.Create(SyntaxKind.MultiLineCommentTrivia, text); } else { return SyntaxTrivia.Create(SyntaxKind.SingleLineCommentTrivia, text); } } internal static SyntaxTrivia ConflictMarker(string text) => SyntaxTrivia.Create(SyntaxKind.ConflictMarkerTrivia, text); internal static SyntaxTrivia DisabledText(string text) { return SyntaxTrivia.Create(SyntaxKind.DisabledTextTrivia, text); } internal static SyntaxTrivia PreprocessingMessage(string text) { return SyntaxTrivia.Create(SyntaxKind.PreprocessingMessageTrivia, text); } public static SyntaxToken Token(SyntaxKind kind) { return SyntaxToken.Create(kind); } internal static SyntaxToken Token(GreenNode leading, SyntaxKind kind, GreenNode trailing) { return SyntaxToken.Create(kind, leading, trailing); } internal static SyntaxToken Token(GreenNode leading, SyntaxKind kind, string text, string valueText, GreenNode trailing) { Debug.Assert(SyntaxFacts.IsAnyToken(kind)); Debug.Assert(kind != SyntaxKind.IdentifierToken); Debug.Assert(kind != SyntaxKind.CharacterLiteralToken); Debug.Assert(kind != SyntaxKind.NumericLiteralToken); string defaultText = SyntaxFacts.GetText(kind); return kind >= SyntaxToken.FirstTokenWithWellKnownText && kind <= SyntaxToken.LastTokenWithWellKnownText && text == defaultText && valueText == defaultText ? Token(leading, kind, trailing) : SyntaxToken.WithValue(kind, leading, text, valueText, trailing); } internal static SyntaxToken MissingToken(SyntaxKind kind) { return SyntaxToken.CreateMissing(kind, null, null); } internal static SyntaxToken MissingToken(GreenNode leading, SyntaxKind kind, GreenNode trailing) { return SyntaxToken.CreateMissing(kind, leading, trailing); } internal static SyntaxToken Identifier(string text) { return Identifier(SyntaxKind.IdentifierToken, null, text, text, null); } internal static SyntaxToken Identifier(GreenNode leading, string text, GreenNode trailing) { return Identifier(SyntaxKind.IdentifierToken, leading, text, text, trailing); } internal static SyntaxToken Identifier(SyntaxKind contextualKind, GreenNode leading, string text, string valueText, GreenNode trailing) { return SyntaxToken.Identifier(contextualKind, leading, text, valueText, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, int value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, uint value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, long value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, ulong value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, float value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, double value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, decimal value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, string value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.StringLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, SyntaxKind kind, string value, GreenNode trailing) { return SyntaxToken.WithValue(kind, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, char value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.CharacterLiteralToken, leading, text, value, trailing); } internal static SyntaxToken BadToken(GreenNode leading, string text, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.BadToken, leading, text, text, trailing); } internal static SyntaxToken XmlTextLiteral(GreenNode leading, string text, string value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.XmlTextLiteralToken, leading, text, value, trailing); } internal static SyntaxToken XmlTextNewLine(GreenNode leading, string text, string value, GreenNode trailing) { if (leading == null && trailing == null && text == CrLf && value == CrLf) { return XmlCarriageReturnLineFeed; } return SyntaxToken.WithValue(SyntaxKind.XmlTextLiteralNewLineToken, leading, text, value, trailing); } internal static SyntaxToken XmlTextNewLine(string text) { return SyntaxToken.WithValue(SyntaxKind.XmlTextLiteralNewLineToken, null, text, text, null); } internal static SyntaxToken XmlEntity(GreenNode leading, string text, string value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.XmlEntityLiteralToken, leading, text, value, trailing); } internal static SyntaxTrivia DocumentationCommentExteriorTrivia(string text) { return SyntaxTrivia.Create(SyntaxKind.DocumentationCommentExteriorTrivia, text); } public static SyntaxList<TNode> List<TNode>() where TNode : CSharpSyntaxNode { return default(SyntaxList<TNode>); } public static SyntaxList<TNode> List<TNode>(TNode node) where TNode : CSharpSyntaxNode { return new SyntaxList<TNode>(SyntaxList.List(node)); } public static SyntaxList<TNode> List<TNode>(TNode node0, TNode node1) where TNode : CSharpSyntaxNode { return new SyntaxList<TNode>(SyntaxList.List(node0, node1)); } internal static GreenNode ListNode(CSharpSyntaxNode node0, CSharpSyntaxNode node1) { return SyntaxList.List(node0, node1); } public static SyntaxList<TNode> List<TNode>(TNode node0, TNode node1, TNode node2) where TNode : CSharpSyntaxNode { return new SyntaxList<TNode>(SyntaxList.List(node0, node1, node2)); } internal static GreenNode ListNode(CSharpSyntaxNode node0, CSharpSyntaxNode node1, CSharpSyntaxNode node2) { return SyntaxList.List(node0, node1, node2); } public static SyntaxList<TNode> List<TNode>(params TNode[] nodes) where TNode : CSharpSyntaxNode { if (nodes != null) { return new SyntaxList<TNode>(SyntaxList.List(nodes)); } return default(SyntaxList<TNode>); } internal static GreenNode ListNode(params ArrayElement<GreenNode>[] nodes) { return SyntaxList.List(nodes); } public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(TNode node) where TNode : CSharpSyntaxNode { return new SeparatedSyntaxList<TNode>(new SyntaxList<CSharpSyntaxNode>(node)); } public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(SyntaxToken token) where TNode : CSharpSyntaxNode { return new SeparatedSyntaxList<TNode>(new SyntaxList<CSharpSyntaxNode>(token)); } public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(TNode node1, SyntaxToken token, TNode node2) where TNode : CSharpSyntaxNode { return new SeparatedSyntaxList<TNode>(new SyntaxList<CSharpSyntaxNode>(SyntaxList.List(node1, token, node2))); } public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(params CSharpSyntaxNode[] nodes) where TNode : CSharpSyntaxNode { if (nodes != null) { return new SeparatedSyntaxList<TNode>(SyntaxList.List(nodes)); } return default(SeparatedSyntaxList<TNode>); } internal static IEnumerable<SyntaxTrivia> GetWellKnownTrivia() { yield return CarriageReturnLineFeed; yield return LineFeed; yield return CarriageReturn; yield return Space; yield return Tab; yield return ElasticCarriageReturnLineFeed; yield return ElasticLineFeed; yield return ElasticCarriageReturn; yield return ElasticSpace; yield return ElasticTab; yield return ElasticZeroSpace; } internal static IEnumerable<SyntaxToken> GetWellKnownTokens() { return SyntaxToken.GetWellKnownTokens(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { using Microsoft.CodeAnalysis.Syntax.InternalSyntax; internal static partial class SyntaxFactory { private const string CrLf = "\r\n"; internal static readonly SyntaxTrivia CarriageReturnLineFeed = EndOfLine(CrLf); internal static readonly SyntaxTrivia LineFeed = EndOfLine("\n"); internal static readonly SyntaxTrivia CarriageReturn = EndOfLine("\r"); internal static readonly SyntaxTrivia Space = Whitespace(" "); internal static readonly SyntaxTrivia Tab = Whitespace("\t"); internal static readonly SyntaxTrivia ElasticCarriageReturnLineFeed = EndOfLine(CrLf, elastic: true); internal static readonly SyntaxTrivia ElasticLineFeed = EndOfLine("\n", elastic: true); internal static readonly SyntaxTrivia ElasticCarriageReturn = EndOfLine("\r", elastic: true); internal static readonly SyntaxTrivia ElasticSpace = Whitespace(" ", elastic: true); internal static readonly SyntaxTrivia ElasticTab = Whitespace("\t", elastic: true); internal static readonly SyntaxTrivia ElasticZeroSpace = Whitespace(string.Empty, elastic: true); private static SyntaxToken s_xmlCarriageReturnLineFeed; private static SyntaxToken XmlCarriageReturnLineFeed { get { return s_xmlCarriageReturnLineFeed ?? (s_xmlCarriageReturnLineFeed = XmlTextNewLine(CrLf)); } } // NOTE: it would be nice to have constants for OmittedArraySizeException and OmittedTypeArgument, // but it's non-trivial to introduce such constants, since they would make this class take a dependency // on the static fields of SyntaxToken (specifically, TokensWithNoTrivia via SyntaxToken.Create). That // could cause unpredictable behavior, since SyntaxToken's static constructor already depends on the // static fields of this class (specifically, ElasticZeroSpace). internal static SyntaxTrivia EndOfLine(string text, bool elastic = false) { SyntaxTrivia trivia = null; // use predefined trivia switch (text) { case "\r": trivia = elastic ? SyntaxFactory.ElasticCarriageReturn : SyntaxFactory.CarriageReturn; break; case "\n": trivia = elastic ? SyntaxFactory.ElasticLineFeed : SyntaxFactory.LineFeed; break; case "\r\n": trivia = elastic ? SyntaxFactory.ElasticCarriageReturnLineFeed : SyntaxFactory.CarriageReturnLineFeed; break; } // note: predefined trivia might not yet be defined during initialization if (trivia != null) { return trivia; } trivia = SyntaxTrivia.Create(SyntaxKind.EndOfLineTrivia, text); if (!elastic) { return trivia; } return trivia.WithAnnotationsGreen(new[] { SyntaxAnnotation.ElasticAnnotation }); } internal static SyntaxTrivia Whitespace(string text, bool elastic = false) { var trivia = SyntaxTrivia.Create(SyntaxKind.WhitespaceTrivia, text); if (!elastic) { return trivia; } return trivia.WithAnnotationsGreen(new[] { SyntaxAnnotation.ElasticAnnotation }); } internal static SyntaxTrivia Comment(string text) { if (text.StartsWith("/*", StringComparison.Ordinal)) { return SyntaxTrivia.Create(SyntaxKind.MultiLineCommentTrivia, text); } else { return SyntaxTrivia.Create(SyntaxKind.SingleLineCommentTrivia, text); } } internal static SyntaxTrivia ConflictMarker(string text) => SyntaxTrivia.Create(SyntaxKind.ConflictMarkerTrivia, text); internal static SyntaxTrivia DisabledText(string text) { return SyntaxTrivia.Create(SyntaxKind.DisabledTextTrivia, text); } internal static SyntaxTrivia PreprocessingMessage(string text) { return SyntaxTrivia.Create(SyntaxKind.PreprocessingMessageTrivia, text); } public static SyntaxToken Token(SyntaxKind kind) { return SyntaxToken.Create(kind); } internal static SyntaxToken Token(GreenNode leading, SyntaxKind kind, GreenNode trailing) { return SyntaxToken.Create(kind, leading, trailing); } internal static SyntaxToken Token(GreenNode leading, SyntaxKind kind, string text, string valueText, GreenNode trailing) { Debug.Assert(SyntaxFacts.IsAnyToken(kind)); Debug.Assert(kind != SyntaxKind.IdentifierToken); Debug.Assert(kind != SyntaxKind.CharacterLiteralToken); Debug.Assert(kind != SyntaxKind.NumericLiteralToken); string defaultText = SyntaxFacts.GetText(kind); return kind >= SyntaxToken.FirstTokenWithWellKnownText && kind <= SyntaxToken.LastTokenWithWellKnownText && text == defaultText && valueText == defaultText ? Token(leading, kind, trailing) : SyntaxToken.WithValue(kind, leading, text, valueText, trailing); } internal static SyntaxToken MissingToken(SyntaxKind kind) { return SyntaxToken.CreateMissing(kind, null, null); } internal static SyntaxToken MissingToken(GreenNode leading, SyntaxKind kind, GreenNode trailing) { return SyntaxToken.CreateMissing(kind, leading, trailing); } internal static SyntaxToken Identifier(string text) { return Identifier(SyntaxKind.IdentifierToken, null, text, text, null); } internal static SyntaxToken Identifier(GreenNode leading, string text, GreenNode trailing) { return Identifier(SyntaxKind.IdentifierToken, leading, text, text, trailing); } internal static SyntaxToken Identifier(SyntaxKind contextualKind, GreenNode leading, string text, string valueText, GreenNode trailing) { return SyntaxToken.Identifier(contextualKind, leading, text, valueText, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, int value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, uint value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, long value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, ulong value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, float value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, double value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, decimal value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.NumericLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, string value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.StringLiteralToken, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, SyntaxKind kind, string value, GreenNode trailing) { return SyntaxToken.WithValue(kind, leading, text, value, trailing); } internal static SyntaxToken Literal(GreenNode leading, string text, char value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.CharacterLiteralToken, leading, text, value, trailing); } internal static SyntaxToken BadToken(GreenNode leading, string text, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.BadToken, leading, text, text, trailing); } internal static SyntaxToken XmlTextLiteral(GreenNode leading, string text, string value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.XmlTextLiteralToken, leading, text, value, trailing); } internal static SyntaxToken XmlTextNewLine(GreenNode leading, string text, string value, GreenNode trailing) { if (leading == null && trailing == null && text == CrLf && value == CrLf) { return XmlCarriageReturnLineFeed; } return SyntaxToken.WithValue(SyntaxKind.XmlTextLiteralNewLineToken, leading, text, value, trailing); } internal static SyntaxToken XmlTextNewLine(string text) { return SyntaxToken.WithValue(SyntaxKind.XmlTextLiteralNewLineToken, null, text, text, null); } internal static SyntaxToken XmlEntity(GreenNode leading, string text, string value, GreenNode trailing) { return SyntaxToken.WithValue(SyntaxKind.XmlEntityLiteralToken, leading, text, value, trailing); } internal static SyntaxTrivia DocumentationCommentExteriorTrivia(string text) { return SyntaxTrivia.Create(SyntaxKind.DocumentationCommentExteriorTrivia, text); } public static SyntaxList<TNode> List<TNode>() where TNode : CSharpSyntaxNode { return default(SyntaxList<TNode>); } public static SyntaxList<TNode> List<TNode>(TNode node) where TNode : CSharpSyntaxNode { return new SyntaxList<TNode>(SyntaxList.List(node)); } public static SyntaxList<TNode> List<TNode>(TNode node0, TNode node1) where TNode : CSharpSyntaxNode { return new SyntaxList<TNode>(SyntaxList.List(node0, node1)); } internal static GreenNode ListNode(CSharpSyntaxNode node0, CSharpSyntaxNode node1) { return SyntaxList.List(node0, node1); } public static SyntaxList<TNode> List<TNode>(TNode node0, TNode node1, TNode node2) where TNode : CSharpSyntaxNode { return new SyntaxList<TNode>(SyntaxList.List(node0, node1, node2)); } internal static GreenNode ListNode(CSharpSyntaxNode node0, CSharpSyntaxNode node1, CSharpSyntaxNode node2) { return SyntaxList.List(node0, node1, node2); } public static SyntaxList<TNode> List<TNode>(params TNode[] nodes) where TNode : CSharpSyntaxNode { if (nodes != null) { return new SyntaxList<TNode>(SyntaxList.List(nodes)); } return default(SyntaxList<TNode>); } internal static GreenNode ListNode(params ArrayElement<GreenNode>[] nodes) { return SyntaxList.List(nodes); } public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(TNode node) where TNode : CSharpSyntaxNode { return new SeparatedSyntaxList<TNode>(new SyntaxList<CSharpSyntaxNode>(node)); } public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(SyntaxToken token) where TNode : CSharpSyntaxNode { return new SeparatedSyntaxList<TNode>(new SyntaxList<CSharpSyntaxNode>(token)); } public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(TNode node1, SyntaxToken token, TNode node2) where TNode : CSharpSyntaxNode { return new SeparatedSyntaxList<TNode>(new SyntaxList<CSharpSyntaxNode>(SyntaxList.List(node1, token, node2))); } public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(params CSharpSyntaxNode[] nodes) where TNode : CSharpSyntaxNode { if (nodes != null) { return new SeparatedSyntaxList<TNode>(SyntaxList.List(nodes)); } return default(SeparatedSyntaxList<TNode>); } internal static IEnumerable<SyntaxTrivia> GetWellKnownTrivia() { yield return CarriageReturnLineFeed; yield return LineFeed; yield return CarriageReturn; yield return Space; yield return Tab; yield return ElasticCarriageReturnLineFeed; yield return ElasticLineFeed; yield return ElasticCarriageReturn; yield return ElasticSpace; yield return ElasticTab; yield return ElasticZeroSpace; } internal static IEnumerable<SyntaxToken> GetWellKnownTokens() { return SyntaxToken.GetWellKnownTokens(); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActionsSourceProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tags; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { [Export(typeof(ISuggestedActionsSourceProvider))] [Export(typeof(SuggestedActionsSourceProvider))] [VisualStudio.Utilities.ContentType(ContentTypeNames.RoslynContentType)] [VisualStudio.Utilities.ContentType(ContentTypeNames.XamlContentType)] [VisualStudio.Utilities.Name("Roslyn Code Fix")] [VisualStudio.Utilities.Order] internal partial class SuggestedActionsSourceProvider : ISuggestedActionsSourceProvider { private static readonly Guid s_CSharpSourceGuid = new Guid("b967fea8-e2c3-4984-87d4-71a38f49e16a"); private static readonly Guid s_visualBasicSourceGuid = new Guid("4de30e93-3e0c-40c2-a4ba-1124da4539f6"); private static readonly Guid s_xamlSourceGuid = new Guid("a0572245-2eab-4c39-9f61-06a6d8c5ddda"); private const int InvalidSolutionVersion = -1; private readonly IThreadingContext _threadingContext; private readonly ICodeRefactoringService _codeRefactoringService; private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly ICodeFixService _codeFixService; private readonly ISuggestedActionCategoryRegistryService _suggestedActionCategoryRegistry; public readonly ICodeActionEditHandlerService EditHandler; public readonly IAsynchronousOperationListener OperationListener; public readonly IUIThreadOperationExecutor UIThreadOperationExecutor; public readonly ImmutableArray<Lazy<ISuggestedActionCallback>> ActionCallbacks; public readonly ImmutableArray<Lazy<IImageIdService, OrderableMetadata>> ImageIdServices; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SuggestedActionsSourceProvider( IThreadingContext threadingContext, ICodeRefactoringService codeRefactoringService, IDiagnosticAnalyzerService diagnosticService, ICodeFixService codeFixService, ICodeActionEditHandlerService editHandler, IUIThreadOperationExecutor uiThreadOperationExecutor, ISuggestedActionCategoryRegistryService suggestedActionCategoryRegistry, IAsynchronousOperationListenerProvider listenerProvider, [ImportMany] IEnumerable<Lazy<IImageIdService, OrderableMetadata>> imageIdServices, [ImportMany] IEnumerable<Lazy<ISuggestedActionCallback>> actionCallbacks) { _threadingContext = threadingContext; _codeRefactoringService = codeRefactoringService; _diagnosticService = diagnosticService; _codeFixService = codeFixService; _suggestedActionCategoryRegistry = suggestedActionCategoryRegistry; ActionCallbacks = actionCallbacks.ToImmutableArray(); EditHandler = editHandler; UIThreadOperationExecutor = uiThreadOperationExecutor; OperationListener = listenerProvider.GetListener(FeatureAttribute.LightBulb); ImageIdServices = ExtensionOrderer.Order(imageIdServices).ToImmutableArray(); } public ISuggestedActionsSource? CreateSuggestedActionsSource(ITextView textView, ITextBuffer textBuffer) { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(textBuffer); // Disable lightbulb points when running under the LSP editor. // The LSP client will interface with the editor to display our code actions. if (textBuffer.IsInLspEditorContext()) { return null; } return new SuggestedActionsSource(_threadingContext, this, textView, textBuffer, _suggestedActionCategoryRegistry); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tags; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { [Export(typeof(ISuggestedActionsSourceProvider))] [Export(typeof(SuggestedActionsSourceProvider))] [VisualStudio.Utilities.ContentType(ContentTypeNames.RoslynContentType)] [VisualStudio.Utilities.ContentType(ContentTypeNames.XamlContentType)] [VisualStudio.Utilities.Name("Roslyn Code Fix")] [VisualStudio.Utilities.Order] internal partial class SuggestedActionsSourceProvider : ISuggestedActionsSourceProvider { private static readonly Guid s_CSharpSourceGuid = new Guid("b967fea8-e2c3-4984-87d4-71a38f49e16a"); private static readonly Guid s_visualBasicSourceGuid = new Guid("4de30e93-3e0c-40c2-a4ba-1124da4539f6"); private static readonly Guid s_xamlSourceGuid = new Guid("a0572245-2eab-4c39-9f61-06a6d8c5ddda"); private const int InvalidSolutionVersion = -1; private readonly IThreadingContext _threadingContext; private readonly ICodeRefactoringService _codeRefactoringService; private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly ICodeFixService _codeFixService; private readonly ISuggestedActionCategoryRegistryService _suggestedActionCategoryRegistry; public readonly ICodeActionEditHandlerService EditHandler; public readonly IAsynchronousOperationListener OperationListener; public readonly IUIThreadOperationExecutor UIThreadOperationExecutor; public readonly ImmutableArray<Lazy<ISuggestedActionCallback>> ActionCallbacks; public readonly ImmutableArray<Lazy<IImageIdService, OrderableMetadata>> ImageIdServices; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SuggestedActionsSourceProvider( IThreadingContext threadingContext, ICodeRefactoringService codeRefactoringService, IDiagnosticAnalyzerService diagnosticService, ICodeFixService codeFixService, ICodeActionEditHandlerService editHandler, IUIThreadOperationExecutor uiThreadOperationExecutor, ISuggestedActionCategoryRegistryService suggestedActionCategoryRegistry, IAsynchronousOperationListenerProvider listenerProvider, [ImportMany] IEnumerable<Lazy<IImageIdService, OrderableMetadata>> imageIdServices, [ImportMany] IEnumerable<Lazy<ISuggestedActionCallback>> actionCallbacks) { _threadingContext = threadingContext; _codeRefactoringService = codeRefactoringService; _diagnosticService = diagnosticService; _codeFixService = codeFixService; _suggestedActionCategoryRegistry = suggestedActionCategoryRegistry; ActionCallbacks = actionCallbacks.ToImmutableArray(); EditHandler = editHandler; UIThreadOperationExecutor = uiThreadOperationExecutor; OperationListener = listenerProvider.GetListener(FeatureAttribute.LightBulb); ImageIdServices = ExtensionOrderer.Order(imageIdServices).ToImmutableArray(); } public ISuggestedActionsSource? CreateSuggestedActionsSource(ITextView textView, ITextBuffer textBuffer) { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(textBuffer); // Disable lightbulb points when running under the LSP editor. // The LSP client will interface with the editor to display our code actions. if (textBuffer.IsInLspEditorContext()) { return null; } return new SuggestedActionsSource(_threadingContext, this, textView, textBuffer, _suggestedActionCategoryRegistry); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/CodeStyle/Core/Analyzers/Options/AnalyzerHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Diagnostics { internal static partial class AnalyzerHelper { #pragma warning disable IDE0060 // Remove unused parameter - Needed to share this method signature between CodeStyle and Features layer. public static T GetOption<T>(this AnalyzerOptions analyzerOptions, IOption2 option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken) #pragma warning restore IDE0060 // Remove unused parameter { if (analyzerOptions.TryGetEditorConfigOption<T>(option, syntaxTree, out var value)) { return value; } return (T)option.DefaultValue!; } public static T GetOption<T>(this AnalyzerOptions analyzerOptions, Option2<T> option, SyntaxTree syntaxTree, CancellationToken cancellationToken) => GetOption<T>(analyzerOptions, option, language: null, syntaxTree, cancellationToken); public static T GetOption<T>(this AnalyzerOptions analyzerOptions, PerLanguageOption2<T> option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken) => GetOption<T>(analyzerOptions, (IOption2)option, language, syntaxTree, cancellationToken); #pragma warning disable IDE0060 // Remove unused parameter - Needed to share this method signature between CodeStyle and Features layer. public static AnalyzerConfigOptions GetAnalyzerOptionSet(this AnalyzerOptions analyzerOptions, SyntaxTree syntaxTree, CancellationToken cancellationToken) #pragma warning restore IDE0060 // Remove unused parameter => analyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Diagnostics { internal static partial class AnalyzerHelper { #pragma warning disable IDE0060 // Remove unused parameter - Needed to share this method signature between CodeStyle and Features layer. public static T GetOption<T>(this AnalyzerOptions analyzerOptions, IOption2 option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken) #pragma warning restore IDE0060 // Remove unused parameter { if (analyzerOptions.TryGetEditorConfigOption<T>(option, syntaxTree, out var value)) { return value; } return (T)option.DefaultValue!; } public static T GetOption<T>(this AnalyzerOptions analyzerOptions, Option2<T> option, SyntaxTree syntaxTree, CancellationToken cancellationToken) => GetOption<T>(analyzerOptions, option, language: null, syntaxTree, cancellationToken); public static T GetOption<T>(this AnalyzerOptions analyzerOptions, PerLanguageOption2<T> option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken) => GetOption<T>(analyzerOptions, (IOption2)option, language, syntaxTree, cancellationToken); #pragma warning disable IDE0060 // Remove unused parameter - Needed to share this method signature between CodeStyle and Features layer. public static AnalyzerConfigOptions GetAnalyzerOptionSet(this AnalyzerOptions analyzerOptions, SyntaxTree syntaxTree, CancellationToken cancellationToken) #pragma warning restore IDE0060 // Remove unused parameter => analyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ICoalesceOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ICoalesceOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_01() { var source = @" class C { void F(int? input, int alternative, int result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Identity) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_02() { var source = @" class C { void F(int? input, long alternative, long result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNumeric) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNumeric) Operand: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_03() { var source = @" class C { void F(int? input, long? alternative, long? result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64?) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64?, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64?) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_04() { var source = @" class C { void F(string input, object alternative, object result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Object) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_05() { var source = @" class C { void F(int? input, System.DateTime alternative, object result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'int?' and 'DateTime' // result = input ?? alternative; Diagnostic(ErrorCode.ERR_BadBinaryOps, "input ?? alternative").WithArguments("??", "int?", "System.DateTime").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input') ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_06() { var source = @" class C { void F(int? input, dynamic alternative, dynamic result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) Operand: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_07() { var source = @" class C { void F(dynamic alternative, dynamic result) /*<bind>*/{ result = null ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'null ?? alternative') Expression: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = nu ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'null ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_08() { var source = @" class C { void F(int alternative, int result) /*<bind>*/{ result = null ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0019: Operator '??' cannot be applied to operands of type '<null>' and 'int' // result = null ?? alternative; Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? alternative").WithArguments("??", "<null>", "int").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'null ?? alternative') Expression: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsInvalid, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = nu ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'result = nu ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_09() { var source = @" class C { void F(int? alternative, int? result) /*<bind>*/{ result = null ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'null ?? alternative') Expression: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = nu ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'null ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_10() { var source = @" class C { void F(int? input, byte? alternative, int? result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Identity) WhenNull: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_11() { var source = @" class C { void F(int? input, int? alternative, int? result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Identity) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_12() { var source = @" class C { void F(int? input1, int? alternative1, int? input2, int? alternative2, int? result) /*<bind>*/{ result = (input1 ?? alternative1) ?? (input2 ?? alternative2); }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [3] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative1') Value: IParameterReferenceOperation: alternative1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative1') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1 ?? alternative1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1') Leaving: {R2} Entering: {R4} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1 ?? alternative1') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1') Next (Regular) Block[B10] Leaving: {R2} } .locals {R4} { CaptureIds: [4] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input2') Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input2') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2') Leaving: {R4} Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2') Next (Regular) Block[B10] Leaving: {R4} } Block[B9] - Block Predecessors: [B7] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative2') Value: IParameterReferenceOperation: alternative2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative2') Next (Regular) Block[B10] Block[B10] - Block Predecessors: [B6] [B8] [B9] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = (i ... ernative2);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = (i ... ternative2)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: '(input1 ?? ... ternative2)') Next (Regular) Block[B11] Leaving: {R1} } Block[B11] - Exit Predecessors: [B10] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_13() { var source = @" class C { const string input = ""a""; void F(object alternative, object result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IFieldReferenceOperation: System.String C.input (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""a"") (Syntax: 'input') Instance Receiver: null Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_14() { string source = @" class P { void M1(int? i, int j, int result) /*<bind>*/{ result = i ?? j; }/*</bind>*/ } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j') Value: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i ?? j;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = i ?? j') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i ?? j') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedGraph, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ICoalesceOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_01() { var source = @" class C { void F(int? input, int alternative, int result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Identity) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_02() { var source = @" class C { void F(int? input, long alternative, long result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNumeric) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNumeric) Operand: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_03() { var source = @" class C { void F(int? input, long? alternative, long? result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64?) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64?, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64?) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_04() { var source = @" class C { void F(string input, object alternative, object result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Object) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_05() { var source = @" class C { void F(int? input, System.DateTime alternative, object result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'int?' and 'DateTime' // result = input ?? alternative; Diagnostic(ErrorCode.ERR_BadBinaryOps, "input ?? alternative").WithArguments("??", "int?", "System.DateTime").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input') ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_06() { var source = @" class C { void F(int? input, dynamic alternative, dynamic result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) Operand: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_07() { var source = @" class C { void F(dynamic alternative, dynamic result) /*<bind>*/{ result = null ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'null ?? alternative') Expression: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = nu ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'null ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_08() { var source = @" class C { void F(int alternative, int result) /*<bind>*/{ result = null ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0019: Operator '??' cannot be applied to operands of type '<null>' and 'int' // result = null ?? alternative; Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? alternative").WithArguments("??", "<null>", "int").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'null ?? alternative') Expression: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsInvalid, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = nu ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'result = nu ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_09() { var source = @" class C { void F(int? alternative, int? result) /*<bind>*/{ result = null ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'null ?? alternative') Expression: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = nu ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'null ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_10() { var source = @" class C { void F(int? input, byte? alternative, int? result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Identity) WhenNull: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_11() { var source = @" class C { void F(int? input, int? alternative, int? result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative') Expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Identity) WhenNull: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') "); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_12() { var source = @" class C { void F(int? input1, int? alternative1, int? input2, int? alternative2, int? result) /*<bind>*/{ result = (input1 ?? alternative1) ?? (input2 ?? alternative2); }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [3] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative1') Value: IParameterReferenceOperation: alternative1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative1') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1 ?? alternative1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1') Leaving: {R2} Entering: {R4} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1 ?? alternative1') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1') Next (Regular) Block[B10] Leaving: {R2} } .locals {R4} { CaptureIds: [4] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input2') Jump if True (Regular) to Block[B9] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input2') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2') Leaving: {R4} Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2') Next (Regular) Block[B10] Leaving: {R4} } Block[B9] - Block Predecessors: [B7] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative2') Value: IParameterReferenceOperation: alternative2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative2') Next (Regular) Block[B10] Block[B10] - Block Predecessors: [B6] [B8] [B9] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = (i ... ernative2);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = (i ... ternative2)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: '(input1 ?? ... ternative2)') Next (Regular) Block[B11] Leaving: {R1} } Block[B11] - Exit Predecessors: [B10] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_13() { var source = @" class C { const string input = ""a""; void F(object alternative, object result) /*<bind>*/{ result = input ?? alternative; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IFieldReferenceOperation: System.String C.input (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""a"") (Syntax: 'input') Instance Receiver: null Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'input') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative') Value: IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CoalesceOperation_14() { string source = @" class P { void M1(int? i, int j, int result) /*<bind>*/{ result = i ?? j; }/*</bind>*/ } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j') Value: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i ?? j;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = i ?? j') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i ?? j') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Utilities/CodeSnippets.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests { internal static class CodeSnippets { public const string FormattableStringType = @" namespace System { public abstract class FormattableString : IFormattable { public abstract string Format { get; } public abstract object[] GetArguments(); public abstract int ArgumentCount { get; } public abstract object GetArgument(int index); public abstract string ToString(IFormatProvider formatProvider); string IFormattable.ToString(string ignored, IFormatProvider formatProvider) => ToString(formatProvider); public static string Invariant(FormattableString formattable) => formattable.ToString(Globalization.CultureInfo.InvariantCulture); public override string ToString() => ToString(Globalization.CultureInfo.CurrentCulture); } } namespace System.Runtime.CompilerServices { public static class FormattableStringFactory { public static FormattableString Create(string format, params object[] arguments) => new ConcreteFormattableString(format, arguments); private sealed class ConcreteFormattableString : FormattableString { private readonly string _format; private readonly object[] _arguments; internal ConcreteFormattableString(string format, object[] arguments) { _format = format; _arguments = arguments; } public override string Format => _format; public override object[] GetArguments() => _arguments; public override int ArgumentCount => _arguments.Length; public override object GetArgument(int index) => _arguments[index]; public override string ToString(IFormatProvider formatProvider) => string.Format(formatProvider, _format, _arguments); } } } "; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests { internal static class CodeSnippets { public const string FormattableStringType = @" namespace System { public abstract class FormattableString : IFormattable { public abstract string Format { get; } public abstract object[] GetArguments(); public abstract int ArgumentCount { get; } public abstract object GetArgument(int index); public abstract string ToString(IFormatProvider formatProvider); string IFormattable.ToString(string ignored, IFormatProvider formatProvider) => ToString(formatProvider); public static string Invariant(FormattableString formattable) => formattable.ToString(Globalization.CultureInfo.InvariantCulture); public override string ToString() => ToString(Globalization.CultureInfo.CurrentCulture); } } namespace System.Runtime.CompilerServices { public static class FormattableStringFactory { public static FormattableString Create(string format, params object[] arguments) => new ConcreteFormattableString(format, arguments); private sealed class ConcreteFormattableString : FormattableString { private readonly string _format; private readonly object[] _arguments; internal ConcreteFormattableString(string format, object[] arguments) { _format = format; _arguments = arguments; } public override string Format => _format; public override object[] GetArguments() => _arguments; public override int ArgumentCount => _arguments.Length; public override object GetArgument(int index) => _arguments[index]; public override string ToString(IFormatProvider formatProvider) => string.Format(formatProvider, _format, _arguments); } } } "; } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest2/Recommendations/ThisKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 ThisKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(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 TestNotAfterAngle() { await VerifyAbsenceAsync( @"interface IGoo<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInterfaceTypeVarianceNotAfterIn() { await VerifyAbsenceAsync( @"interface IGoo<in $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInterfaceTypeVarianceNotAfterComma() { await VerifyAbsenceAsync( @"interface IGoo<Goo, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInterfaceTypeVarianceNotAfterAttribute() { await VerifyAbsenceAsync( @"interface IGoo<[Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestDelegateTypeVarianceNotAfterAngle() { await VerifyAbsenceAsync( @"delegate void D<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestDelegateTypeVarianceNotAfterComma() { await VerifyAbsenceAsync( @"delegate void D<Goo, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestDelegateTypeVarianceNotAfterAttribute() { await VerifyAbsenceAsync( @"delegate void D<[Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotThisBaseListAfterAngle() { await VerifyAbsenceAsync( @"interface IGoo : Bar<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGenericMethod() { await VerifyAbsenceAsync( @"interface IGoo { void Goo<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRef() { await VerifyAbsenceAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIn() { await VerifyAbsenceAsync( @"class C { void Goo(in $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterThis_InBogusMethod() { await VerifyAbsenceAsync( @"class C { void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterOut() { await VerifyAbsenceAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethodOpenParen() { await VerifyAbsenceAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethodComma() { await VerifyAbsenceAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethodAttribute() { await VerifyAbsenceAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterConstructorOpenParen() { await VerifyAbsenceAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterConstructorComma() { await VerifyAbsenceAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterConstructorAttribute() { await VerifyAbsenceAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateOpenParen() { await VerifyAbsenceAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateComma() { await VerifyAbsenceAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAttribute() { await VerifyAbsenceAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterOperator() { await VerifyAbsenceAsync( @"class C { static int operator +($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDestructor() { await VerifyAbsenceAsync( @"class C { ~C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIndexer() { await VerifyAbsenceAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInInstanceMethodInInstanceClass() { await VerifyAbsenceAsync( @"class C { int Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticMethodInInstanceClass() { await VerifyAbsenceAsync( @"class C { static int Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInInstanceMethodInStaticClass() { await VerifyAbsenceAsync( @"static class C { int Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInStaticMethodInStaticClass() { await VerifyKeywordAsync( @"static class C { static int Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27028, "https://github.com/dotnet/roslyn/issues/27028")] public async Task TestInLocalFunction() { await VerifyKeywordAsync( @"class C { int Method() { void local() { $$ } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27028, "https://github.com/dotnet/roslyn/issues/27028")] public async Task TestInNestedLocalFunction() { await VerifyKeywordAsync( @"class C { int Method() { void local() { void nested() { $$ } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27028, "https://github.com/dotnet/roslyn/issues/27028")] public async Task TestInLocalFunctionInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { void local() { $$ } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27028, "https://github.com/dotnet/roslyn/issues/27028")] public async Task TestInNestedLocalFunctionInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { void local() { void nested() { $$ } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(35644, "https://github.com/dotnet/roslyn/issues/35644")] public async Task TestInStaticLocalFunction() { await VerifyAbsenceAsync( @"class C { int Method() { static void local() { $$ } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(35644, "https://github.com/dotnet/roslyn/issues/35644")] public async Task TestInNestedInStaticLocalFunction() { await VerifyAbsenceAsync( @"class C { int Method() { static void local() { void nested() { $$ } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethod() { await VerifyKeywordAsync( @"class C { int Method() { Action a = delegate { $$ }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedAnonymousMethod() { await VerifyKeywordAsync( @"class C { int Method() { Action a = delegate { Action b = delegate { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { Action a = delegate { $$ }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedAnonymousMethodInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { Action a = delegate { Action b = delegate { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInLambdaExpression() { await VerifyKeywordAsync( @"class C { int Method() { Action a = () => { $$ }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedLambdaExpression() { await VerifyKeywordAsync( @"class C { int Method() { Action a = () => { Action b = () => { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInLambdaExpressionInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { Action a = () => { $$ }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedLambdaExpressionInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { Action a = () => { Action b = () => { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedLambdaExpressionInAnonymousMethod() { await VerifyKeywordAsync( @"class C { int Method() { Action a = delegate { Action b = () => { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedAnonymousInLambdaExpression() { await VerifyKeywordAsync( @"class C { int Method() { Action a = () => { Action b = delegate { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedAnonymousMethodInLambdaExpressionInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { Action a = () => { Action b = delegate { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedLambdaExpressionInAnonymousMethodInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { Action a = delegate { Action b = () => { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAProperty() { await VerifyKeywordAsync( @"class C { Action A { get { return delegate { $$ } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAPropertyInitializer() { await VerifyKeywordAsync( @"class C { Action B { get; } = delegate { $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAExpressionProperty() { await VerifyKeywordAsync( @"class C { Action A => delegate { $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAFieldInitializer() { await VerifyKeywordAsync( @"class C { Action A = delegate { $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAStaticProperty() { await VerifyAbsenceAsync( @"class C { static Action A { get { return delegate { $$ } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAStaticPropertyInitializer() { await VerifyAbsenceAsync( @"class C { static Action B { get; } = delegate { $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAStaticExpressionProperty() { await VerifyAbsenceAsync( @"class C { static Action A => delegate { $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAStaticFieldInitializer() { await VerifyAbsenceAsync( @"class C { static Action A = delegate { $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAttribute() { await VerifyKeywordAsync( @"static class C { static int Goo([Bar]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSecondAttribute() { await VerifyAbsenceAsync( @"static class C { static int Goo(this int i, [Bar]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterThis() { await VerifyAbsenceAsync( @"static class C { static int Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterFirstParameter() { await VerifyAbsenceAsync( @"static class C { static int Goo(this int a, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInClassConstructorInitializer() { await VerifyKeywordAsync( @"class C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticClassConstructorInitializer() { await VerifyAbsenceAsync( @"class C { static C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInStructConstructorInitializer() { await VerifyKeywordAsync( @"struct C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterCast() { await VerifyKeywordAsync(AddInsideMethod( @"stack.Push(((IEnumerable<Segment>)((TreeSegment)$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReturn() { await VerifyKeywordAsync(AddInsideMethod( @"return $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexer() { await VerifyKeywordAsync(AddInsideMethod( @"return this.items[$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSimpleCast() { await VerifyKeywordAsync(AddInsideMethod( @"return ((IEnumerable<T>)$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClass() { await VerifyAbsenceAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVoid() { await VerifyAbsenceAsync( @"class C { void $$"); } [WorkItem(542636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542636")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterType() { await VerifyAbsenceAsync( @"class C { int $$"); } [WorkItem(542636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542636")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeArray() { await VerifyAbsenceAsync( @"class C { internal byte[] $$"); } [WorkItem(542636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542636")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeArrayBeforeArguments() { await VerifyAbsenceAsync( @"class C { internal byte[] $$[int i] { get; }"); } [WorkItem(542636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542636")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeBeforeArguments() { await VerifyAbsenceAsync( @"class C { internal byte $$[int i] { get; }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMultiply() { await VerifyKeywordAsync( @"class C { internal CustomAttributeRow this[uint rowId] // This is 1 based... { get // ^ requires rowId <= this.NumberOfRows; { int rowOffset = (int)(rowId - 1) * $$"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticMethod() { await VerifyAbsenceAsync( @"class C { static void Goo() { int i = $$ } }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticProperty() { await VerifyAbsenceAsync( @"class C { static int Goo { get { int i = $$ } }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInstanceProperty() { await VerifyKeywordAsync( @"class C { int Goo { get { int i = $$ } }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticConstructor() { await VerifyAbsenceAsync( @"class C { static C() { int i = $$ } }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInstanceConstructor() { await VerifyKeywordAsync( @"class C { public C() { int i = $$ } }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumMemberInitializer1() { await VerifyAbsenceAsync( @"enum E { a = $$ }"); } [WorkItem(539334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539334")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartialInType() { await VerifyAbsenceAsync( @"class C { partial $$ }"); } [WorkItem(540476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540476")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIncompleteTypeName() { await VerifyAbsenceAsync( @"class C { Goo.$$ }"); } [WorkItem(541712, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541712")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticMethodContext() { await VerifyAbsenceAsync( @"class Program { static void Main(string[] args) { $$ } }"); } [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(725, "https://github.com/dotnet/roslyn/issues/725")] [WorkItem(1107414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExpressionBodiedMembersProperty() { await VerifyKeywordAsync(@" class C { int x; int M => $$ int p; }"); } [WorkItem(725, "https://github.com/dotnet/roslyn/issues/725")] [WorkItem(1107414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExpressionBodiedMembersMethod() { await VerifyKeywordAsync(@" class C { int x; int give() => $$"); } [WorkItem(725, "https://github.com/dotnet/roslyn/issues/725")] [WorkItem(1107414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExpressionBodiedMembersIndexer() { await VerifyKeywordAsync(@" class C { int x; public object this[int i] => $$"); } [WorkItem(725, "https://github.com/dotnet/roslyn/issues/725")] [WorkItem(1107414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInExpressionBodiedMembers_Static() { await VerifyAbsenceAsync(@" class C { int x; static int M => $$"); } [WorkItem(725, "https://github.com/dotnet/roslyn/issues/725")] [WorkItem(1107414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInExpressionBodiedMembersOperator() { await VerifyAbsenceAsync(@" class C { int x; public static C operator - (C c1) => $$"); } [WorkItem(725, "https://github.com/dotnet/roslyn/issues/725")] [WorkItem(1107414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInExpressionBodiedMembersConversionOperator() { await VerifyAbsenceAsync(@" class F { } class C { int x; public static explicit operator F(C c1) => $$"); } [WorkItem(725, "https://github.com/dotnet/roslyn/issues/725")] [WorkItem(1107414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOutsideExpressionBodiedMember() { await VerifyAbsenceAsync(@" class C { int x; int M => this.x;$$ int p; }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task Preselection() { await VerifyKeywordAsync(@" class Program { void Main(string[] args) { Helper($$) } void Helper(Program x) { } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterRefKeyword_InClass() { await VerifyKeywordAsync(@" public static class Extensions { public static void Extension(ref $$"); await VerifyKeywordAsync(@" public static class Extensions { public static void Extension(ref $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterInKeyword_InClass() { await VerifyKeywordAsync(@" public static class Extensions { public static void Extension(in $$"); await VerifyKeywordAsync(@" public static class Extensions { public static void Extension(in $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterOutKeyword_InClass() { await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(out $$"); await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(out $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_AfterRefKeyword_InClass() { await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(int x, ref $$"); await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(int x, ref $$ object obj) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_AfterInKeyword_InClass() { await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(int x, in $$"); await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(int x, in $$ object obj) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_AfterOutKeyword_InClass() { await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(int x, out $$"); await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(int x, out $$ object obj) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterRefKeyword_OutsideClass() { await VerifyAbsenceAsync("public static void Extension(ref $$"); await VerifyAbsenceAsync("public static void Extension(ref $$ object obj, int x) { }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterInKeyword_OutsideClass() { await VerifyAbsenceAsync("public static void Extension(in $$"); await VerifyAbsenceAsync("public static void Extension(in $$ object obj, int x) { }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterOutKeyword_OutsideClass() { await VerifyAbsenceAsync("public static void Extension(out $$"); await VerifyAbsenceAsync("public static void Extension(out $$ object obj, int x) { }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterRefKeyword_NonStaticClass() { await VerifyAbsenceAsync(@" public class Extensions { public static void Extension(ref $$"); await VerifyAbsenceAsync(@" public class Extensions { public static void Extension(ref $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterInKeyword_NonStaticClass() { await VerifyAbsenceAsync(@" public class Extensions { public static void Extension(in $$"); await VerifyAbsenceAsync(@" public class Extensions { public static void Extension(in $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterOutKeyword_NonStaticClass() { await VerifyAbsenceAsync(@" public class Extensions { public static void Extension(out $$"); await VerifyAbsenceAsync(@" public class Extensions { public static void Extension(out $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterRefKeyword_NonStaticMethod() { await VerifyAbsenceAsync(@" public static class Extensions { public void Extension(ref $$"); await VerifyAbsenceAsync(@" public static class Extensions { public void Extension(ref $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterInKeyword_NonStaticMethod() { await VerifyAbsenceAsync(@" public static class Extensions { public void Extension(in $$"); await VerifyAbsenceAsync(@" public static class Extensions { public void Extension(in $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterOutKeyword_NonStaticMethod() { await VerifyAbsenceAsync(@" public static class Extensions { public void Extension(out $$"); await VerifyAbsenceAsync(@" public static class Extensions { public void Extension(out $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 ThisKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(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 TestNotAfterAngle() { await VerifyAbsenceAsync( @"interface IGoo<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInterfaceTypeVarianceNotAfterIn() { await VerifyAbsenceAsync( @"interface IGoo<in $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInterfaceTypeVarianceNotAfterComma() { await VerifyAbsenceAsync( @"interface IGoo<Goo, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInterfaceTypeVarianceNotAfterAttribute() { await VerifyAbsenceAsync( @"interface IGoo<[Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestDelegateTypeVarianceNotAfterAngle() { await VerifyAbsenceAsync( @"delegate void D<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestDelegateTypeVarianceNotAfterComma() { await VerifyAbsenceAsync( @"delegate void D<Goo, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestDelegateTypeVarianceNotAfterAttribute() { await VerifyAbsenceAsync( @"delegate void D<[Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotThisBaseListAfterAngle() { await VerifyAbsenceAsync( @"interface IGoo : Bar<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGenericMethod() { await VerifyAbsenceAsync( @"interface IGoo { void Goo<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRef() { await VerifyAbsenceAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIn() { await VerifyAbsenceAsync( @"class C { void Goo(in $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterThis_InBogusMethod() { await VerifyAbsenceAsync( @"class C { void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterOut() { await VerifyAbsenceAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethodOpenParen() { await VerifyAbsenceAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethodComma() { await VerifyAbsenceAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethodAttribute() { await VerifyAbsenceAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterConstructorOpenParen() { await VerifyAbsenceAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterConstructorComma() { await VerifyAbsenceAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterConstructorAttribute() { await VerifyAbsenceAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateOpenParen() { await VerifyAbsenceAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateComma() { await VerifyAbsenceAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAttribute() { await VerifyAbsenceAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterOperator() { await VerifyAbsenceAsync( @"class C { static int operator +($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDestructor() { await VerifyAbsenceAsync( @"class C { ~C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIndexer() { await VerifyAbsenceAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInInstanceMethodInInstanceClass() { await VerifyAbsenceAsync( @"class C { int Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticMethodInInstanceClass() { await VerifyAbsenceAsync( @"class C { static int Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInInstanceMethodInStaticClass() { await VerifyAbsenceAsync( @"static class C { int Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInStaticMethodInStaticClass() { await VerifyKeywordAsync( @"static class C { static int Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27028, "https://github.com/dotnet/roslyn/issues/27028")] public async Task TestInLocalFunction() { await VerifyKeywordAsync( @"class C { int Method() { void local() { $$ } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27028, "https://github.com/dotnet/roslyn/issues/27028")] public async Task TestInNestedLocalFunction() { await VerifyKeywordAsync( @"class C { int Method() { void local() { void nested() { $$ } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27028, "https://github.com/dotnet/roslyn/issues/27028")] public async Task TestInLocalFunctionInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { void local() { $$ } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27028, "https://github.com/dotnet/roslyn/issues/27028")] public async Task TestInNestedLocalFunctionInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { void local() { void nested() { $$ } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(35644, "https://github.com/dotnet/roslyn/issues/35644")] public async Task TestInStaticLocalFunction() { await VerifyAbsenceAsync( @"class C { int Method() { static void local() { $$ } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(35644, "https://github.com/dotnet/roslyn/issues/35644")] public async Task TestInNestedInStaticLocalFunction() { await VerifyAbsenceAsync( @"class C { int Method() { static void local() { void nested() { $$ } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethod() { await VerifyKeywordAsync( @"class C { int Method() { Action a = delegate { $$ }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedAnonymousMethod() { await VerifyKeywordAsync( @"class C { int Method() { Action a = delegate { Action b = delegate { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { Action a = delegate { $$ }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedAnonymousMethodInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { Action a = delegate { Action b = delegate { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInLambdaExpression() { await VerifyKeywordAsync( @"class C { int Method() { Action a = () => { $$ }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedLambdaExpression() { await VerifyKeywordAsync( @"class C { int Method() { Action a = () => { Action b = () => { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInLambdaExpressionInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { Action a = () => { $$ }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedLambdaExpressionInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { Action a = () => { Action b = () => { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedLambdaExpressionInAnonymousMethod() { await VerifyKeywordAsync( @"class C { int Method() { Action a = delegate { Action b = () => { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedAnonymousInLambdaExpression() { await VerifyKeywordAsync( @"class C { int Method() { Action a = () => { Action b = delegate { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedAnonymousMethodInLambdaExpressionInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { Action a = () => { Action b = delegate { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInNestedLambdaExpressionInAnonymousMethodInStaticMethod() { await VerifyAbsenceAsync( @"class C { static int Method() { Action a = delegate { Action b = () => { $$ }; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAProperty() { await VerifyKeywordAsync( @"class C { Action A { get { return delegate { $$ } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAPropertyInitializer() { await VerifyKeywordAsync( @"class C { Action B { get; } = delegate { $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAExpressionProperty() { await VerifyKeywordAsync( @"class C { Action A => delegate { $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAFieldInitializer() { await VerifyKeywordAsync( @"class C { Action A = delegate { $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAStaticProperty() { await VerifyAbsenceAsync( @"class C { static Action A { get { return delegate { $$ } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAStaticPropertyInitializer() { await VerifyAbsenceAsync( @"class C { static Action B { get; } = delegate { $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAStaticExpressionProperty() { await VerifyAbsenceAsync( @"class C { static Action A => delegate { $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(27923, "https://github.com/dotnet/roslyn/issues/27923")] public async Task TestInAnonymousMethodInAStaticFieldInitializer() { await VerifyAbsenceAsync( @"class C { static Action A = delegate { $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAttribute() { await VerifyKeywordAsync( @"static class C { static int Goo([Bar]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSecondAttribute() { await VerifyAbsenceAsync( @"static class C { static int Goo(this int i, [Bar]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterThis() { await VerifyAbsenceAsync( @"static class C { static int Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterFirstParameter() { await VerifyAbsenceAsync( @"static class C { static int Goo(this int a, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInClassConstructorInitializer() { await VerifyKeywordAsync( @"class C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticClassConstructorInitializer() { await VerifyAbsenceAsync( @"class C { static C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInStructConstructorInitializer() { await VerifyKeywordAsync( @"struct C { public C() : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterCast() { await VerifyKeywordAsync(AddInsideMethod( @"stack.Push(((IEnumerable<Segment>)((TreeSegment)$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReturn() { await VerifyKeywordAsync(AddInsideMethod( @"return $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexer() { await VerifyKeywordAsync(AddInsideMethod( @"return this.items[$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSimpleCast() { await VerifyKeywordAsync(AddInsideMethod( @"return ((IEnumerable<T>)$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClass() { await VerifyAbsenceAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVoid() { await VerifyAbsenceAsync( @"class C { void $$"); } [WorkItem(542636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542636")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterType() { await VerifyAbsenceAsync( @"class C { int $$"); } [WorkItem(542636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542636")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeArray() { await VerifyAbsenceAsync( @"class C { internal byte[] $$"); } [WorkItem(542636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542636")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeArrayBeforeArguments() { await VerifyAbsenceAsync( @"class C { internal byte[] $$[int i] { get; }"); } [WorkItem(542636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542636")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeBeforeArguments() { await VerifyAbsenceAsync( @"class C { internal byte $$[int i] { get; }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMultiply() { await VerifyKeywordAsync( @"class C { internal CustomAttributeRow this[uint rowId] // This is 1 based... { get // ^ requires rowId <= this.NumberOfRows; { int rowOffset = (int)(rowId - 1) * $$"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticMethod() { await VerifyAbsenceAsync( @"class C { static void Goo() { int i = $$ } }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticProperty() { await VerifyAbsenceAsync( @"class C { static int Goo { get { int i = $$ } }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInstanceProperty() { await VerifyKeywordAsync( @"class C { int Goo { get { int i = $$ } }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticConstructor() { await VerifyAbsenceAsync( @"class C { static C() { int i = $$ } }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInstanceConstructor() { await VerifyKeywordAsync( @"class C { public C() { int i = $$ } }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumMemberInitializer1() { await VerifyAbsenceAsync( @"enum E { a = $$ }"); } [WorkItem(539334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539334")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartialInType() { await VerifyAbsenceAsync( @"class C { partial $$ }"); } [WorkItem(540476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540476")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIncompleteTypeName() { await VerifyAbsenceAsync( @"class C { Goo.$$ }"); } [WorkItem(541712, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541712")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStaticMethodContext() { await VerifyAbsenceAsync( @"class Program { static void Main(string[] args) { $$ } }"); } [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(725, "https://github.com/dotnet/roslyn/issues/725")] [WorkItem(1107414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExpressionBodiedMembersProperty() { await VerifyKeywordAsync(@" class C { int x; int M => $$ int p; }"); } [WorkItem(725, "https://github.com/dotnet/roslyn/issues/725")] [WorkItem(1107414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExpressionBodiedMembersMethod() { await VerifyKeywordAsync(@" class C { int x; int give() => $$"); } [WorkItem(725, "https://github.com/dotnet/roslyn/issues/725")] [WorkItem(1107414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExpressionBodiedMembersIndexer() { await VerifyKeywordAsync(@" class C { int x; public object this[int i] => $$"); } [WorkItem(725, "https://github.com/dotnet/roslyn/issues/725")] [WorkItem(1107414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInExpressionBodiedMembers_Static() { await VerifyAbsenceAsync(@" class C { int x; static int M => $$"); } [WorkItem(725, "https://github.com/dotnet/roslyn/issues/725")] [WorkItem(1107414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInExpressionBodiedMembersOperator() { await VerifyAbsenceAsync(@" class C { int x; public static C operator - (C c1) => $$"); } [WorkItem(725, "https://github.com/dotnet/roslyn/issues/725")] [WorkItem(1107414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInExpressionBodiedMembersConversionOperator() { await VerifyAbsenceAsync(@" class F { } class C { int x; public static explicit operator F(C c1) => $$"); } [WorkItem(725, "https://github.com/dotnet/roslyn/issues/725")] [WorkItem(1107414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107414")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestOutsideExpressionBodiedMember() { await VerifyAbsenceAsync(@" class C { int x; int M => this.x;$$ int p; }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task Preselection() { await VerifyKeywordAsync(@" class Program { void Main(string[] args) { Helper($$) } void Helper(Program x) { } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterRefKeyword_InClass() { await VerifyKeywordAsync(@" public static class Extensions { public static void Extension(ref $$"); await VerifyKeywordAsync(@" public static class Extensions { public static void Extension(ref $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterInKeyword_InClass() { await VerifyKeywordAsync(@" public static class Extensions { public static void Extension(in $$"); await VerifyKeywordAsync(@" public static class Extensions { public static void Extension(in $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterOutKeyword_InClass() { await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(out $$"); await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(out $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_AfterRefKeyword_InClass() { await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(int x, ref $$"); await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(int x, ref $$ object obj) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_AfterInKeyword_InClass() { await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(int x, in $$"); await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(int x, in $$ object obj) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_AfterOutKeyword_InClass() { await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(int x, out $$"); await VerifyAbsenceAsync(@" public static class Extensions { public static void Extension(int x, out $$ object obj) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterRefKeyword_OutsideClass() { await VerifyAbsenceAsync("public static void Extension(ref $$"); await VerifyAbsenceAsync("public static void Extension(ref $$ object obj, int x) { }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterInKeyword_OutsideClass() { await VerifyAbsenceAsync("public static void Extension(in $$"); await VerifyAbsenceAsync("public static void Extension(in $$ object obj, int x) { }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterOutKeyword_OutsideClass() { await VerifyAbsenceAsync("public static void Extension(out $$"); await VerifyAbsenceAsync("public static void Extension(out $$ object obj, int x) { }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterRefKeyword_NonStaticClass() { await VerifyAbsenceAsync(@" public class Extensions { public static void Extension(ref $$"); await VerifyAbsenceAsync(@" public class Extensions { public static void Extension(ref $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterInKeyword_NonStaticClass() { await VerifyAbsenceAsync(@" public class Extensions { public static void Extension(in $$"); await VerifyAbsenceAsync(@" public class Extensions { public static void Extension(in $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterOutKeyword_NonStaticClass() { await VerifyAbsenceAsync(@" public class Extensions { public static void Extension(out $$"); await VerifyAbsenceAsync(@" public class Extensions { public static void Extension(out $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterRefKeyword_NonStaticMethod() { await VerifyAbsenceAsync(@" public static class Extensions { public void Extension(ref $$"); await VerifyAbsenceAsync(@" public static class Extensions { public void Extension(ref $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterInKeyword_NonStaticMethod() { await VerifyAbsenceAsync(@" public static class Extensions { public void Extension(in $$"); await VerifyAbsenceAsync(@" public static class Extensions { public void Extension(in $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterOutKeyword_NonStaticMethod() { await VerifyAbsenceAsync(@" public static class Extensions { public void Extension(out $$"); await VerifyAbsenceAsync(@" public static class Extensions { public void Extension(out $$ object obj, int x) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionService.CacheEntry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion { internal abstract partial class AbstractTypeImportCompletionService { private readonly struct CacheEntry { public string Language { get; } public Checksum Checksum { get; } private ImmutableArray<TypeImportCompletionItemInfo> ItemInfos { get; } /// <summary> /// The number of items in this entry for types declared as public. /// This is used to minimize memory allocation in case non-public items aren't needed. /// </summary> private int PublicItemCount { get; } private CacheEntry( Checksum checksum, string language, ImmutableArray<TypeImportCompletionItemInfo> items, int publicItemCount) { Checksum = checksum; Language = language; ItemInfos = items; PublicItemCount = publicItemCount; } public ImmutableArray<CompletionItem> GetItemsForContext( string language, string genericTypeSuffix, bool isInternalsVisible, bool isAttributeContext, bool isCaseSensitive, bool hideAdvancedMembers) { var isSameLanguage = Language == language; using var _ = ArrayBuilder<CompletionItem>.GetInstance(out var builder); // PERF: try set the capacity upfront to avoid allocation from Resize if (!isAttributeContext) { if (isInternalsVisible) { builder.EnsureCapacity(ItemInfos.Length); } else { builder.EnsureCapacity(PublicItemCount); } } foreach (var info in ItemInfos) { if (!info.IsPublic && !isInternalsVisible) { continue; } // Option to show advanced members is false so we need to exclude them. if (hideAdvancedMembers && info.IsEditorBrowsableStateAdvanced) { continue; } var item = info.Item; if (isAttributeContext) { // Don't show non attribute item in attribute context if (!info.IsAttribute) { continue; } // We are in attribute context, will not show or complete with "Attribute" suffix. item = GetAppropriateAttributeItem(info.Item, isCaseSensitive); } // C# and VB the display text is different for generics, i.e. <T> and (Of T). For simpllicity, we only cache for one language. // But when we trigger in a project with different language than when the cache entry was created for, we will need to // change the generic suffix accordingly. if (!isSameLanguage && info.IsGeneric) { // We don't want to cache this item. item = ImportCompletionItem.CreateItemWithGenericDisplaySuffix(item, genericTypeSuffix); } builder.Add(item); } return builder.ToImmutable(); static CompletionItem GetAppropriateAttributeItem(CompletionItem attributeItem, bool isCaseSensitive) { if (attributeItem.DisplayText.TryGetWithoutAttributeSuffix(isCaseSensitive: isCaseSensitive, out var attributeNameWithoutSuffix)) { // We don't want to cache this item. return ImportCompletionItem.CreateAttributeItemWithoutSuffix(attributeItem, attributeNameWithoutSuffix, CompletionItemFlags.Expanded); } return attributeItem; } } public class Builder : IDisposable { private readonly string _language; private readonly string _genericTypeSuffix; private readonly Checksum _checksum; private readonly EditorBrowsableInfo _editorBrowsableInfo; private int _publicItemCount; private readonly ArrayBuilder<TypeImportCompletionItemInfo> _itemsBuilder; public Builder(Checksum checksum, string language, string genericTypeSuffix, EditorBrowsableInfo editorBrowsableInfo) { _checksum = checksum; _language = language; _genericTypeSuffix = genericTypeSuffix; _editorBrowsableInfo = editorBrowsableInfo; _itemsBuilder = ArrayBuilder<TypeImportCompletionItemInfo>.GetInstance(); } public CacheEntry ToReferenceCacheEntry() { return new CacheEntry( _checksum, _language, _itemsBuilder.ToImmutable(), _publicItemCount); } public void AddItem(INamedTypeSymbol symbol, string containingNamespace, bool isPublic) { // We want to cache items with EditoBrowsableState == Advanced regardless of current "hide adv members" option value var (isBrowsable, isEditorBrowsableStateAdvanced) = symbol.IsEditorBrowsableWithState( hideAdvancedMembers: false, _editorBrowsableInfo.Compilation, _editorBrowsableInfo); if (!isBrowsable) { // Hide this item from completion return; } var isGeneric = symbol.Arity > 0; // Need to determine if a type is an attribute up front since we want to filter out // non-attribute types when in attribute context. We can't do this lazily since we don't hold // on to symbols. However, the cost of calling `IsAttribute` on every top-level type symbols // is prohibitively high, so we opt for the heuristic that would do the simple textual "Attribute" // suffix check first, then the more expensive symbolic check. As a result, all unimported // attribute types that don't have "Attribute" suffix would be filtered out when in attribute context. var isAttribute = symbol.Name.HasAttributeSuffix(isCaseSensitive: false) && symbol.IsAttribute(); var item = ImportCompletionItem.Create( symbol.Name, symbol.Arity, containingNamespace, symbol.GetGlyph(), _genericTypeSuffix, CompletionItemFlags.CachedAndExpanded, extensionMethodData: null); if (isPublic) _publicItemCount++; _itemsBuilder.Add(new TypeImportCompletionItemInfo(item, isPublic, isGeneric, isAttribute, isEditorBrowsableStateAdvanced)); } public void Dispose() => _itemsBuilder.Free(); } } [ExportWorkspaceServiceFactory(typeof(IImportCompletionCacheService<CacheEntry, CacheEntry>), ServiceLayer.Editor), Shared] private sealed class CacheServiceFactory : AbstractImportCompletionCacheServiceFactory<CacheEntry, CacheEntry> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CacheServiceFactory() { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion { internal abstract partial class AbstractTypeImportCompletionService { private readonly struct CacheEntry { public string Language { get; } public Checksum Checksum { get; } private ImmutableArray<TypeImportCompletionItemInfo> ItemInfos { get; } /// <summary> /// The number of items in this entry for types declared as public. /// This is used to minimize memory allocation in case non-public items aren't needed. /// </summary> private int PublicItemCount { get; } private CacheEntry( Checksum checksum, string language, ImmutableArray<TypeImportCompletionItemInfo> items, int publicItemCount) { Checksum = checksum; Language = language; ItemInfos = items; PublicItemCount = publicItemCount; } public ImmutableArray<CompletionItem> GetItemsForContext( string language, string genericTypeSuffix, bool isInternalsVisible, bool isAttributeContext, bool isCaseSensitive, bool hideAdvancedMembers) { var isSameLanguage = Language == language; using var _ = ArrayBuilder<CompletionItem>.GetInstance(out var builder); // PERF: try set the capacity upfront to avoid allocation from Resize if (!isAttributeContext) { if (isInternalsVisible) { builder.EnsureCapacity(ItemInfos.Length); } else { builder.EnsureCapacity(PublicItemCount); } } foreach (var info in ItemInfos) { if (!info.IsPublic && !isInternalsVisible) { continue; } // Option to show advanced members is false so we need to exclude them. if (hideAdvancedMembers && info.IsEditorBrowsableStateAdvanced) { continue; } var item = info.Item; if (isAttributeContext) { // Don't show non attribute item in attribute context if (!info.IsAttribute) { continue; } // We are in attribute context, will not show or complete with "Attribute" suffix. item = GetAppropriateAttributeItem(info.Item, isCaseSensitive); } // C# and VB the display text is different for generics, i.e. <T> and (Of T). For simpllicity, we only cache for one language. // But when we trigger in a project with different language than when the cache entry was created for, we will need to // change the generic suffix accordingly. if (!isSameLanguage && info.IsGeneric) { // We don't want to cache this item. item = ImportCompletionItem.CreateItemWithGenericDisplaySuffix(item, genericTypeSuffix); } builder.Add(item); } return builder.ToImmutable(); static CompletionItem GetAppropriateAttributeItem(CompletionItem attributeItem, bool isCaseSensitive) { if (attributeItem.DisplayText.TryGetWithoutAttributeSuffix(isCaseSensitive: isCaseSensitive, out var attributeNameWithoutSuffix)) { // We don't want to cache this item. return ImportCompletionItem.CreateAttributeItemWithoutSuffix(attributeItem, attributeNameWithoutSuffix, CompletionItemFlags.Expanded); } return attributeItem; } } public class Builder : IDisposable { private readonly string _language; private readonly string _genericTypeSuffix; private readonly Checksum _checksum; private readonly EditorBrowsableInfo _editorBrowsableInfo; private int _publicItemCount; private readonly ArrayBuilder<TypeImportCompletionItemInfo> _itemsBuilder; public Builder(Checksum checksum, string language, string genericTypeSuffix, EditorBrowsableInfo editorBrowsableInfo) { _checksum = checksum; _language = language; _genericTypeSuffix = genericTypeSuffix; _editorBrowsableInfo = editorBrowsableInfo; _itemsBuilder = ArrayBuilder<TypeImportCompletionItemInfo>.GetInstance(); } public CacheEntry ToReferenceCacheEntry() { return new CacheEntry( _checksum, _language, _itemsBuilder.ToImmutable(), _publicItemCount); } public void AddItem(INamedTypeSymbol symbol, string containingNamespace, bool isPublic) { // We want to cache items with EditoBrowsableState == Advanced regardless of current "hide adv members" option value var (isBrowsable, isEditorBrowsableStateAdvanced) = symbol.IsEditorBrowsableWithState( hideAdvancedMembers: false, _editorBrowsableInfo.Compilation, _editorBrowsableInfo); if (!isBrowsable) { // Hide this item from completion return; } var isGeneric = symbol.Arity > 0; // Need to determine if a type is an attribute up front since we want to filter out // non-attribute types when in attribute context. We can't do this lazily since we don't hold // on to symbols. However, the cost of calling `IsAttribute` on every top-level type symbols // is prohibitively high, so we opt for the heuristic that would do the simple textual "Attribute" // suffix check first, then the more expensive symbolic check. As a result, all unimported // attribute types that don't have "Attribute" suffix would be filtered out when in attribute context. var isAttribute = symbol.Name.HasAttributeSuffix(isCaseSensitive: false) && symbol.IsAttribute(); var item = ImportCompletionItem.Create( symbol.Name, symbol.Arity, containingNamespace, symbol.GetGlyph(), _genericTypeSuffix, CompletionItemFlags.CachedAndExpanded, extensionMethodData: null); if (isPublic) _publicItemCount++; _itemsBuilder.Add(new TypeImportCompletionItemInfo(item, isPublic, isGeneric, isAttribute, isEditorBrowsableStateAdvanced)); } public void Dispose() => _itemsBuilder.Free(); } } [ExportWorkspaceServiceFactory(typeof(IImportCompletionCacheService<CacheEntry, CacheEntry>), ServiceLayer.Editor), Shared] private sealed class CacheServiceFactory : AbstractImportCompletionCacheServiceFactory<CacheEntry, CacheEntry> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CacheServiceFactory() { } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/TestUtilities/AbstractTypingCommandHandlerTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [UseExportProvider] public abstract class AbstractTypingCommandHandlerTest<TCommandArgs> where TCommandArgs : CommandArgs { internal abstract ICommandHandler<TCommandArgs> GetCommandHandler(TestWorkspace workspace); protected abstract TestWorkspace CreateTestWorkspace(string initialMarkup); protected abstract (TCommandArgs, string insertionText) CreateCommandArgs(ITextView textView, ITextBuffer textBuffer); protected void Verify(string initialMarkup, string expectedMarkup, Action<TestWorkspace> initializeWorkspace = null) { using (var workspace = CreateTestWorkspace(initialMarkup)) { initializeWorkspace?.Invoke(workspace); var testDocument = workspace.Documents.Single(); var view = testDocument.GetTextView(); view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value)); var commandHandler = GetCommandHandler(workspace); var (args, insertionText) = CreateCommandArgs(view, view.TextBuffer); var nextHandler = CreateInsertTextHandler(view, insertionText); if (!commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create())) { nextHandler(); } MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition); Assert.Equal(expectedCode, view.TextSnapshot.GetText()); var caretPosition = view.Caret.Position.BufferPosition.Position; Assert.True(expectedPosition == caretPosition, string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition)); } } protected void VerifyTabs(string initialMarkup, string expectedMarkup) => Verify(ReplaceTabTags(initialMarkup), ReplaceTabTags(expectedMarkup)); private static string ReplaceTabTags(string markup) => markup.Replace("<tab>", "\t"); private static Action CreateInsertTextHandler(ITextView textView, string text) { return () => { var caretPosition = textView.Caret.Position.BufferPosition; var newSpanshot = textView.TextBuffer.Insert(caretPosition, text); textView.Caret.MoveTo(new SnapshotPoint(newSpanshot, (int)caretPosition + text.Length)); }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [UseExportProvider] public abstract class AbstractTypingCommandHandlerTest<TCommandArgs> where TCommandArgs : CommandArgs { internal abstract ICommandHandler<TCommandArgs> GetCommandHandler(TestWorkspace workspace); protected abstract TestWorkspace CreateTestWorkspace(string initialMarkup); protected abstract (TCommandArgs, string insertionText) CreateCommandArgs(ITextView textView, ITextBuffer textBuffer); protected void Verify(string initialMarkup, string expectedMarkup, Action<TestWorkspace> initializeWorkspace = null) { using (var workspace = CreateTestWorkspace(initialMarkup)) { initializeWorkspace?.Invoke(workspace); var testDocument = workspace.Documents.Single(); var view = testDocument.GetTextView(); view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value)); var commandHandler = GetCommandHandler(workspace); var (args, insertionText) = CreateCommandArgs(view, view.TextBuffer); var nextHandler = CreateInsertTextHandler(view, insertionText); if (!commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create())) { nextHandler(); } MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition); Assert.Equal(expectedCode, view.TextSnapshot.GetText()); var caretPosition = view.Caret.Position.BufferPosition.Position; Assert.True(expectedPosition == caretPosition, string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition)); } } protected void VerifyTabs(string initialMarkup, string expectedMarkup) => Verify(ReplaceTabTags(initialMarkup), ReplaceTabTags(expectedMarkup)); private static string ReplaceTabTags(string markup) => markup.Replace("<tab>", "\t"); private static Action CreateInsertTextHandler(ITextView textView, string text) { return () => { var caretPosition = textView.Caret.Position.BufferPosition; var newSpanshot = textView.TextBuffer.Insert(caretPosition, text); textView.Caret.MoveTo(new SnapshotPoint(newSpanshot, (int)caretPosition + text.Length)); }; } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/SourceGeneration/IncrementalWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Wraps an incremental generator in a dummy <see cref="ISourceGenerator"/> interface. /// </summary> /// <remarks> /// Allows us to treat both generator types as ISourceGenerator externally and not change the public API. /// Inside the driver we unwrap and use the actual generator instance. /// </remarks> internal sealed class IncrementalGeneratorWrapper : ISourceGenerator { internal IIncrementalGenerator Generator { get; } public IncrementalGeneratorWrapper(IIncrementalGenerator generator) { this.Generator = generator; } // never used. Just for back compat with loading mechanisim void ISourceGenerator.Execute(GeneratorExecutionContext context) => throw ExceptionUtilities.Unreachable; void ISourceGenerator.Initialize(GeneratorInitializationContext context) => throw 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. using System; using System.Collections.Generic; using System.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Wraps an incremental generator in a dummy <see cref="ISourceGenerator"/> interface. /// </summary> /// <remarks> /// Allows us to treat both generator types as ISourceGenerator externally and not change the public API. /// Inside the driver we unwrap and use the actual generator instance. /// </remarks> internal sealed class IncrementalGeneratorWrapper : ISourceGenerator { internal IIncrementalGenerator Generator { get; } public IncrementalGeneratorWrapper(IIncrementalGenerator generator) { this.Generator = generator; } // never used. Just for back compat with loading mechanisim void ISourceGenerator.Execute(GeneratorExecutionContext context) => throw ExceptionUtilities.Unreachable; void ISourceGenerator.Initialize(GeneratorInitializationContext context) => throw ExceptionUtilities.Unreachable; } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Scripting/Core/Hosting/ObjectFormatter/CommonObjectFormatter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Globalization; using System.Reflection; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using static Microsoft.CodeAnalysis.Scripting.Hosting.ObjectFormatterHelpers; namespace Microsoft.CodeAnalysis.Scripting.Hosting { /// <summary> /// Object pretty printer. /// </summary> internal abstract partial class CommonObjectFormatter : ObjectFormatter { public override string FormatObject(object obj, PrintOptions options) { if (options == null) { // We could easily recover by using default options, but it makes // more sense for the host to choose the defaults so we'll require // that options be passed. throw new ArgumentNullException(nameof(options)); } var visitor = new Visitor(this, GetInternalBuilderOptions(options), GetPrimitiveOptions(options), GetTypeNameOptions(options), options.MemberDisplayFormat); return visitor.FormatObject(obj); } protected virtual MemberFilter Filter { get; } = new CommonMemberFilter(); protected abstract CommonTypeNameFormatter TypeNameFormatter { get; } protected abstract CommonPrimitiveFormatter PrimitiveFormatter { get; } protected virtual BuilderOptions GetInternalBuilderOptions(PrintOptions printOptions) => new BuilderOptions( indentation: " ", newLine: Environment.NewLine, ellipsis: printOptions.Ellipsis, maximumLineLength: int.MaxValue, maximumOutputLength: printOptions.MaximumOutputLength); protected virtual CommonPrimitiveFormatterOptions GetPrimitiveOptions(PrintOptions printOptions) => new CommonPrimitiveFormatterOptions( numberRadix: printOptions.NumberRadix, includeCodePoints: false, quoteStringsAndCharacters: true, escapeNonPrintableCharacters: printOptions.EscapeNonPrintableCharacters, cultureInfo: CultureInfo.CurrentUICulture); protected virtual CommonTypeNameFormatterOptions GetTypeNameOptions(PrintOptions printOptions) => new CommonTypeNameFormatterOptions( arrayBoundRadix: printOptions.NumberRadix, showNamespaces: false); public override string FormatException(Exception e) { if (e == null) { throw new ArgumentNullException(nameof(e)); } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(e.GetType()); builder.Append(": "); builder.Append(e.Message); builder.Append(Environment.NewLine); var trace = new StackTrace(e, fNeedFileInfo: true); foreach (var frame in trace.GetFrames()) { if (!Filter.Include(frame)) { continue; } var method = frame.GetMethod(); var methodDisplay = FormatMethodSignature(method); if (methodDisplay == null) { continue; } builder.Append(" + "); builder.Append(methodDisplay); var fileName = frame.GetFileName(); if (fileName != null) { builder.Append(string.Format(CultureInfo.CurrentUICulture, ScriptingResources.AtFileLine, fileName, frame.GetFileLineNumber())); } builder.AppendLine(); } return pooled.ToStringAndFree(); } /// <summary> /// Returns a method signature display string. Used to display stack frames. /// </summary> /// <returns>Null if the method is a compiler generated method that shouldn't be displayed to the user.</returns> protected internal virtual string FormatMethodSignature(MethodBase method) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; var declaringType = method.DeclaringType; var options = new CommonTypeNameFormatterOptions(arrayBoundRadix: NumberRadixDecimal, showNamespaces: true); builder.Append(TypeNameFormatter.FormatTypeName(declaringType, options)); builder.Append('.'); builder.Append(method.Name); if (method.IsGenericMethod) { builder.Append(TypeNameFormatter.FormatTypeArguments(method.GetGenericArguments(), options)); } builder.Append('('); bool first = true; foreach (var parameter in method.GetParameters()) { if (first) { first = false; } else { builder.Append(", "); } if (parameter.ParameterType.IsByRef) { builder.Append(FormatRefKind(parameter)); builder.Append(' '); builder.Append(TypeNameFormatter.FormatTypeName(parameter.ParameterType.GetElementType(), options)); } else { builder.Append(TypeNameFormatter.FormatTypeName(parameter.ParameterType, options)); } } builder.Append(')'); return pooled.ToStringAndFree(); } protected abstract string FormatRefKind(ParameterInfo parameter); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Globalization; using System.Reflection; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using static Microsoft.CodeAnalysis.Scripting.Hosting.ObjectFormatterHelpers; namespace Microsoft.CodeAnalysis.Scripting.Hosting { /// <summary> /// Object pretty printer. /// </summary> internal abstract partial class CommonObjectFormatter : ObjectFormatter { public override string FormatObject(object obj, PrintOptions options) { if (options == null) { // We could easily recover by using default options, but it makes // more sense for the host to choose the defaults so we'll require // that options be passed. throw new ArgumentNullException(nameof(options)); } var visitor = new Visitor(this, GetInternalBuilderOptions(options), GetPrimitiveOptions(options), GetTypeNameOptions(options), options.MemberDisplayFormat); return visitor.FormatObject(obj); } protected virtual MemberFilter Filter { get; } = new CommonMemberFilter(); protected abstract CommonTypeNameFormatter TypeNameFormatter { get; } protected abstract CommonPrimitiveFormatter PrimitiveFormatter { get; } protected virtual BuilderOptions GetInternalBuilderOptions(PrintOptions printOptions) => new BuilderOptions( indentation: " ", newLine: Environment.NewLine, ellipsis: printOptions.Ellipsis, maximumLineLength: int.MaxValue, maximumOutputLength: printOptions.MaximumOutputLength); protected virtual CommonPrimitiveFormatterOptions GetPrimitiveOptions(PrintOptions printOptions) => new CommonPrimitiveFormatterOptions( numberRadix: printOptions.NumberRadix, includeCodePoints: false, quoteStringsAndCharacters: true, escapeNonPrintableCharacters: printOptions.EscapeNonPrintableCharacters, cultureInfo: CultureInfo.CurrentUICulture); protected virtual CommonTypeNameFormatterOptions GetTypeNameOptions(PrintOptions printOptions) => new CommonTypeNameFormatterOptions( arrayBoundRadix: printOptions.NumberRadix, showNamespaces: false); public override string FormatException(Exception e) { if (e == null) { throw new ArgumentNullException(nameof(e)); } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(e.GetType()); builder.Append(": "); builder.Append(e.Message); builder.Append(Environment.NewLine); var trace = new StackTrace(e, fNeedFileInfo: true); foreach (var frame in trace.GetFrames()) { if (!Filter.Include(frame)) { continue; } var method = frame.GetMethod(); var methodDisplay = FormatMethodSignature(method); if (methodDisplay == null) { continue; } builder.Append(" + "); builder.Append(methodDisplay); var fileName = frame.GetFileName(); if (fileName != null) { builder.Append(string.Format(CultureInfo.CurrentUICulture, ScriptingResources.AtFileLine, fileName, frame.GetFileLineNumber())); } builder.AppendLine(); } return pooled.ToStringAndFree(); } /// <summary> /// Returns a method signature display string. Used to display stack frames. /// </summary> /// <returns>Null if the method is a compiler generated method that shouldn't be displayed to the user.</returns> protected internal virtual string FormatMethodSignature(MethodBase method) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; var declaringType = method.DeclaringType; var options = new CommonTypeNameFormatterOptions(arrayBoundRadix: NumberRadixDecimal, showNamespaces: true); builder.Append(TypeNameFormatter.FormatTypeName(declaringType, options)); builder.Append('.'); builder.Append(method.Name); if (method.IsGenericMethod) { builder.Append(TypeNameFormatter.FormatTypeArguments(method.GetGenericArguments(), options)); } builder.Append('('); bool first = true; foreach (var parameter in method.GetParameters()) { if (first) { first = false; } else { builder.Append(", "); } if (parameter.ParameterType.IsByRef) { builder.Append(FormatRefKind(parameter)); builder.Append(' '); builder.Append(TypeNameFormatter.FormatTypeName(parameter.ParameterType.GetElementType(), options)); } else { builder.Append(TypeNameFormatter.FormatTypeName(parameter.ParameterType, options)); } } builder.Append(')'); return pooled.ToStringAndFree(); } protected abstract string FormatRefKind(ParameterInfo parameter); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Syntax/UsingStatementSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class UsingStatementSyntax { public UsingStatementSyntax Update(SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) => Update(AwaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); public UsingStatementSyntax Update(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) => Update(AttributeLists, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static UsingStatementSyntax UsingStatement(SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) => UsingStatement(awaitKeyword: default, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); public static UsingStatementSyntax UsingStatement(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) => UsingStatement(attributeLists: default, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); public static UsingStatementSyntax UsingStatement(VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, StatementSyntax statement) => UsingStatement(attributeLists: default, declaration, expression, statement); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class UsingStatementSyntax { public UsingStatementSyntax Update(SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) => Update(AwaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); public UsingStatementSyntax Update(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) => Update(AttributeLists, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static UsingStatementSyntax UsingStatement(SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) => UsingStatement(awaitKeyword: default, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); public static UsingStatementSyntax UsingStatement(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) => UsingStatement(attributeLists: default, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); public static UsingStatementSyntax UsingStatement(VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, StatementSyntax statement) => UsingStatement(attributeLists: default, declaration, expression, statement); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.Omit.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ChangeSignature; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddOptionalParameter_ToEmptySignature_CallsiteOmitted() { var markup = @" class C { void M$$() { M(); } }"; var updatedSignature = new[] { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") }; var updatedCode = @" class C { void M(int a = 1) { M(); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddOptionalParameter_AfterRequiredParameter_CallsiteOmitted() { var markup = @" class C { void M$$(int x) { M(1); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(0), AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") }; var updatedCode = @" class C { void M(int x, int a = 1) { M(1); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddOptionalParameter_BeforeOptionalParameter_CallsiteOmitted() { var markup = @" class C { void M$$(int x = 2) { M() M(2); M(x: 2); } }"; var updatedSignature = new[] { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"), new AddedParameterOrExistingIndex(0) }; var updatedCode = @" class C { void M(int a = 1, int x = 2) { M() M(x: 2); M(x: 2); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddOptionalParameter_BeforeExpandedParamsArray_CallsiteOmitted() { var markup = @" class C { void M$$(params int[] p) { M(); M(1); M(1, 2); M(1, 2, 3); } }"; var updatedSignature = new[] { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"), new AddedParameterOrExistingIndex(0) }; var updatedCode = @" class C { void M(int a = 1, params int[] p) { M(); M(p: new int[] { 1 }); M(p: new int[] { 1, 2 }); M(p: new int[] { 1, 2, 3 }); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddOptionalParameterWithOmittedCallsiteToAttributeConstructor() { var markup = @" [Some(1, 2, 4)] class SomeAttribute : System.Attribute { public SomeAttribute$$(int a, int b, int y = 4) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(1), AddedParameterOrExistingIndex.CreateAdded("int", "x", CallSiteKind.Omitted, isRequired: false, defaultValue: "3"), new AddedParameterOrExistingIndex(2)}; var updatedCode = @" [Some(1, 2, y: 4)] class SomeAttribute : System.Attribute { public SomeAttribute(int a, int b, int x = 3, int y = 4) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddOptionalParameter_ToEmptySignature_CallsiteOmitted() { var markup = @" class C { void M$$() { M(); } }"; var updatedSignature = new[] { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") }; var updatedCode = @" class C { void M(int a = 1) { M(); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddOptionalParameter_AfterRequiredParameter_CallsiteOmitted() { var markup = @" class C { void M$$(int x) { M(1); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(0), AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1") }; var updatedCode = @" class C { void M(int x, int a = 1) { M(1); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddOptionalParameter_BeforeOptionalParameter_CallsiteOmitted() { var markup = @" class C { void M$$(int x = 2) { M() M(2); M(x: 2); } }"; var updatedSignature = new[] { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"), new AddedParameterOrExistingIndex(0) }; var updatedCode = @" class C { void M(int a = 1, int x = 2) { M() M(x: 2); M(x: 2); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddOptionalParameter_BeforeExpandedParamsArray_CallsiteOmitted() { var markup = @" class C { void M$$(params int[] p) { M(); M(1); M(1, 2); M(1, 2, 3); } }"; var updatedSignature = new[] { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired: false, defaultValue: "1"), new AddedParameterOrExistingIndex(0) }; var updatedCode = @" class C { void M(int a = 1, params int[] p) { M(); M(p: new int[] { 1 }); M(p: new int[] { 1, 2 }); M(p: new int[] { 1, 2, 3 }); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddOptionalParameterWithOmittedCallsiteToAttributeConstructor() { var markup = @" [Some(1, 2, 4)] class SomeAttribute : System.Attribute { public SomeAttribute$$(int a, int b, int y = 4) { } }"; var permutation = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(1), AddedParameterOrExistingIndex.CreateAdded("int", "x", CallSiteKind.Omitted, isRequired: false, defaultValue: "3"), new AddedParameterOrExistingIndex(2)}; var updatedCode = @" [Some(1, 2, y: 4)] class SomeAttribute : System.Attribute { public SomeAttribute(int a, int b, int x = 3, int y = 4) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/FindReferences/TableEntriesSnapshot.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Windows; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal partial class StreamingFindUsagesPresenter { // Name of the key used to retireve the whole entry object. internal const string SelfKeyName = "self"; private class TableEntriesSnapshot : WpfTableEntriesSnapshotBase { private readonly int _versionNumber; private readonly ImmutableList<Entry> _entries; public TableEntriesSnapshot(ImmutableList<Entry> entries, int versionNumber) { _entries = entries; _versionNumber = versionNumber; } public override int VersionNumber => _versionNumber; public override int Count => _entries.Count; public override int IndexOf(int currentIndex, ITableEntriesSnapshot newSnapshot) { // We only add items to the end of our list, and we never reorder. // As such, any index in us will map to the same index in any newer snapshot. return currentIndex; } public override bool TryGetValue(int index, string keyName, out object? content) { // TableControlEventProcessor.PreprocessNavigate needs to get an entry // to call TryNavigateTo on it. if (keyName == SelfKeyName) { content = _entries[index]; return true; } return _entries[index].TryGetValue(keyName, out content); } public override bool TryCreateColumnContent( int index, string columnName, bool singleColumnView, [NotNullWhen(true)] out FrameworkElement? content) { return this._entries[index].TryCreateColumnContent(columnName, out content); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Windows; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal partial class StreamingFindUsagesPresenter { // Name of the key used to retireve the whole entry object. internal const string SelfKeyName = "self"; private class TableEntriesSnapshot : WpfTableEntriesSnapshotBase { private readonly int _versionNumber; private readonly ImmutableList<Entry> _entries; public TableEntriesSnapshot(ImmutableList<Entry> entries, int versionNumber) { _entries = entries; _versionNumber = versionNumber; } public override int VersionNumber => _versionNumber; public override int Count => _entries.Count; public override int IndexOf(int currentIndex, ITableEntriesSnapshot newSnapshot) { // We only add items to the end of our list, and we never reorder. // As such, any index in us will map to the same index in any newer snapshot. return currentIndex; } public override bool TryGetValue(int index, string keyName, out object? content) { // TableControlEventProcessor.PreprocessNavigate needs to get an entry // to call TryNavigateTo on it. if (keyName == SelfKeyName) { content = _entries[index]; return true; } return _entries[index].TryGetValue(keyName, out content); } public override bool TryCreateColumnContent( int index, string columnName, bool singleColumnView, [NotNullWhen(true)] out FrameworkElement? content) { return this._entries[index].TryCreateColumnContent(columnName, out content); } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingSolutionExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal static class UnitTestingSolutionExtensions { public static int GetWorkspaceVersion(this Solution solution) => solution.WorkspaceVersion; public static async Task<UnitTestingChecksumWrapper> GetChecksumAsync(this Solution solution, CancellationToken cancellationToken) => new UnitTestingChecksumWrapper(await solution.State.GetChecksumAsync(cancellationToken).ConfigureAwait(false)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal static class UnitTestingSolutionExtensions { public static int GetWorkspaceVersion(this Solution solution) => solution.WorkspaceVersion; public static async Task<UnitTestingChecksumWrapper> GetChecksumAsync(this Solution solution, CancellationToken cancellationToken) => new UnitTestingChecksumWrapper(await solution.State.GetChecksumAsync(cancellationToken).ConfigureAwait(false)); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/ConversionOperatorDeclarationStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource { public class ConversionOperatorDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<ConversionOperatorDeclarationSyntax> { protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource; internal override AbstractSyntaxStructureProvider CreateProvider() => new ConversionOperatorDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task NoCommentsOrAttributes() { const string code = @" class C { public static explicit operator $$Goo(byte b); }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithAttributes() { const string code = @" class C { {|hint:{|textspan:[Blah] |}public static explicit operator $$Goo(byte b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAndAttributes() { const string code = @" class C { {|hint:{|textspan:// Summary: // This is a summary. [Blah] |}public static explicit operator $$Goo(byte b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestOperator3() { const string code = @" class C { $${|#0:public static explicit operator C(byte i){|textspan: { }|#0} |} public static explicit operator C(short i) { } }"; await VerifyBlockSpansAsync(code, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: 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.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource { public class ConversionOperatorDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<ConversionOperatorDeclarationSyntax> { protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource; internal override AbstractSyntaxStructureProvider CreateProvider() => new ConversionOperatorDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task NoCommentsOrAttributes() { const string code = @" class C { public static explicit operator $$Goo(byte b); }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithAttributes() { const string code = @" class C { {|hint:{|textspan:[Blah] |}public static explicit operator $$Goo(byte b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAndAttributes() { const string code = @" class C { {|hint:{|textspan:// Summary: // This is a summary. [Blah] |}public static explicit operator $$Goo(byte b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestOperator3() { const string code = @" class C { $${|#0:public static explicit operator C(byte i){|textspan: { }|#0} |} public static explicit operator C(short i) { } }"; await VerifyBlockSpansAsync(code, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ExternKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ExternKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.OverrideKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SealedKeyword, SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.VirtualKeyword, }; private static readonly ISet<SyntaxKind> s_validGlobalModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword, }; private static readonly ISet<SyntaxKind> s_validLocalFunctionModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword }; public ExternKeywordRecommender() : base(SyntaxKind.ExternKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return IsExternAliasContext(context) || (context.IsGlobalStatementContext && syntaxTree.IsScript()) || syntaxTree.IsGlobalMemberDeclarationContext(position, s_validGlobalModifiers, cancellationToken) || context.IsMemberDeclarationContext( validModifiers: s_validModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken) || context.SyntaxTree.IsLocalFunctionDeclarationContext(position, s_validLocalFunctionModifiers, cancellationToken); } private static bool IsExternAliasContext(CSharpSyntaxContext context) { // cases: // root: | // root: e| // extern alias a; // | // extern alias a; // e| // all the above, but inside a namespace. // usings and other constructs *cannot* precede. var token = context.TargetToken; // root: | if (token.Kind() == SyntaxKind.None) { // root namespace return true; } if (token.Kind() == SyntaxKind.OpenBraceToken && token.Parent.IsKind(SyntaxKind.NamespaceDeclaration)) { return true; } // namespace N; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.FileScopedNamespaceDeclaration)) { return true; } // extern alias a; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.ExternAliasDirective)) { return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ExternKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.OverrideKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SealedKeyword, SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.VirtualKeyword, }; private static readonly ISet<SyntaxKind> s_validGlobalModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword, }; private static readonly ISet<SyntaxKind> s_validLocalFunctionModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword }; public ExternKeywordRecommender() : base(SyntaxKind.ExternKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return IsExternAliasContext(context) || (context.IsGlobalStatementContext && syntaxTree.IsScript()) || syntaxTree.IsGlobalMemberDeclarationContext(position, s_validGlobalModifiers, cancellationToken) || context.IsMemberDeclarationContext( validModifiers: s_validModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken) || context.SyntaxTree.IsLocalFunctionDeclarationContext(position, s_validLocalFunctionModifiers, cancellationToken); } private static bool IsExternAliasContext(CSharpSyntaxContext context) { // cases: // root: | // root: e| // extern alias a; // | // extern alias a; // e| // all the above, but inside a namespace. // usings and other constructs *cannot* precede. var token = context.TargetToken; // root: | if (token.Kind() == SyntaxKind.None) { // root namespace return true; } if (token.Kind() == SyntaxKind.OpenBraceToken && token.Parent.IsKind(SyntaxKind.NamespaceDeclaration)) { return true; } // namespace N; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.FileScopedNamespaceDeclaration)) { return true; } // extern alias a; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.ExternAliasDirective)) { return true; } return false; } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/NamespaceKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class NamespaceKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public NamespaceKeywordRecommender() : base(SyntaxKind.NamespaceKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; // namespaces are illegal in interactive code: if (syntaxTree.IsScript()) { return false; } // cases: // root: | // root: n| // extern alias a; // | // extern alias a; // n| // using Goo; // | // using Goo; // n| // using Goo = Bar; // | // using Goo = Bar; // n| // namespace N {} // | // namespace N {} // n| // class C {} // | // class C {} // n| var leftToken = context.LeftToken; var token = context.TargetToken; // root: n| // ns Goo { n| // extern alias a; // n| // using Goo; // n| // using Goo = Bar; // n| // a namespace can't come before usings/externs // a child namespace can't come before usings/externs var nextToken = leftToken.GetNextToken(includeSkipped: true); if (nextToken.IsUsingOrExternKeyword() || (nextToken.Kind() == SyntaxKind.GlobalKeyword && nextToken.GetAncestor<UsingDirectiveSyntax>()?.GlobalKeyword == nextToken)) { return false; } // root: | if (token.Kind() == SyntaxKind.None) { // root namespace var root = syntaxTree.GetRoot(cancellationToken) as CompilationUnitSyntax; if (root.Externs.Count > 0 || root.Usings.Count > 0) { return false; } return true; } if (token.Kind() == SyntaxKind.OpenBraceToken && token.Parent.IsKind(SyntaxKind.NamespaceDeclaration)) { return true; } // extern alias a; // | // using Goo; // | if (token.Kind() == SyntaxKind.SemicolonToken) { if (token.Parent.IsKind(SyntaxKind.ExternAliasDirective, SyntaxKind.UsingDirective) && !token.Parent.Parent.IsKind(SyntaxKind.FileScopedNamespaceDeclaration)) { return true; } } // class C {} // | if (token.Kind() == SyntaxKind.CloseBraceToken) { if (token.Parent is TypeDeclarationSyntax && !(token.Parent.Parent is TypeDeclarationSyntax)) { return true; } else if (token.Parent.IsKind(SyntaxKind.NamespaceDeclaration)) { return true; } } // delegate void D(); // | if (token.Kind() == SyntaxKind.SemicolonToken) { if (token.Parent.IsKind(SyntaxKind.DelegateDeclaration) && !(token.Parent.Parent is TypeDeclarationSyntax)) { return true; } } // [assembly: goo] // | if (token.Kind() == SyntaxKind.CloseBracketToken && token.Parent.IsKind(SyntaxKind.AttributeList) && token.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class NamespaceKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public NamespaceKeywordRecommender() : base(SyntaxKind.NamespaceKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; // namespaces are illegal in interactive code: if (syntaxTree.IsScript()) { return false; } // cases: // root: | // root: n| // extern alias a; // | // extern alias a; // n| // using Goo; // | // using Goo; // n| // using Goo = Bar; // | // using Goo = Bar; // n| // namespace N {} // | // namespace N {} // n| // class C {} // | // class C {} // n| var leftToken = context.LeftToken; var token = context.TargetToken; // root: n| // ns Goo { n| // extern alias a; // n| // using Goo; // n| // using Goo = Bar; // n| // a namespace can't come before usings/externs // a child namespace can't come before usings/externs var nextToken = leftToken.GetNextToken(includeSkipped: true); if (nextToken.IsUsingOrExternKeyword() || (nextToken.Kind() == SyntaxKind.GlobalKeyword && nextToken.GetAncestor<UsingDirectiveSyntax>()?.GlobalKeyword == nextToken)) { return false; } // root: | if (token.Kind() == SyntaxKind.None) { // root namespace var root = syntaxTree.GetRoot(cancellationToken) as CompilationUnitSyntax; if (root.Externs.Count > 0 || root.Usings.Count > 0) { return false; } return true; } if (token.Kind() == SyntaxKind.OpenBraceToken && token.Parent.IsKind(SyntaxKind.NamespaceDeclaration)) { return true; } // extern alias a; // | // using Goo; // | if (token.Kind() == SyntaxKind.SemicolonToken) { if (token.Parent.IsKind(SyntaxKind.ExternAliasDirective, SyntaxKind.UsingDirective) && !token.Parent.Parent.IsKind(SyntaxKind.FileScopedNamespaceDeclaration)) { return true; } } // class C {} // | if (token.Kind() == SyntaxKind.CloseBraceToken) { if (token.Parent is TypeDeclarationSyntax && !(token.Parent.Parent is TypeDeclarationSyntax)) { return true; } else if (token.Parent.IsKind(SyntaxKind.NamespaceDeclaration)) { return true; } } // delegate void D(); // | if (token.Kind() == SyntaxKind.SemicolonToken) { if (token.Parent.IsKind(SyntaxKind.DelegateDeclaration) && !(token.Parent.Parent is TypeDeclarationSyntax)) { return true; } } // [assembly: goo] // | if (token.Kind() == SyntaxKind.CloseBracketToken && token.Parent.IsKind(SyntaxKind.AttributeList) && token.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { return true; } return false; } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/ChangeSignature/AddParameterTests.OptionalParameter.Infer.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.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests Inherits AbstractChangeSignatureTests <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_NoOptions() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$() M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(a As Integer) M(TODO) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleLocal() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$() Dim x = 7 M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(a As Integer) Dim x = 7 M(x) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_MultipleLocals() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$() Dim x = 7 Dim y = 8 M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(a As Integer) Dim x = 7 Dim y = 8 M(y) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleParameter() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$(x As Integer) M(1) End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(0), AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(x As Integer, a As Integer) M(1, x) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleField() As Task Dim markup = <Text><![CDATA[ Class C Dim x As Integer = 7 Sub M$$() M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Dim x As Integer = 7 Sub M(a As Integer) M(x) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleProperty() As Task Dim markup = <Text><![CDATA[ Class C Property X As Integer Sub M$$() M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Property X As Integer Sub M(a As Integer) M(X) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_ImplicitlyConvertable() As Task Dim markup = <Text><![CDATA[ Class B End Class Class D Inherits B End Class Class C Sub M$$() Dim d As D M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("B", "b", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class B End Class Class D Inherits B End Class Class C Sub M(b As B) Dim d As D M(d) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) 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.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests Inherits AbstractChangeSignatureTests <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_NoOptions() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$() M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(a As Integer) M(TODO) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleLocal() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$() Dim x = 7 M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(a As Integer) Dim x = 7 M(x) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_MultipleLocals() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$() Dim x = 7 Dim y = 8 M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(a As Integer) Dim x = 7 Dim y = 8 M(y) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleParameter() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$(x As Integer) M(1) End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(0), AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(x As Integer, a As Integer) M(1, x) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleField() As Task Dim markup = <Text><![CDATA[ Class C Dim x As Integer = 7 Sub M$$() M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Dim x As Integer = 7 Sub M(a As Integer) M(x) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_SingleProperty() As Task Dim markup = <Text><![CDATA[ Class C Property X As Integer Sub M$$() M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class C Property X As Integer Sub M(a As Integer) M(X) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_CallsiteInferred_ImplicitlyConvertable() As Task Dim markup = <Text><![CDATA[ Class B End Class Class D Inherits B End Class Class C Sub M$$() Dim d As D M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature = { AddedParameterOrExistingIndex.CreateAdded("B", "b", CallSiteKind.Inferred)} Dim updatedCode = <Text><![CDATA[ Class B End Class Class D Inherits B End Class Class C Sub M(b As B) Dim d As D M(d) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function End Class End Namespace
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/VisualBasicResultProviderTestBase.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Reflection Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.VisualStudio.Debugger.ComponentInterfaces Imports Microsoft.VisualStudio.Debugger.Evaluation Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public MustInherit Class VisualBasicResultProviderTestBase : Inherits ResultProviderTestBase Public Sub New() MyClass.New(New VisualBasicFormatter()) End Sub Private Sub New(formatter As VisualBasicFormatter) MyClass.New(New DkmInspectionSession(ImmutableArray.Create(Of IDkmClrFormatter)(formatter), ImmutableArray.Create(Of IDkmClrResultProvider)(New VisualBasicResultProvider(formatter, formatter)))) End Sub Private Sub New(inspectionSession As DkmInspectionSession) MyBase.New(inspectionSession, CreateDkmInspectionContext(inspectionSession, DkmEvaluationFlags.None, radix:=10)) End Sub Protected Shared Function GetAssembly(source As String) As Assembly Dim comp = CompilationUtils.CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseDll) Return ReflectionUtilities.Load(comp.EmitToArray()) End Function Protected Shared Function GetAssemblyFromIL(ilSource As String) As Assembly Dim ilImage As ImmutableArray(Of Byte) = Nothing Dim comp = CompilationUtils.CreateCompilationWithCustomILSource(sources:=<compilation/>, ilSource:=ilSource, options:=TestOptions.ReleaseDll, ilImage:=ilImage) Return ReflectionUtilities.Load(ilImage) End Function Protected Shared Function PointerToString(pointer As IntPtr) As String If Environment.Is64BitProcess Then Return String.Format("&H{0:X16}", pointer.ToInt64()) Else Return String.Format("&H{0:X8}", pointer.ToInt32()) End If End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Reflection Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.VisualStudio.Debugger.ComponentInterfaces Imports Microsoft.VisualStudio.Debugger.Evaluation Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public MustInherit Class VisualBasicResultProviderTestBase : Inherits ResultProviderTestBase Public Sub New() MyClass.New(New VisualBasicFormatter()) End Sub Private Sub New(formatter As VisualBasicFormatter) MyClass.New(New DkmInspectionSession(ImmutableArray.Create(Of IDkmClrFormatter)(formatter), ImmutableArray.Create(Of IDkmClrResultProvider)(New VisualBasicResultProvider(formatter, formatter)))) End Sub Private Sub New(inspectionSession As DkmInspectionSession) MyBase.New(inspectionSession, CreateDkmInspectionContext(inspectionSession, DkmEvaluationFlags.None, radix:=10)) End Sub Protected Shared Function GetAssembly(source As String) As Assembly Dim comp = CompilationUtils.CreateCompilationWithMscorlib40({source}, options:=TestOptions.ReleaseDll) Return ReflectionUtilities.Load(comp.EmitToArray()) End Function Protected Shared Function GetAssemblyFromIL(ilSource As String) As Assembly Dim ilImage As ImmutableArray(Of Byte) = Nothing Dim comp = CompilationUtils.CreateCompilationWithCustomILSource(sources:=<compilation/>, ilSource:=ilSource, options:=TestOptions.ReleaseDll, ilImage:=ilImage) Return ReflectionUtilities.Load(ilImage) End Function Protected Shared Function PointerToString(pointer As IntPtr) As String If Environment.Is64BitProcess Then Return String.Format("&H{0:X16}", pointer.ToInt64()) Else Return String.Format("&H{0:X8}", pointer.ToInt32()) End If End Function End Class End Namespace
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./scripts/all-ci-times.xlsx
PK!uCc[Content_Types].xml (ĖN0EHC-J\@5ec H{DulBMHl<<\{2Ln׵N౲&gو%`U1f a@6vz~6y8 pZ`fzRX_@~Ɲs1>& ih4trX<։,NlX9J@NҨ_%d`Y9 $4Oqϴ5RDM6Zk~.mQTv CA(,B8f̗=8y.6Ҭ/ cO>wVD ǰрC?"ƒz *tp?P^ =$ycREn.moc\Ym=1y_=>1O_v?/:*WlSGBCrW&Rك+P;<WL?PK!U0#L _rels/.rels (MO0 HݐBKwAH!T~I$ݿ'TG~<!4;#wqu*&rFqvGJy(v*K#FD.W =ZMYbBS7ϛז ?9Lҙsbgٮ|l!USh9ibr:"y_dlD|-NR"42G%Z4˝y7 ëɂPK!?w U1xl/workbook.xmlUo:~O *_کڲ%RSfiRM1iC},WZ*ÈWLOa RZȊ'k?wRT:1u캚弤DּK&UI սkisMYEnIE;X!L0>)ye: jE{WRnjɲ;Q؂bThxN`zU)Zfݎ+r?=+UNJhj%-si& ~IѺLKj3Oi0~0z҈ x=J!P?ﰖ7;c6Ymbh0\U sjŞP t1+jrԨ"xMCXVJb[jѫgҥK;z0K2 >@@鮢!'dp[1۟q0^0u293d8H0Ψ(f6&ߩB'8}iBqlmܻ|tch{#Tn8! mZHMa?/90&! m(2KYhcF3J UmU1uH5F<K9C{=T<%߂}!A؃@zJVtmvߚ mD,I8x1~A63DpHfyO~ͩilMض~2&va=(̺w Z#/\8|<r|y{hs޺(>-n۟PK!JaGxl/_rels/workbook.xml.rels (j0 ѽqP:{)0Mlc?y6У$41f9#u)(ڛε ^OW 3H./6kNOd@"8R`ÃT[4e>KAsc+EY5iQw~ om4]~ ɉ -i^Yy\YD>qW$KS3b2k T>:3[/%s* }+4?rV PK!&皲Mxl/worksheets/sheet1.xmlYے6}OU $xR}V*3 8\6{Z`@ bƶ:-OzM2O+;ȶSVYE}tOO?p_$,@8+K-$J'?''9EUxrsDQvt BEnpHd/Yr"9F|NeSನr^yvV_kPǧS^DG;QlZ7uSE^dxnwHO-TN`EKH}'XЁIK_>P"o|K" ̱o֛:N~-,S|ln[ErXx#HVԍLRlUUOg|y2q/#1ϿNͤ($L`Vߵogsۋm `0򷟓Uru1D5v8?'ИE[W6/eg5XvkH/ > 7Zn7\Mk6Q Hnxɮ ,mX(a^ѝ ƗjBukuݠVxܩ^ J>rb4%0ZTn`psn{ng :}qAHוݐ;"/HxfOL^Hv&N>xEMQEDKCb^[Cņ ; y<.wsyFT{Dqpy^LwH4`t0!NPpcT)ܩCSgLF sH s5؂9F挥!w̉sҩk †SͧC!FDC87x ]^Zwjz1#se:8TkO]3ISp ǧv[XrF`_qGF8L^H4)/G,K:;< {Q0kQ S!J25<kUYX4176b Sk8T{0Ɖ@8T{ᰀx͑wP gJ XJª=+ j͘@~ ZpHOLp{q|9gC^{OPuz|y 8TD@=g|6ơYKC2|Mߪު]Զx<Kqf/AulV+ yH䟋0X^iQ5Kc7PŇw߁}\4( ֭)Dl|j@!(/m;Aʠ 8YHC|~3U{sG 7=cɹp*p3 .A8`A{šYlC(V8 dmGp8<VF>֞K>`rQ)Ϻ`=\B3V!eg/ 6m' i^7NYտ8b%F;.¶d٭?| m7hʕs$u 2v[[O&Tc~n)%*SiCN/|3rdgdǼq~I 80y^_dҽg!X<~q_PK!uxl/worksheets/sheet2.xmlY[6~x6v,<z}f E'i1$` gyM*+ {uCRlLNULJm/VwV_4@8T s߯4+8e|cfP Bb˒tY$/yz[25̿zΎ-Onq }Vm@]'O柟E?wLy/&4#MyEUjvc/8_z=)aa,F0ށ)K]S0 Ì$ C\R*s<aeS 7]@f[}w)$ާ?+ۃ/#e奏EEt&_>^(݃$];(;Muٿ6/4{zA5{̷_ij0{Ny|ey 1A(KU_mGc}7i &`rHmTg?Jr2xs]10v`Bir{}[}[F@F :T,qj5%6V)U[\][_ [պ)V[wK,օےxH9AAޫY`ZVr68f". `%Nem'*xz& {I8aj6p)OJ;\*|qуc!/v<kky|RqGBN>d̝)1w<Pyak/6N'^Bs}>)q+w;;TK̻3?N .; "wow;kkl1KR(ҷҷCkm7vK+`r*8P>kcT *C~FWBem'j,֞( Q<A89 <N\@xr]zLlbtyq ȻaH'*'Ha3F G#zK>@=EvƘCc!%v1%ciɵu<Ha$7FF" ae7l;kP$wF$wC"rBΫ]!qR퉺9D2HG3f2%,j@AxH2Ր6VᔂB,.B<ir af( !|׊hc, ũ@ .EIe{İ63{}}}(G0 jTnXx<d )䤐`_pR5-Vp~u<`=r঑h&Q8r@(70IEW5 N T1{D.(EIؤJK{s^1<Pa @ >SfYZ0mc w[ O&@ںH(Y=NρU3 n7mʄҮ0npJ^"JZ~XxJSiۣcO١r9w+ۓm)O.8[2?5O=f<؈wEQ 2~JN9Wo4^#PK!N xl/theme/theme1.xmlY͋7? sw5%l$dQV32%9R(Bo=@ $'#$lJZv G~ztҽzG ’_P=ؘ$Ӗk8(4|OHe n ,K۟~rmDlI9*f8&H#ޘ+R#^bP{}2!# J{O1B (W%òBR!a1;{(~h%/V&DYCn2L`|Xsj Z{_\Zҧh4:na PաWU_]נT E A)>\Çfgנ_[K^PkPDIr.jwd A)Q RSLX"7Z2>R$I O(9%o&`T) JU>#02]`XRxbL+7 /={=_*Kn%SSՏ__7'Ŀ˗:/}}O!c&a?0BĒ@v^[ uX<kٺ$Fcvw:ચpLݓ󹉻Бk.J3WRٍe 8SCC=2L%Cr`%R.Cbe mèk=|d#a[ 0~h.QR9D15d2rG&/$Dz)c,K:A ]6Krҹ3=v؍P<sL~&!EwI|;D=CP1ܷ f"j'ete<ص͉3;:ڻSt{>sXa3W"`J+U`ek)r+emgoqx(ߤDJ]8TzM5)0IYgz|]p+~o`_=|j Qk<a ݂\DZl؛6FVω'wws[:(eD ,kzhpsyUs^f^>ekZAj|&O3!ŻBw}ь0Q'j"5,ܔ#-q&?'2ڏ ZCeLTx3&cu+ЭNxNg x)\CJZ=ޭ~TwY(aLfQuQ_B^g^ٙXtXPꗡZFq 0mxEAAfc ΙFz3Pb/3 tSٺqyjuiE-#t00,;͖Yƺ2Obr3kE"'&&S;nj*#4kx#[SvInwaD:\N1{-_- 4m+W>Z@+qt;x2#iQNSp$½:7XX/+r1w`h׼9#:Pvd5O+Oٚ.<O7sig*t; CԲ*nN-rk.yJ}0-2MYNÊQ۴3, O6muF8='?ȝZu@,Jܼfw<zp8RPBo#(Ȕ6`ܓY߼9'-~)lJ-aTRvV\u*`Q\\aEvi.-ͅL_\|q ʠYmvjf=(N:^[ zݰ<# nP7 r[j%e~YJ; +c`)}djPK!Z uB xl/styles.xml\[oF~`Y#pەJ}57 {ؒV=gl<38nsf>mTURcݺ2u-Σb䫱CZE|E?M~aT4D도 ,uoE˕Q8\T8(K 4F&^#\g HOu/*uHy&bZ]^ESPukam~ikr'ݓ%QYTŒ\Q,IF ߆dyi o7"FO0|d,rRiQ BG~ʋg&{K7&HR#;p=Y\_1 d^&x2̒>m ,IQ gggѾ$GrڪV=Io "Du]gF1\z@nL`:a#̟ b¼,s'tjE+Qtٽc5R3'\^LϓAK% ZA MҴ莃LF!qp5PsX[WٲiPi@-V3`h\N3Y-lwSֽ31荇͇Pufº])i$uy5}há:R'F'"ƋMx (0g hx *r(*]adfG@QT9 Euq(*r(*t8Wˤr(*vl2<iEn{ۣ5a/UxI`VbW~b B%=-pUa{нFX'I„aƮE|6;v9p=_ol:ŋd[>?p#^Fk'9FZrpbG ]Țz6r#lHȍEb7^8IwGg0<9fߟ'1]fj㇮"%7B7Ip#ƛOhZpkj4*G7.hMd34--{}`.clx&e@oRi,!є8v|&<iEa#Bo:ӎ1}#X >~{`</Jϔv;@xRON `BX42 @WXy`abkp%rAh &_d[\37GXUbLc.bUg%]ЁyeX\"qTZPG ʯqj7(<zr!ī AWj 5*Ϗȑng G[U~ɠ>Aڪ$GVy2O>?: aZO)>Iy~T.wPޜm-A%i{{zlzbHuIi7Q=[06‰IRُ>@G M[#aAk, E\,@h0qXc5 gcAipXP 4X=I߻Hg 2zX,X9,0\,G,|.# \,G,\6.f~I09IrbqHrbq&bq+'x,G1Oybq}IeFoK2FaHFaQYHFaJFa+Uj3Eﺒޝ] cK^6) odJHLc=i3˨ vyHY{I\D(  okBu&L;D`m ߣ= bR |i#$R,2_)^=rxCʰߋ%{|ZSrx}EI!i˞J\Xxh7r7i LGBr%޻#,s-}#M[;3%~ܻ&%/:+}\5^ 1wb5bx͗ ڦLwӁ{ؽ9\'z7ylz{m^ Fr^/c忱sc;է-ڼ7o<i~8 <˾;/8ݽ7oUyT޻&II.BYbtPK!xl/sharedStrings.xmlSQK0~%ڹ)v@b{.:m:}*ei7p-'Vx|\Xa 1.2"NB.R.j*M(:-`Xg[:PlR49Pţ^zP"y,֠br 2cwt1 Y('k}IceIN^ٶrЏ kJ>^I1c;K٦Oԡ9oj;DЀ73UO=m:4NvEH5-cZc.d;(Hέw%|o0)08 L4q$+c>l׼4w PK!8w/xl/drawings/drawing1.xmlTn0`N IQJ^Uv2&;$Uw_ۘ&[0|Ͱ= =8P!;r(#.~"o TոJx[|:";ʭLs*|_X2}p1`b5Q kR tx h,lfKkFZ.FU#0Jr h4E6'{#G'݅V[kx9\t+^"<h|>FxOyxv <P0`"x][ y8< 9 `+ev={EWͼB%&6Ur(^VQ0͈X'nݡyJިϛ#t=+a[vm ^nP{e\xIYͽu<<7Z~mV1n*vD<\g-4Xv^ƞGgpʡޭ`6/@F%jrr9['nc{шSA2+9"lDr#[NԸv&d%"3'бvQeE8NcML}X?*PK!ܟ ^Nxl/charts/chart1.xml\o8~> Y[FE"Eq}iw2W%*.KKqm;FbQj8gi2$ep@(`T󇃊l<#R =_^F@%Y5ѨI+=/Hyb r4/T&#0d(+ q]"$dTpQS@u-Bniު12գ<T2䌚V'Cc8b ΖdSQXu6'0/3i4>J()3*3 \Ky;I<E]hnILox/<y >/u\`!{%0?2eBc=MBDa֎r8If8`i=<74 ?2_,|(eNY' "eE~%Q@ßE_ I.Ġ _KK2,b-EH6qRSt~QC#pS}Gmqb>f0ذ+ rY~ @7?>Ib64 O<$O$l0)5$u621:o_,DGP:nldzS؁?LKQq#R(HQqy ,6fWxcz0ɴ(flQN%gMߤśKUEu2(khGjwTQ 9|0!4L/ ٜi R<AD Ylb=1֛-%d }SQ6v`pJVЧv3j$)l'v1! Dc9INJ4sLe !I,-g OP 2.qyI6)l8_iu^Ή\$FXd(;6\ _bzb ar.t</4UrɇL]Te₳ԌǏ8c;x)g=)sK s"|mqBP Pu0 鱉 q2?=Uu6!zEdJ"hC. siR]мgj{r"wes'ڐG0/wݓdvAoV= v[zL[6XP⻛ΑֹBzo⬾D)$Iq(@K}3pcHi:t2{vR*EZ<2"|@lɤpuQV`kl 7Wqa>'4W7I<㥷s=f`șUZ.3,uG6Z'ZOUJOēd5)mwǫl99mo ay<YMylcv0um;:Wנ&˶Md.z'ZwM&us,P>j ISBY%Dahk=l#N<sbXagk=ޫ)vk!Y&M#W O 쩣v,˚"Ȓ@ vӏ{4n~~,%<Ћ]_ (f b1c"9uwofIX @ YB/Ý0,Lt;{լSRn-@`TlzU[Uu,iwju` 3M;[*[ZӞBZo+B}ϳS<L\|bmdƌf= _M0.w~rst̍]ovq㑆󰦾džfG^/&=n|!lwIK^g[>b-Eپ3kƖ9[ 49 ]1}ْ/Qa\fZ0n a@`v"Hf=n]Al@ $@E$ϴCvEld Wd/Jjhrx&C{kZ`M :dsY!x)ta{7ߔ !EC]7^!ptp-:;:cv!"etX5ԷF2"3Ohݱ A?Als.gI2=7[ALMn{~ϛ|%>0 6r>KZ}dX T'4"-cK[vJ%<]2Lߥ"}ò< 칦 ;mP?+Pi$n(pZ#|"|r=ɒ |g? !5C#p`x 2Gap "[[dOpI?M+G,#p#'&`eLg~* LY&(3loutX?h}@cV&pس 5et'*B Z=ێaZ"5#aDܾ7  mG,؞Z-}ݵDؗ>+c_ \vJEQ8VlH#}7ŧW-ͰmX' #Y# kK\a;Cbfv0R|M`,dyöFxQ{,񭡝TKyC8 -ͭ ^ ș@4kM8m| IMS]EKXI2>iݶ₰mfpr5W&?#yW.;{Ы#V9=سM&T}v̒#@EY!"jë]ةL`l4fLve&67x%;=7vThp#9/[lW{muL!^ąFXLi|)?=bc?C8P}n}Nϗ3~Y"}qUQ/ՑLPALvR88 D|m@S'a煰1QLY5 7QSxŽ? |Q< A%Mb}$A6uȈ}u~r8A=xQ=%NbZro']N!ZBeU)݃Kv*orvw.ZES.QD/ghs,PK!x&xl/charts/style1.xmlZr:~ R`Bfd:rL-ZYD yMwhm$oW b Fq!j |_Scu@ %"}QD)V/gA4xeKDBX !'1YZW~)G ӿF7=L7#ƿ^x(I@+RS.$,VMrϤ !m+fQj_(_b4ҵC}}zI$ߠ¼`M&B.@SV\%O ̸7~E^!3N֊O tfh ,y5U^@FSsLׯ܊Y{0aaHICZوrR?g~WvZ81V < 7 ao#]׻|gkFjpQϝ5oL7%5T&n(,X ڞ)"\@B8$D#&҆z" " ^FM|{ po%Á.Wvuz=q L5Sn(uFN)#z> 7GLSD{ +A8%[oN!kbty:g;.40lUWܹٓ`NBuD0Md nS3HlXB*;ӿWеk| 9@`@9 NZc|@e}!Cͮ SI"tR.}u2}ӾLmbd}޷f󏸆xyG]Fe{ʖłMoK H;Yqߗh<XX]c:v` w q<0BP},7?8"uNcXmBb- ScAsJG⏊Ś~!~Cp$8$o`]fVALϤPyeK&u ')ջSʽӪRn(>#ۮCm:V6Ɗ9kߛT_KvtWV7h<`5M?/P tVpv[:#hNsY,9VcoqH>󏏮su˪Fw&OnPK!nxl/charts/colors1.xmlAn0Eq "¦'Mlb ۥp{PhC!;$/WH&HFkֆ8 >5 y!E2T(x[-/؂ =`vSr HJn@Yښ`jjglO#>Kk†Z1FN+݃SٛkTOj ,[ӣRQq}QOFOy~ t:PK!2W0xl/drawings/drawing2.xmlTn0`N %@ªR1-#MRU}IM7? ˻#sp@@M϶9RBAg$D»ALfN]w"9;mEJo:hh:Q$  tx h 63uC.}SڶNjs7pTq]Xk0Eg%A,σΝǨs,N #OQ(‚е\\>}rXuH(j7zIE9|먼ԱWkɋ2M|<Dɻ kf6LإSV0>oiZoٵYq428+ouL2HVzb짯bTx .[oi\[[=Bt9C[l^J<i-r0N\#açgVrD/,وiG2PԸ v&d$"3'бvQe ۢKzCM&>_PK!Ro cNxl/charts/chart2.xmlko8|F&DK@˴^4b _ZΆXg3>&MzׄqH8[?~~d8$Q8Ĕ8"=$+Qb<%Iq9 ENS.Gs?Ci22 N|Rg/qD&yT$c J̀e\4h^ 6t$;Ӄΐ3Gu DcFP`ؽk7&8[ >FWٜÜf0h|0B3*3X+z;Q<*nInŰϡ2zޓOULIyԏ"/ oL50XdKv9 d|)N8m׏sMbp(FYBďs<wGs'W4%{KS;RŸE>$^x;P!_GS)pA3PQ}2F|x]\xG9Yl/m>3U,VG D@\ G A<>%Ib.'yϧq .$L>A♤J_s:t'ҷltԽmMcY83 q`y#*7nD` ME*A/ 21ar |}$.;U\TIV08%ef/LDxm$nL4&1.J(ϗ^7@oh!ثq!oPdI1g$pbBˆdIN(r+2xik{+rYS,9kLo<V%`BWtNT %)ޓX.x s&=;{80Ġ8hBX&ZL$zREJ>M,./y'Bd ;ZJ.qƗ7d Z-{ߋ3s,|m'q.B` `upJ ]Vq25bBfղ T@RltZa'by!a/,.tYN,\ՍA 0S`vo֔S v렝z[6QQ7݌4׹z⬺ D3Iqh.)X V\3%MSVHHyE#"rgM |*G낮ջ5^^Ņ_t\B% N~]:h7G}Js MӶ};p,߳A8Kk&i}v]d[շ>wjG c!UVRx?taF`:g;mVjN.B-lVJ其2!7zв|# 3q3y <˱Ɩ*vc/WY"/;3C~b9?5S?s)p&7 i =7,YrKvKpǷc7rVol^{L:;,)9k΂"hy~El8p {ܳk<bv5ЭcPv8rYj+ĝ{:`Mh㟞6XٛvԞh{fޕN\k{Z3 ;ߪbg=+z;r_28,wO\~%ٺ!qev#9w2;Sci B떏x얉 H p6̚w"[@hpvu'<[ 㻇wI]-xiZlWnP7sITQj6Г&܅@FhAMdY{OX@.L9$XdKHHg>y uy uCw^H~m|To"F #W38=·`g*Sl;wUmZHEEU=cC 2;b.:Fl }r-t e8M5k;RBnF`yv?չCǷS 廮Ȗ:V5Qu*?4|sنB8=! `~Aj ipgZ.?]s 0CHP]lM?U_|޹0Yn`" tC3 <_E%yS[r jG|G bnv/lDݢ|'\p<>8.1Y,\-SY& w|N?mCZ.Nx0tlǀ؇<Zy[ᡆ.Cϰ]OCp ;\Nۅvƒ!8ӎ|iuu 7! ֛@VJh'ٮij. (Z kPu-|vmt&CD7<;VV];3PZgNWi7;~* j7c>-Íw>0HWy0#5jK\٥JM B1V|SM`Jӆ}C f%l՞~CuqNc^JJ^xUY9 zOS @9NX@Jqt%NYPPik 2}Uu[ 췍 nϻE\*пG*re.>剪z@Cp?*Wk,9lK^e>j䯫ůFJZ@vRe&[4 D "=-*Uvtc94c-aĽK:%3!J_䅲FjАډV[CUJqX!QK<<f5$?qK\U+'8^\%9ip!~>';,ucȰՑM 5o qrEoI)Ѱ< mݒ&&>Ȇu&Q[7N3]9)C49apRX["rpp $-M =g jXWx"/eU!#x9@ PK!x&xl/charts/style2.xmlZr:~ R`Bfd:rL-ZYD yMwhm$oW b Fq!j |_Scu@ %"}QD)V/gA4xeKDBX !'1YZW~)G ӿF7=L7#ƿ^x(I@+RS.$,VMrϤ !m+fQj_(_b4ҵC}}zI$ߠ¼`M&B.@SV\%O ̸7~E^!3N֊O tfh ,y5U^@FSsLׯ܊Y{0aaHICZوrR?g~WvZ81V < 7 ao#]׻|gkFjpQϝ5oL7%5T&n(,X ڞ)"\@B8$D#&҆z" " ^FM|{ po%Á.Wvuz=q L5Sn(uFN)#z> 7GLSD{ +A8%[oN!kbty:g;.40lUWܹٓ`NBuD0Md nS3HlXB*;ӿWеk| 9@`@9 NZc|@e}!Cͮ SI"tR.}u2}ӾLmbd}޷f󏸆xyG]Fe{ʖłMoK H;Yqߗh<XX]c:v` w q<0BP},7?8"uNcXmBb- ScAsJG⏊Ś~!~Cp$8$o`]fVALϤPyeK&u ')ջSʽӪRn(>#ۮCm:V6Ɗ9kߛT_KvtWV7h<`5M?/P tVpv[:#hNsY,9VcoqH>󏏮su˪Fw&OnPK!nxl/charts/colors2.xmlAn0Eq "¦'Mlb ۥp{PhC!;$/WH&HFkֆ8 >5 y!E2T(x[-/؂ =`vSr HJn@Yښ`jjglO#>Kk†Z1FN+݃SٛkTOj ,[ӣRQq}QOFOy~ t:PK!<+#xl/worksheets/_rels/sheet1.xml.rels 0nz^D*dmoo.mgf?Q)R oi4'tGHL z4bOE8ЧvJiB>˗ SS;Rبɀ)NVC<D3v0t6K?,2cGIRȠJ}U_PK!=d+#xl/worksheets/_rels/sheet2.xml.rels 0nR{U,$dۛ xe<EӰra ;$^.Mc`)5 )RlqƔeU@sTY?P1jG>Cv]7{sɥFfAC)sdPu*/PK!D߼%#xl/drawings/_rels/drawing1.xml.rels 0nzЫXIFooӰ;7;E'r k\;^í 8mqr4,PMq c:a,Ų!FR@3tlr:fi hؓgAO_LQB ŧlu3l̀!& ) ,P_7PK!܁xl/charts/_rels/chart1.xml.relsJ0nAD6݃ U dLG3}?s<}>%P`fOcȳ(..RF + FW[HPD5J KYk &'2'Wȳ._݌3`1y겖fayJ)j̞⸾P$~kFs<cෝF+[޽qPK!&ꇻ%#xl/drawings/_rels/drawing2.xml.rels 0n "MzWXIFѷ7EA4N<Y)䝆R YMnp97;u8{GИ>ь)8XØR+vY@.; <AWHUEU)NClrB.PvĘ2@I YPV_ PK!z!xl/charts/_rels/chart2.xml.relsj0 Bhod(sCpk{}(929.o_g)ѱ$x ^])hkZP-.O/`s$+ LJy,5$K*%؅JÉbL:Y'Imo ;:iATwlf4irvvݞ킹YVOybn;Z?wZZX7PK!\w<KidocProps/core.xml (|]K0C}~v2oNbn k>HiDMrNrM *%)@1ͅZUy1'(r*NB;phZ-<Xmz. $3Z{oƎAR R[I}6m pWXz;`l": 96=3 HP,׃ 2rJw&t:9ۋ{`l6i>FȟS_5TfzmGوN;J<!6yRÁG!8*/b<8<_),{.@BO4لa#Ps_PK!S EGdocProps/app.xml (n0EW"AaP <EYjdI3~}) qf y\^ΐjs6狌3&ToKvCJ}ZdYX] EjԩCiJi܊PM0<". |E{2㲧V |9 Xomєn~Xހbڔn *bʵC AC[iQɞ= Vp[# 8%uSdcr]կ " 1j s`0qcW:[Gw@;b瑝_XY}b.D?'ى߭‡vn4Ent*SAާG7\7ozּn Oq*\d&5)^~PK-!uCc[Content_Types].xmlPK-!U0#L _rels/.relsPK-!?w U1xl/workbook.xmlPK-!JaG xl/_rels/workbook.xml.relsPK-!&皲M xl/worksheets/sheet1.xmlPK-!uxl/worksheets/sheet2.xmlPK-!N xl/theme/theme1.xmlPK-!Z uB "xl/styles.xmlPK-!*xl/sharedStrings.xmlPK-!8w/T,xl/drawings/drawing1.xmlPK-!ܟ ^N.xl/charts/chart1.xmlPK-!x&;xl/charts/style1.xmlPK-!nE@xl/charts/colors1.xmlPK-!2W0uAxl/drawings/drawing2.xmlPK-!Ro cNCxl/charts/chart2.xmlPK-!x&|Pxl/charts/style2.xmlPK-!n7Uxl/charts/colors2.xmlPK-!<+#gVxl/worksheets/_rels/sheet1.xml.relsPK-!=d+#eWxl/worksheets/_rels/sheet2.xml.relsPK-!D߼%#cXxl/drawings/_rels/drawing1.xml.relsPK-!܁`Yxl/charts/_rels/chart1.xml.relsPK-!&ꇻ%#oZxl/drawings/_rels/drawing2.xml.relsPK-!z!k[xl/charts/_rels/chart2.xml.relsPK-!\w<Ki{\docProps/core.xmlPK-!S EG^docProps/app.xmlPKa
PK!uCc[Content_Types].xml (ĖN0EHC-J\@5ec H{DulBMHl<<\{2Ln׵N౲&gو%`U1f a@6vz~6y8 pZ`fzRX_@~Ɲs1>& ih4trX<։,NlX9J@NҨ_%d`Y9 $4Oqϴ5RDM6Zk~.mQTv CA(,B8f̗=8y.6Ҭ/ cO>wVD ǰрC?"ƒz *tp?P^ =$ycREn.moc\Ym=1y_=>1O_v?/:*WlSGBCrW&Rك+P;<WL?PK!U0#L _rels/.rels (MO0 HݐBKwAH!T~I$ݿ'TG~<!4;#wqu*&rFqvGJy(v*K#FD.W =ZMYbBS7ϛז ?9Lҙsbgٮ|l!USh9ibr:"y_dlD|-NR"42G%Z4˝y7 ëɂPK!?w U1xl/workbook.xmlUo:~O *_کڲ%RSfiRM1iC},WZ*ÈWLOa RZȊ'k?wRT:1u캚弤DּK&UI սkisMYEnIE;X!L0>)ye: jE{WRnjɲ;Q؂bThxN`zU)Zfݎ+r?=+UNJhj%-si& ~IѺLKj3Oi0~0z҈ x=J!P?ﰖ7;c6Ymbh0\U sjŞP t1+jrԨ"xMCXVJb[jѫgҥK;z0K2 >@@鮢!'dp[1۟q0^0u293d8H0Ψ(f6&ߩB'8}iBqlmܻ|tch{#Tn8! mZHMa?/90&! m(2KYhcF3J UmU1uH5F<K9C{=T<%߂}!A؃@zJVtmvߚ mD,I8x1~A63DpHfyO~ͩilMض~2&va=(̺w Z#/\8|<r|y{hs޺(>-n۟PK!JaGxl/_rels/workbook.xml.rels (j0 ѽqP:{)0Mlc?y6У$41f9#u)(ڛε ^OW 3H./6kNOd@"8R`ÃT[4e>KAsc+EY5iQw~ om4]~ ɉ -i^Yy\YD>qW$KS3b2k T>:3[/%s* }+4?rV PK!&皲Mxl/worksheets/sheet1.xmlYے6}OU $xR}V*3 8\6{Z`@ bƶ:-OzM2O+;ȶSVYE}tOO?p_$,@8+K-$J'?''9EUxrsDQvt BEnpHd/Yr"9F|NeSನr^yvV_kPǧS^DG;QlZ7uSE^dxnwHO-TN`EKH}'XЁIK_>P"o|K" ̱o֛:N~-,S|ln[ErXx#HVԍLRlUUOg|y2q/#1ϿNͤ($L`Vߵogsۋm `0򷟓Uru1D5v8?'ИE[W6/eg5XvkH/ > 7Zn7\Mk6Q Hnxɮ ,mX(a^ѝ ƗjBukuݠVxܩ^ J>rb4%0ZTn`psn{ng :}qAHוݐ;"/HxfOL^Hv&N>xEMQEDKCb^[Cņ ; y<.wsyFT{Dqpy^LwH4`t0!NPpcT)ܩCSgLF sH s5؂9F挥!w̉sҩk †SͧC!FDC87x ]^Zwjz1#se:8TkO]3ISp ǧv[XrF`_qGF8L^H4)/G,K:;< {Q0kQ S!J25<kUYX4176b Sk8T{0Ɖ@8T{ᰀx͑wP gJ XJª=+ j͘@~ ZpHOLp{q|9gC^{OPuz|y 8TD@=g|6ơYKC2|Mߪު]Զx<Kqf/AulV+ yH䟋0X^iQ5Kc7PŇw߁}\4( ֭)Dl|j@!(/m;Aʠ 8YHC|~3U{sG 7=cɹp*p3 .A8`A{šYlC(V8 dmGp8<VF>֞K>`rQ)Ϻ`=\B3V!eg/ 6m' i^7NYտ8b%F;.¶d٭?| m7hʕs$u 2v[[O&Tc~n)%*SiCN/|3rdgdǼq~I 80y^_dҽg!X<~q_PK!uxl/worksheets/sheet2.xmlY[6~x6v,<z}f E'i1$` gyM*+ {uCRlLNULJm/VwV_4@8T s߯4+8e|cfP Bb˒tY$/yz[25̿zΎ-Onq }Vm@]'O柟E?wLy/&4#MyEUjvc/8_z=)aa,F0ށ)K]S0 Ì$ C\R*s<aeS 7]@f[}w)$ާ?+ۃ/#e奏EEt&_>^(݃$];(;Muٿ6/4{zA5{̷_ij0{Ny|ey 1A(KU_mGc}7i &`rHmTg?Jr2xs]10v`Bir{}[}[F@F :T,qj5%6V)U[\][_ [պ)V[wK,օےxH9AAޫY`ZVr68f". `%Nem'*xz& {I8aj6p)OJ;\*|qуc!/v<kky|RqGBN>d̝)1w<Pyak/6N'^Bs}>)q+w;;TK̻3?N .; "wow;kkl1KR(ҷҷCkm7vK+`r*8P>kcT *C~FWBem'j,֞( Q<A89 <N\@xr]zLlbtyq ȻaH'*'Ha3F G#zK>@=EvƘCc!%v1%ciɵu<Ha$7FF" ae7l;kP$wF$wC"rBΫ]!qR퉺9D2HG3f2%,j@AxH2Ր6VᔂB,.B<ir af( !|׊hc, ũ@ .EIe{İ63{}}}(G0 jTnXx<d )䤐`_pR5-Vp~u<`=r঑h&Q8r@(70IEW5 N T1{D.(EIؤJK{s^1<Pa @ >SfYZ0mc w[ O&@ںH(Y=NρU3 n7mʄҮ0npJ^"JZ~XxJSiۣcO١r9w+ۓm)O.8[2?5O=f<؈wEQ 2~JN9Wo4^#PK!N xl/theme/theme1.xmlY͋7? sw5%l$dQV32%9R(Bo=@ $'#$lJZv G~ztҽzG ’_P=ؘ$Ӗk8(4|OHe n ,K۟~rmDlI9*f8&H#ޘ+R#^bP{}2!# J{O1B (W%òBR!a1;{(~h%/V&DYCn2L`|Xsj Z{_\Zҧh4:na PաWU_]נT E A)>\Çfgנ_[K^PkPDIr.jwd A)Q RSLX"7Z2>R$I O(9%o&`T) JU>#02]`XRxbL+7 /={=_*Kn%SSՏ__7'Ŀ˗:/}}O!c&a?0BĒ@v^[ uX<kٺ$Fcvw:ચpLݓ󹉻Бk.J3WRٍe 8SCC=2L%Cr`%R.Cbe mèk=|d#a[ 0~h.QR9D15d2rG&/$Dz)c,K:A ]6Krҹ3=v؍P<sL~&!EwI|;D=CP1ܷ f"j'ete<ص͉3;:ڻSt{>sXa3W"`J+U`ek)r+emgoqx(ߤDJ]8TzM5)0IYgz|]p+~o`_=|j Qk<a ݂\DZl؛6FVω'wws[:(eD ,kzhpsyUs^f^>ekZAj|&O3!ŻBw}ь0Q'j"5,ܔ#-q&?'2ڏ ZCeLTx3&cu+ЭNxNg x)\CJZ=ޭ~TwY(aLfQuQ_B^g^ٙXtXPꗡZFq 0mxEAAfc ΙFz3Pb/3 tSٺqyjuiE-#t00,;͖Yƺ2Obr3kE"'&&S;nj*#4kx#[SvInwaD:\N1{-_- 4m+W>Z@+qt;x2#iQNSp$½:7XX/+r1w`h׼9#:Pvd5O+Oٚ.<O7sig*t; CԲ*nN-rk.yJ}0-2MYNÊQ۴3, O6muF8='?ȝZu@,Jܼfw<zp8RPBo#(Ȕ6`ܓY߼9'-~)lJ-aTRvV\u*`Q\\aEvi.-ͅL_\|q ʠYmvjf=(N:^[ zݰ<# nP7 r[j%e~YJ; +c`)}djPK!Z uB xl/styles.xml\[oF~`Y#pەJ}57 {ؒV=gl<38nsf>mTURcݺ2u-Σb䫱CZE|E?M~aT4D도 ,uoE˕Q8\T8(K 4F&^#\g HOu/*uHy&bZ]^ESPukam~ikr'ݓ%QYTŒ\Q,IF ߆dyi o7"FO0|d,rRiQ BG~ʋg&{K7&HR#;p=Y\_1 d^&x2̒>m ,IQ gggѾ$GrڪV=Io "Du]gF1\z@nL`:a#̟ b¼,s'tjE+Qtٽc5R3'\^LϓAK% ZA MҴ莃LF!qp5PsX[WٲiPi@-V3`h\N3Y-lwSֽ31荇͇Pufº])i$uy5}há:R'F'"ƋMx (0g hx *r(*]adfG@QT9 Euq(*r(*t8Wˤr(*vl2<iEn{ۣ5a/UxI`VbW~b B%=-pUa{нFX'I„aƮE|6;v9p=_ol:ŋd[>?p#^Fk'9FZrpbG ]Țz6r#lHȍEb7^8IwGg0<9fߟ'1]fj㇮"%7B7Ip#ƛOhZpkj4*G7.hMd34--{}`.clx&e@oRi,!є8v|&<iEa#Bo:ӎ1}#X >~{`</Jϔv;@xRON `BX42 @WXy`abkp%rAh &_d[\37GXUbLc.bUg%]ЁyeX\"qTZPG ʯqj7(<zr!ī AWj 5*Ϗȑng G[U~ɠ>Aڪ$GVy2O>?: aZO)>Iy~T.wPޜm-A%i{{zlzbHuIi7Q=[06‰IRُ>@G M[#aAk, E\,@h0qXc5 gcAipXP 4X=I߻Hg 2zX,X9,0\,G,|.# \,G,\6.f~I09IrbqHrbq&bq+'x,G1Oybq}IeFoK2FaHFaQYHFaJFa+Uj3Eﺒޝ] cK^6) odJHLc=i3˨ vyHY{I\D(  okBu&L;D`m ߣ= bR |i#$R,2_)^=rxCʰߋ%{|ZSrx}EI!i˞J\Xxh7r7i LGBr%޻#,s-}#M[;3%~ܻ&%/:+}\5^ 1wb5bx͗ ڦLwӁ{ؽ9\'z7ylz{m^ Fr^/c忱sc;է-ڼ7o<i~8 <˾;/8ݽ7oUyT޻&II.BYbtPK!xl/sharedStrings.xmlSQK0~%ڹ)v@b{.:m:}*ei7p-'Vx|\Xa 1.2"NB.R.j*M(:-`Xg[:PlR49Pţ^zP"y,֠br 2cwt1 Y('k}IceIN^ٶrЏ kJ>^I1c;K٦Oԡ9oj;DЀ73UO=m:4NvEH5-cZc.d;(Hέw%|o0)08 L4q$+c>l׼4w PK!8w/xl/drawings/drawing1.xmlTn0`N IQJ^Uv2&;$Uw_ۘ&[0|Ͱ= =8P!;r(#.~"o TոJx[|:";ʭLs*|_X2}p1`b5Q kR tx h,lfKkFZ.FU#0Jr h4E6'{#G'݅V[kx9\t+^"<h|>FxOyxv <P0`"x][ y8< 9 `+ev={EWͼB%&6Ur(^VQ0͈X'nݡyJިϛ#t=+a[vm ^nP{e\xIYͽu<<7Z~mV1n*vD<\g-4Xv^ƞGgpʡޭ`6/@F%jrr9['nc{шSA2+9"lDr#[NԸv&d%"3'бvQeE8NcML}X?*PK!ܟ ^Nxl/charts/chart1.xml\o8~> Y[FE"Eq}iw2W%*.KKqm;FbQj8gi2$ep@(`T󇃊l<#R =_^F@%Y5ѨI+=/Hyb r4/T&#0d(+ q]"$dTpQS@u-Bniު12գ<T2䌚V'Cc8b ΖdSQXu6'0/3i4>J()3*3 \Ky;I<E]hnILox/<y >/u\`!{%0?2eBc=MBDa֎r8If8`i=<74 ?2_,|(eNY' "eE~%Q@ßE_ I.Ġ _KK2,b-EH6qRSt~QC#pS}Gmqb>f0ذ+ rY~ @7?>Ib64 O<$O$l0)5$u621:o_,DGP:nldzS؁?LKQq#R(HQqy ,6fWxcz0ɴ(flQN%gMߤśKUEu2(khGjwTQ 9|0!4L/ ٜi R<AD Ylb=1֛-%d }SQ6v`pJVЧv3j$)l'v1! Dc9INJ4sLe !I,-g OP 2.qyI6)l8_iu^Ή\$FXd(;6\ _bzb ar.t</4UrɇL]Te₳ԌǏ8c;x)g=)sK s"|mqBP Pu0 鱉 q2?=Uu6!zEdJ"hC. siR]мgj{r"wes'ڐG0/wݓdvAoV= v[zL[6XP⻛ΑֹBzo⬾D)$Iq(@K}3pcHi:t2{vR*EZ<2"|@lɤpuQV`kl 7Wqa>'4W7I<㥷s=f`șUZ.3,uG6Z'ZOUJOēd5)mwǫl99mo ay<YMylcv0um;:Wנ&˶Md.z'ZwM&us,P>j ISBY%Dahk=l#N<sbXagk=ޫ)vk!Y&M#W O 쩣v,˚"Ȓ@ vӏ{4n~~,%<Ћ]_ (f b1c"9uwofIX @ YB/Ý0,Lt;{լSRn-@`TlzU[Uu,iwju` 3M;[*[ZӞBZo+B}ϳS<L\|bmdƌf= _M0.w~rst̍]ovq㑆󰦾džfG^/&=n|!lwIK^g[>b-Eپ3kƖ9[ 49 ]1}ْ/Qa\fZ0n a@`v"Hf=n]Al@ $@E$ϴCvEld Wd/Jjhrx&C{kZ`M :dsY!x)ta{7ߔ !EC]7^!ptp-:;:cv!"etX5ԷF2"3Ohݱ A?Als.gI2=7[ALMn{~ϛ|%>0 6r>KZ}dX T'4"-cK[vJ%<]2Lߥ"}ò< 칦 ;mP?+Pi$n(pZ#|"|r=ɒ |g? !5C#p`x 2Gap "[[dOpI?M+G,#p#'&`eLg~* LY&(3loutX?h}@cV&pس 5et'*B Z=ێaZ"5#aDܾ7  mG,؞Z-}ݵDؗ>+c_ \vJEQ8VlH#}7ŧW-ͰmX' #Y# kK\a;Cbfv0R|M`,dyöFxQ{,񭡝TKyC8 -ͭ ^ ș@4kM8m| IMS]EKXI2>iݶ₰mfpr5W&?#yW.;{Ы#V9=سM&T}v̒#@EY!"jë]ةL`l4fLve&67x%;=7vThp#9/[lW{muL!^ąFXLi|)?=bc?C8P}n}Nϗ3~Y"}qUQ/ՑLPALvR88 D|m@S'a煰1QLY5 7QSxŽ? |Q< A%Mb}$A6uȈ}u~r8A=xQ=%NbZro']N!ZBeU)݃Kv*orvw.ZES.QD/ghs,PK!x&xl/charts/style1.xmlZr:~ R`Bfd:rL-ZYD yMwhm$oW b Fq!j |_Scu@ %"}QD)V/gA4xeKDBX !'1YZW~)G ӿF7=L7#ƿ^x(I@+RS.$,VMrϤ !m+fQj_(_b4ҵC}}zI$ߠ¼`M&B.@SV\%O ̸7~E^!3N֊O tfh ,y5U^@FSsLׯ܊Y{0aaHICZوrR?g~WvZ81V < 7 ao#]׻|gkFjpQϝ5oL7%5T&n(,X ڞ)"\@B8$D#&҆z" " ^FM|{ po%Á.Wvuz=q L5Sn(uFN)#z> 7GLSD{ +A8%[oN!kbty:g;.40lUWܹٓ`NBuD0Md nS3HlXB*;ӿWеk| 9@`@9 NZc|@e}!Cͮ SI"tR.}u2}ӾLmbd}޷f󏸆xyG]Fe{ʖłMoK H;Yqߗh<XX]c:v` w q<0BP},7?8"uNcXmBb- ScAsJG⏊Ś~!~Cp$8$o`]fVALϤPyeK&u ')ջSʽӪRn(>#ۮCm:V6Ɗ9kߛT_KvtWV7h<`5M?/P tVpv[:#hNsY,9VcoqH>󏏮su˪Fw&OnPK!nxl/charts/colors1.xmlAn0Eq "¦'Mlb ۥp{PhC!;$/WH&HFkֆ8 >5 y!E2T(x[-/؂ =`vSr HJn@Yښ`jjglO#>Kk†Z1FN+݃SٛkTOj ,[ӣRQq}QOFOy~ t:PK!2W0xl/drawings/drawing2.xmlTn0`N %@ªR1-#MRU}IM7? ˻#sp@@M϶9RBAg$D»ALfN]w"9;mEJo:hh:Q$  tx h 63uC.}SڶNjs7pTq]Xk0Eg%A,σΝǨs,N #OQ(‚е\\>}rXuH(j7zIE9|먼ԱWkɋ2M|<Dɻ kf6LإSV0>oiZoٵYq428+ouL2HVzb짯bTx .[oi\[[=Bt9C[l^J<i-r0N\#açgVrD/,وiG2PԸ v&d$"3'бvQe ۢKzCM&>_PK!Ro cNxl/charts/chart2.xmlko8|F&DK@˴^4b _ZΆXg3>&MzׄqH8[?~~d8$Q8Ĕ8"=$+Qb<%Iq9 ENS.Gs?Ci22 N|Rg/qD&yT$c J̀e\4h^ 6t$;Ӄΐ3Gu DcFP`ؽk7&8[ >FWٜÜf0h|0B3*3X+z;Q<*nInŰϡ2zޓOULIyԏ"/ oL50XdKv9 d|)N8m׏sMbp(FYBďs<wGs'W4%{KS;RŸE>$^x;P!_GS)pA3PQ}2F|x]\xG9Yl/m>3U,VG D@\ G A<>%Ib.'yϧq .$L>A♤J_s:t'ҷltԽmMcY83 q`y#*7nD` ME*A/ 21ar |}$.;U\TIV08%ef/LDxm$nL4&1.J(ϗ^7@oh!ثq!oPdI1g$pbBˆdIN(r+2xik{+rYS,9kLo<V%`BWtNT %)ޓX.x s&=;{80Ġ8hBX&ZL$zREJ>M,./y'Bd ;ZJ.qƗ7d Z-{ߋ3s,|m'q.B` `upJ ]Vq25bBfղ T@RltZa'by!a/,.tYN,\ՍA 0S`vo֔S v렝z[6QQ7݌4׹z⬺ D3Iqh.)X V\3%MSVHHyE#"rgM |*G낮ջ5^^Ņ_t\B% N~]:h7G}Js MӶ};p,߳A8Kk&i}v]d[շ>wjG c!UVRx?taF`:g;mVjN.B-lVJ其2!7zв|# 3q3y <˱Ɩ*vc/WY"/;3C~b9?5S?s)p&7 i =7,YrKvKpǷc7rVol^{L:;,)9k΂"hy~El8p {ܳk<bv5ЭcPv8rYj+ĝ{:`Mh㟞6XٛvԞh{fޕN\k{Z3 ;ߪbg=+z;r_28,wO\~%ٺ!qev#9w2;Sci B떏x얉 H p6̚w"[@hpvu'<[ 㻇wI]-xiZlWnP7sITQj6Г&܅@FhAMdY{OX@.L9$XdKHHg>y uy uCw^H~m|To"F #W38=·`g*Sl;wUmZHEEU=cC 2;b.:Fl }r-t e8M5k;RBnF`yv?չCǷS 廮Ȗ:V5Qu*?4|sنB8=! `~Aj ipgZ.?]s 0CHP]lM?U_|޹0Yn`" tC3 <_E%yS[r jG|G bnv/lDݢ|'\p<>8.1Y,\-SY& w|N?mCZ.Nx0tlǀ؇<Zy[ᡆ.Cϰ]OCp ;\Nۅvƒ!8ӎ|iuu 7! ֛@VJh'ٮij. (Z kPu-|vmt&CD7<;VV];3PZgNWi7;~* j7c>-Íw>0HWy0#5jK\٥JM B1V|SM`Jӆ}C f%l՞~CuqNc^JJ^xUY9 zOS @9NX@Jqt%NYPPik 2}Uu[ 췍 nϻE\*пG*re.>剪z@Cp?*Wk,9lK^e>j䯫ůFJZ@vRe&[4 D "=-*Uvtc94c-aĽK:%3!J_䅲FjАډV[CUJqX!QK<<f5$?qK\U+'8^\%9ip!~>';,ucȰՑM 5o qrEoI)Ѱ< mݒ&&>Ȇu&Q[7N3]9)C49apRX["rpp $-M =g jXWx"/eU!#x9@ PK!x&xl/charts/style2.xmlZr:~ R`Bfd:rL-ZYD yMwhm$oW b Fq!j |_Scu@ %"}QD)V/gA4xeKDBX !'1YZW~)G ӿF7=L7#ƿ^x(I@+RS.$,VMrϤ !m+fQj_(_b4ҵC}}zI$ߠ¼`M&B.@SV\%O ̸7~E^!3N֊O tfh ,y5U^@FSsLׯ܊Y{0aaHICZوrR?g~WvZ81V < 7 ao#]׻|gkFjpQϝ5oL7%5T&n(,X ڞ)"\@B8$D#&҆z" " ^FM|{ po%Á.Wvuz=q L5Sn(uFN)#z> 7GLSD{ +A8%[oN!kbty:g;.40lUWܹٓ`NBuD0Md nS3HlXB*;ӿWеk| 9@`@9 NZc|@e}!Cͮ SI"tR.}u2}ӾLmbd}޷f󏸆xyG]Fe{ʖłMoK H;Yqߗh<XX]c:v` w q<0BP},7?8"uNcXmBb- ScAsJG⏊Ś~!~Cp$8$o`]fVALϤPyeK&u ')ջSʽӪRn(>#ۮCm:V6Ɗ9kߛT_KvtWV7h<`5M?/P tVpv[:#hNsY,9VcoqH>󏏮su˪Fw&OnPK!nxl/charts/colors2.xmlAn0Eq "¦'Mlb ۥp{PhC!;$/WH&HFkֆ8 >5 y!E2T(x[-/؂ =`vSr HJn@Yښ`jjglO#>Kk†Z1FN+݃SٛkTOj ,[ӣRQq}QOFOy~ t:PK!<+#xl/worksheets/_rels/sheet1.xml.rels 0nz^D*dmoo.mgf?Q)R oi4'tGHL z4bOE8ЧvJiB>˗ SS;Rبɀ)NVC<D3v0t6K?,2cGIRȠJ}U_PK!=d+#xl/worksheets/_rels/sheet2.xml.rels 0nR{U,$dۛ xe<EӰra ;$^.Mc`)5 )RlqƔeU@sTY?P1jG>Cv]7{sɥFfAC)sdPu*/PK!D߼%#xl/drawings/_rels/drawing1.xml.rels 0nzЫXIFooӰ;7;E'r k\;^í 8mqr4,PMq c:a,Ų!FR@3tlr:fi hؓgAO_LQB ŧlu3l̀!& ) ,P_7PK!܁xl/charts/_rels/chart1.xml.relsJ0nAD6݃ U dLG3}?s<}>%P`fOcȳ(..RF + FW[HPD5J KYk &'2'Wȳ._݌3`1y겖fayJ)j̞⸾P$~kFs<cෝF+[޽qPK!&ꇻ%#xl/drawings/_rels/drawing2.xml.rels 0n "MzWXIFѷ7EA4N<Y)䝆R YMnp97;u8{GИ>ь)8XØR+vY@.; <AWHUEU)NClrB.PvĘ2@I YPV_ PK!z!xl/charts/_rels/chart2.xml.relsj0 Bhod(sCpk{}(929.o_g)ѱ$x ^])hkZP-.O/`s$+ LJy,5$K*%؅JÉbL:Y'Imo ;:iATwlf4irvvݞ킹YVOybn;Z?wZZX7PK!\w<KidocProps/core.xml (|]K0C}~v2oNbn k>HiDMrNrM *%)@1ͅZUy1'(r*NB;phZ-<Xmz. $3Z{oƎAR R[I}6m pWXz;`l": 96=3 HP,׃ 2rJw&t:9ۋ{`l6i>FȟS_5TfzmGوN;J<!6yRÁG!8*/b<8<_),{.@BO4لa#Ps_PK!S EGdocProps/app.xml (n0EW"AaP <EYjdI3~}) qf y\^ΐjs6狌3&ToKvCJ}ZdYX] EjԩCiJi܊PM0<". |E{2㲧V |9 Xomєn~Xހbڔn *bʵC AC[iQɞ= Vp[# 8%uSdcr]կ " 1j s`0qcW:[Gw@;b瑝_XY}b.D?'ى߭‡vn4Ent*SAާG7\7ozּn Oq*\d&5)^~PK-!uCc[Content_Types].xmlPK-!U0#L _rels/.relsPK-!?w U1xl/workbook.xmlPK-!JaG xl/_rels/workbook.xml.relsPK-!&皲M xl/worksheets/sheet1.xmlPK-!uxl/worksheets/sheet2.xmlPK-!N xl/theme/theme1.xmlPK-!Z uB "xl/styles.xmlPK-!*xl/sharedStrings.xmlPK-!8w/T,xl/drawings/drawing1.xmlPK-!ܟ ^N.xl/charts/chart1.xmlPK-!x&;xl/charts/style1.xmlPK-!nE@xl/charts/colors1.xmlPK-!2W0uAxl/drawings/drawing2.xmlPK-!Ro cNCxl/charts/chart2.xmlPK-!x&|Pxl/charts/style2.xmlPK-!n7Uxl/charts/colors2.xmlPK-!<+#gVxl/worksheets/_rels/sheet1.xml.relsPK-!=d+#eWxl/worksheets/_rels/sheet2.xml.relsPK-!D߼%#cXxl/drawings/_rels/drawing1.xml.relsPK-!܁`Yxl/charts/_rels/chart1.xml.relsPK-!&ꇻ%#oZxl/drawings/_rels/drawing2.xml.relsPK-!z!k[xl/charts/_rels/chart2.xml.relsPK-!\w<Ki{\docProps/core.xmlPK-!S EG^docProps/app.xmlPKa
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/ExpressionEvaluator/Package/source.extension.vsixmanifest
<?xml version="1.0" encoding="utf-8"?> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="21BAC26D-2935-4D0D-A282-AD647E2592B5" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Roslyn Expression Evaluators</DisplayName> <Description xml:space="preserve">Roslyn Expression Evaluators</Description> <PackageId>Microsoft.CodeAnalysis.ExpressionEvaluator</PackageId> <License>EULA.rtf</License> <AllowClientRole>true</AllowClientRole> </Metadata> <Installation Experimental="true"> <InstallationTarget Id="Microsoft.VisualStudio.Pro" Version="[15.0,]" /> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.VSWinDesktopExpress" /> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.VWDExpress" /> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.VSWinExpress" /> </Installation> <Dependencies> <Dependency Version="[|VisualStudioSetup;GetVsixVersion|,]" DisplayName="Roslyn Language Services" Id="0b5e8ddb-f12d-4131-a71d-77acc26a798f" /> </Dependencies> <Assets> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="BasicExpressionCompiler" Path="|BasicExpressionCompiler;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="BasicResultProvider.Portable" Path="|BasicResultProvider.Portable;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="CSharpExpressionCompiler" Path="|CSharpExpressionCompiler;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="CSharpResultProvider.Portable" Path="|CSharpResultProvider.Portable;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="FunctionResolver" Path="|FunctionResolver;VsdConfigOutputGroup|" /> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" /> </Assets> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[15.0,17.0)" DisplayName="Visual Studio core editor" /> </Prerequisites> </PackageManifest>
<?xml version="1.0" encoding="utf-8"?> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="21BAC26D-2935-4D0D-A282-AD647E2592B5" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Roslyn Expression Evaluators</DisplayName> <Description xml:space="preserve">Roslyn Expression Evaluators</Description> <PackageId>Microsoft.CodeAnalysis.ExpressionEvaluator</PackageId> <License>EULA.rtf</License> <AllowClientRole>true</AllowClientRole> </Metadata> <Installation Experimental="true"> <InstallationTarget Id="Microsoft.VisualStudio.Pro" Version="[15.0,]" /> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.VSWinDesktopExpress" /> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.VWDExpress" /> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.VSWinExpress" /> </Installation> <Dependencies> <Dependency Version="[|VisualStudioSetup;GetVsixVersion|,]" DisplayName="Roslyn Language Services" Id="0b5e8ddb-f12d-4131-a71d-77acc26a798f" /> </Dependencies> <Assets> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="BasicExpressionCompiler" Path="|BasicExpressionCompiler;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="BasicResultProvider.Portable" Path="|BasicResultProvider.Portable;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="CSharpExpressionCompiler" Path="|CSharpExpressionCompiler;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="CSharpResultProvider.Portable" Path="|CSharpResultProvider.Portable;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="FunctionResolver" Path="|FunctionResolver;VsdConfigOutputGroup|" /> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" /> </Assets> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[15.0,17.0)" DisplayName="Visual Studio core editor" /> </Prerequisites> </PackageManifest>
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordBaseEquals.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 System.Linq; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// If the record type is derived from a base record type Base, the record type includes /// a synthesized override of the strongly-typed Equals(Base other). The synthesized /// override is sealed. It is an error if the override is declared explicitly. /// The synthesized override returns Equals((object?)other). /// </summary> internal sealed class SynthesizedRecordBaseEquals : SynthesizedRecordOrdinaryMethod { public SynthesizedRecordBaseEquals(SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.ObjectEquals, hasBody: true, memberOffset, diagnostics) { } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { const DeclarationModifiers result = DeclarationModifiers.Public | DeclarationModifiers.Override | DeclarationModifiers.Sealed; Debug.Assert((result & ~allowedModifiers) == 0); return result; } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var compilation = DeclaringCompilation; var location = ReturnTypeLocation; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Boolean, location, diagnostics)), Parameters: ImmutableArray.Create<ParameterSymbol>( new SourceSimpleParameterSymbol(owner: this, TypeWithAnnotations.Create(ContainingType.BaseTypeNoUseSiteDiagnostics, NullableAnnotation.Annotated), ordinal: 0, RefKind.None, "other", Locations)), IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 1; protected override void MethodChecks(BindingDiagnosticBag diagnostics) { base.MethodChecks(diagnostics); var overridden = OverriddenMethod; if (overridden is object && !overridden.ContainingType.Equals(ContainingType.BaseTypeNoUseSiteDiagnostics, TypeCompareKind.AllIgnoreOptions)) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseMethod, Locations[0], this, ContainingType.BaseTypeNoUseSiteDiagnostics); } } internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.SyntaxNode, compilationState, diagnostics); try { ParameterSymbol parameter = Parameters[0]; if (parameter.Type.IsErrorType()) { F.CloseMethod(F.ThrowNull()); return; } var retExpr = F.Call( F.This(), ContainingType.GetMembersUnordered().OfType<SynthesizedRecordObjEquals>().Single(), F.Convert(F.SpecialType(SpecialType.System_Object), F.Parameter(parameter))); F.CloseMethod(F.Block(F.Return(retExpr))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 System.Linq; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// If the record type is derived from a base record type Base, the record type includes /// a synthesized override of the strongly-typed Equals(Base other). The synthesized /// override is sealed. It is an error if the override is declared explicitly. /// The synthesized override returns Equals((object?)other). /// </summary> internal sealed class SynthesizedRecordBaseEquals : SynthesizedRecordOrdinaryMethod { public SynthesizedRecordBaseEquals(SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.ObjectEquals, hasBody: true, memberOffset, diagnostics) { } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { const DeclarationModifiers result = DeclarationModifiers.Public | DeclarationModifiers.Override | DeclarationModifiers.Sealed; Debug.Assert((result & ~allowedModifiers) == 0); return result; } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var compilation = DeclaringCompilation; var location = ReturnTypeLocation; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Boolean, location, diagnostics)), Parameters: ImmutableArray.Create<ParameterSymbol>( new SourceSimpleParameterSymbol(owner: this, TypeWithAnnotations.Create(ContainingType.BaseTypeNoUseSiteDiagnostics, NullableAnnotation.Annotated), ordinal: 0, RefKind.None, "other", Locations)), IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 1; protected override void MethodChecks(BindingDiagnosticBag diagnostics) { base.MethodChecks(diagnostics); var overridden = OverriddenMethod; if (overridden is object && !overridden.ContainingType.Equals(ContainingType.BaseTypeNoUseSiteDiagnostics, TypeCompareKind.AllIgnoreOptions)) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseMethod, Locations[0], this, ContainingType.BaseTypeNoUseSiteDiagnostics); } } internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.SyntaxNode, compilationState, diagnostics); try { ParameterSymbol parameter = Parameters[0]; if (parameter.Type.IsErrorType()) { F.CloseMethod(F.ThrowNull()); return; } var retExpr = F.Call( F.This(), ContainingType.GetMembersUnordered().OfType<SynthesizedRecordObjEquals>().Single(), F.Convert(F.SpecialType(SpecialType.System_Object), F.Parameter(parameter))); F.CloseMethod(F.Block(F.Return(retExpr))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter : BoundTreeRewriterWithStackGuard { private readonly CSharpCompilation _compilation; private readonly SyntheticBoundNodeFactory _factory; private readonly SynthesizedSubmissionFields _previousSubmissionFields; private readonly bool _allowOmissionOfConditionalCalls; private LoweredDynamicOperationFactory _dynamicFactory; private bool _sawLambdas; private int _availableLocalFunctionOrdinal; private bool _inExpressionLambda; private bool _sawAwait; private bool _sawAwaitInExceptionHandler; private bool _needsSpilling; private readonly BindingDiagnosticBag _diagnostics; private Instrumenter _instrumenter; private readonly BoundStatement _rootStatement; private Dictionary<BoundValuePlaceholderBase, BoundExpression>? _placeholderReplacementMapDoNotUseDirectly; private LocalRewriter( CSharpCompilation compilation, MethodSymbol containingMethod, int containingMethodOrdinal, BoundStatement rootStatement, NamedTypeSymbol? containingType, SyntheticBoundNodeFactory factory, SynthesizedSubmissionFields previousSubmissionFields, bool allowOmissionOfConditionalCalls, BindingDiagnosticBag diagnostics, Instrumenter instrumenter) { _compilation = compilation; _factory = factory; _factory.CurrentFunction = containingMethod; Debug.Assert(TypeSymbol.Equals(factory.CurrentType, (containingType ?? containingMethod.ContainingType), TypeCompareKind.ConsiderEverything2)); _dynamicFactory = new LoweredDynamicOperationFactory(factory, containingMethodOrdinal); _previousSubmissionFields = previousSubmissionFields; _allowOmissionOfConditionalCalls = allowOmissionOfConditionalCalls; _diagnostics = diagnostics; Debug.Assert(instrumenter != null); #if DEBUG // Ensure that only expected kinds of instrumenters are in use _ = RemoveDynamicAnalysisInjectors(instrumenter); #endif _instrumenter = instrumenter; _rootStatement = rootStatement; } /// <summary> /// Lower a block of code by performing local rewritings. /// </summary> public static BoundStatement Rewrite( CSharpCompilation compilation, MethodSymbol method, int methodOrdinal, NamedTypeSymbol containingType, BoundStatement statement, TypeCompilationState compilationState, SynthesizedSubmissionFields previousSubmissionFields, bool allowOmissionOfConditionalCalls, bool instrumentForDynamicAnalysis, ref ImmutableArray<SourceSpan> dynamicAnalysisSpans, DebugDocumentProvider debugDocumentProvider, BindingDiagnosticBag diagnostics, out bool sawLambdas, out bool sawLocalFunctions, out bool sawAwaitInExceptionHandler) { Debug.Assert(statement != null); Debug.Assert(compilationState != null); try { var factory = new SyntheticBoundNodeFactory(method, statement.Syntax, compilationState, diagnostics); DynamicAnalysisInjector? dynamicInstrumenter = instrumentForDynamicAnalysis ? DynamicAnalysisInjector.TryCreate(method, statement, factory, diagnostics, debugDocumentProvider, Instrumenter.NoOp) : null; // We don’t want IL to differ based upon whether we write the PDB to a file/stream or not. // Presence of sequence points in the tree affects final IL, therefore, we always generate them. var localRewriter = new LocalRewriter(compilation, method, methodOrdinal, statement, containingType, factory, previousSubmissionFields, allowOmissionOfConditionalCalls, diagnostics, dynamicInstrumenter != null ? new DebugInfoInjector(dynamicInstrumenter) : DebugInfoInjector.Singleton); statement.CheckLocalsDefined(); var loweredStatement = localRewriter.VisitStatement(statement); Debug.Assert(loweredStatement is { }); loweredStatement.CheckLocalsDefined(); sawLambdas = localRewriter._sawLambdas; sawLocalFunctions = localRewriter._availableLocalFunctionOrdinal != 0; sawAwaitInExceptionHandler = localRewriter._sawAwaitInExceptionHandler; if (localRewriter._needsSpilling && !loweredStatement.HasErrors) { // Move spill sequences to a top-level statement. This handles "lifting" await and the switch expression. var spilledStatement = SpillSequenceSpiller.Rewrite(loweredStatement, method, compilationState, diagnostics); spilledStatement.CheckLocalsDefined(); loweredStatement = spilledStatement; } if (dynamicInstrumenter != null) { dynamicAnalysisSpans = dynamicInstrumenter.DynamicAnalysisSpans; } #if DEBUG LocalRewritingValidator.Validate(loweredStatement); #endif return loweredStatement; } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); sawLambdas = sawLocalFunctions = sawAwaitInExceptionHandler = false; return new BoundBadStatement(statement.Syntax, ImmutableArray.Create<BoundNode>(statement), hasErrors: true); } } private bool Instrument { get { return !_inExpressionLambda; } } private PEModuleBuilder? EmitModule { get { return _factory.CompilationState.ModuleBuilderOpt; } } /// <summary> /// Return the translated node, or null if no code is necessary in the translation. /// </summary> public override BoundNode? Visit(BoundNode? node) { if (node == null) { return node; } Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered"); BoundExpression? expr = node as BoundExpression; if (expr != null) { return VisitExpressionImpl(expr); } return node.Accept(this); } [return: NotNullIfNotNull("node")] private BoundExpression? VisitExpression(BoundExpression? node) { if (node == null) { return node; } Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered"); // https://github.com/dotnet/roslyn/issues/47682 return VisitExpressionImpl(node)!; } private BoundStatement? VisitStatement(BoundStatement? node) { if (node == null) { return node; } Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered"); return (BoundStatement?)node.Accept(this); } private BoundExpression? VisitExpressionImpl(BoundExpression node) { ConstantValue? constantValue = node.ConstantValue; if (constantValue != null) { TypeSymbol? type = node.Type; if (type?.IsNullableType() != true) { return MakeLiteral(node.Syntax, constantValue, type); } } var visited = VisitExpressionWithStackGuard(node); // If you *really* need to change the type, consider using an indirect method // like compound assignment does (extra flag only passed when it is an expression // statement means that this constraint is not violated). // Dynamic type will be erased in emit phase. It is considered equivalent to Object in lowered bound trees. // Unused deconstructions are lowered to produce a return value that isn't a tuple type. Debug.Assert(visited == null || visited.HasErrors || ReferenceEquals(visited.Type, node.Type) || visited.Type is { } && visited.Type.Equals(node.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) || IsUnusedDeconstruction(node)); if (visited != null && visited != node && node.Kind != BoundKind.ImplicitReceiver && node.Kind != BoundKind.ObjectOrCollectionValuePlaceholder) { if (!CanBePassedByReference(node) && CanBePassedByReference(visited)) { visited = RefAccessMustMakeCopy(visited); } } return visited; } private static BoundExpression RefAccessMustMakeCopy(BoundExpression visited) { visited = new BoundPassByCopy( visited.Syntax, visited, type: visited.Type); return visited; } private static bool IsUnusedDeconstruction(BoundExpression node) { return node.Kind == BoundKind.DeconstructionAssignmentOperator && !((BoundDeconstructionAssignmentOperator)node).IsUsed; } public override BoundNode VisitLambda(BoundLambda node) { _sawLambdas = true; var lambda = node.Symbol; CheckRefReadOnlySymbols(lambda); var oldContainingSymbol = _factory.CurrentFunction; var oldInstrumenter = _instrumenter; try { _factory.CurrentFunction = lambda; if (lambda.IsDirectlyExcludedFromCodeCoverage) { _instrumenter = RemoveDynamicAnalysisInjectors(oldInstrumenter); } return base.VisitLambda(node)!; } finally { _factory.CurrentFunction = oldContainingSymbol; _instrumenter = oldInstrumenter; } } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { int localFunctionOrdinal = _availableLocalFunctionOrdinal++; var localFunction = node.Symbol; CheckRefReadOnlySymbols(localFunction); if (_factory.CompilationState.ModuleBuilderOpt is { } moduleBuilder) { var typeParameters = localFunction.TypeParameters; if (typeParameters.Any(typeParameter => typeParameter.HasUnmanagedTypeConstraint)) { moduleBuilder.EnsureIsUnmanagedAttributeExists(); } if (hasReturnTypeOrParameter(localFunction, t => t.ContainsNativeInteger()) || typeParameters.Any(t => t.ConstraintTypesNoUseSiteDiagnostics.Any(t => t.ContainsNativeInteger()))) { moduleBuilder.EnsureNativeIntegerAttributeExists(); } if (_factory.CompilationState.Compilation.ShouldEmitNullableAttributes(localFunction)) { bool constraintsNeedNullableAttribute = typeParameters.Any( typeParameter => ((SourceTypeParameterSymbolBase)typeParameter).ConstraintsNeedNullableAttribute()); if (constraintsNeedNullableAttribute || hasReturnTypeOrParameter(localFunction, t => t.NeedsNullableAttribute())) { moduleBuilder.EnsureNullableAttributeExists(); } } static bool hasReturnTypeOrParameter(LocalFunctionSymbol localFunction, Func<TypeWithAnnotations, bool> predicate) => predicate(localFunction.ReturnTypeWithAnnotations) || localFunction.ParameterTypesWithAnnotations.Any(predicate); } var oldContainingSymbol = _factory.CurrentFunction; var oldInstrumenter = _instrumenter; var oldDynamicFactory = _dynamicFactory; try { _factory.CurrentFunction = localFunction; if (localFunction.IsDirectlyExcludedFromCodeCoverage) { _instrumenter = RemoveDynamicAnalysisInjectors(oldInstrumenter); } if (localFunction.IsGenericMethod) { // Each generic local function gets its own dynamic factory because it // needs its own container to cache dynamic call-sites. That type (the container) "inherits" // local function's type parameters as well as type parameters of all containing methods. _dynamicFactory = new LoweredDynamicOperationFactory(_factory, _dynamicFactory.MethodOrdinal, localFunctionOrdinal); } return base.VisitLocalFunctionStatement(node)!; } finally { _factory.CurrentFunction = oldContainingSymbol; _instrumenter = oldInstrumenter; _dynamicFactory = oldDynamicFactory; } } private static Instrumenter RemoveDynamicAnalysisInjectors(Instrumenter instrumenter) { switch (instrumenter) { case DynamicAnalysisInjector { Previous: var previous }: return RemoveDynamicAnalysisInjectors(previous); case DebugInfoInjector { Previous: var previous } injector: var newPrevious = RemoveDynamicAnalysisInjectors(previous); if ((object)newPrevious == previous) { return injector; } else if ((object)newPrevious == Instrumenter.NoOp) { return DebugInfoInjector.Singleton; } else { return new DebugInfoInjector(previous); } case CompoundInstrumenter compound: // If we hit this it means a new kind of compound instrumenter is in use. // Either add a new case or add an abstraction that lets us // filter out the unwanted injectors in a more generalized way. throw ExceptionUtilities.UnexpectedValue(compound); default: Debug.Assert((object)instrumenter == Instrumenter.NoOp); return instrumenter; } } public override BoundNode VisitDefaultLiteral(BoundDefaultLiteral node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { return PlaceholderReplacement(node); } public override BoundNode VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { if (_inExpressionLambda) { // Expression trees do not include the 'this' argument for members. return node; } return PlaceholderReplacement(node); } public override BoundNode VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) => PlaceholderReplacement(node); public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) => PlaceholderReplacement(node); /// <summary> /// Returns substitution currently used by the rewriter for a placeholder node. /// Each occurrence of the placeholder node is replaced with the node returned. /// Throws if there is no substitution. /// </summary> private BoundExpression PlaceholderReplacement(BoundValuePlaceholderBase placeholder) { Debug.Assert(_placeholderReplacementMapDoNotUseDirectly is { }); var value = _placeholderReplacementMapDoNotUseDirectly[placeholder]; AssertPlaceholderReplacement(placeholder, value); return value; } [Conditional("DEBUG")] private static void AssertPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value) { Debug.Assert(value.Type is { } && value.Type.Equals(placeholder.Type, TypeCompareKind.AllIgnoreOptions)); } /// <summary> /// Sets substitution used by the rewriter for a placeholder node. /// Each occurrence of the placeholder node is replaced with the node returned. /// Throws if there is already a substitution. /// </summary> private void AddPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value) { AssertPlaceholderReplacement(placeholder, value); if (_placeholderReplacementMapDoNotUseDirectly is null) { _placeholderReplacementMapDoNotUseDirectly = new Dictionary<BoundValuePlaceholderBase, BoundExpression>(); } _placeholderReplacementMapDoNotUseDirectly.Add(placeholder, value); } /// <summary> /// Removes substitution currently used by the rewriter for a placeholder node. /// Asserts if there isn't already a substitution. /// </summary> private void RemovePlaceholderReplacement(BoundValuePlaceholderBase placeholder) { Debug.Assert(placeholder is { }); Debug.Assert(_placeholderReplacementMapDoNotUseDirectly is { }); bool removed = _placeholderReplacementMapDoNotUseDirectly.Remove(placeholder); Debug.Assert(removed); } public sealed override BoundNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node) { // OutDeconstructVarPendingInference nodes are only used within initial binding, but don't survive past that stage throw ExceptionUtilities.Unreachable; } public override BoundNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) { // DeconstructionVariablePendingInference nodes are only used within initial binding, but don't survive past that stage throw ExceptionUtilities.Unreachable; } public override BoundNode VisitBadExpression(BoundBadExpression node) { // Cannot recurse into BadExpression children since the BadExpression // may represent being unable to use the child as an lvalue or rvalue. return node; } private static BoundExpression BadExpression(BoundExpression node) { Debug.Assert(node.Type is { }); return BadExpression(node.Syntax, node.Type, ImmutableArray.Create(node)); } private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child) { return BadExpression(syntax, resultType, ImmutableArray.Create(child)); } private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child1, BoundExpression child2) { return BadExpression(syntax, resultType, ImmutableArray.Create(child1, child2)); } private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, ImmutableArray<BoundExpression> children) { return new BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray<Symbol?>.Empty, children, resultType); } private bool TryGetWellKnownTypeMember<TSymbol>(SyntaxNode? syntax, WellKnownMember member, out TSymbol symbol, bool isOptional = false, Location? location = null) where TSymbol : Symbol { Debug.Assert((syntax != null) ^ (location != null)); symbol = (TSymbol)Binder.GetWellKnownTypeMember(_compilation, member, _diagnostics, syntax: syntax, isOptional: isOptional, location: location); return symbol is { }; } /// <summary> /// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing. /// Recommendation: Do not use, use <see cref="TryGetSpecialTypeMethod(SyntaxNode, SpecialMember, out MethodSymbol)"/> instead! /// If used, a unit-test with a missing member is absolutely a must have. /// </summary> private MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember) { return UnsafeGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics); } /// <summary> /// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing. /// Recommendation: Do not use, use <see cref="TryGetSpecialTypeMethod(SyntaxNode, SpecialMember, CSharpCompilation, BindingDiagnosticBag, out MethodSymbol)"/> instead! /// If used, a unit-test with a missing member is absolutely a must have. /// </summary> private static MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { MethodSymbol method; if (TryGetSpecialTypeMethod(syntax, specialMember, compilation, diagnostics, out method)) { return method; } else { MemberDescriptor descriptor = SpecialMembers.GetDescriptor(specialMember); SpecialType type = (SpecialType)descriptor.DeclaringTypeId; TypeSymbol container = compilation.Assembly.GetSpecialType(type); TypeSymbol returnType = new ExtendedErrorTypeSymbol(compilation: compilation, name: descriptor.Name, errorInfo: null, arity: descriptor.Arity); return new ErrorMethodSymbol(container, returnType, "Missing"); } } private bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, out MethodSymbol method) { return TryGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics, out method); } private static bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, BindingDiagnosticBag diagnostics, out MethodSymbol method) { return Binder.TryGetSpecialTypeMember(compilation, specialMember, syntax, diagnostics, out method); } public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node) { Debug.Assert(node.GetTypeFromHandle is null); var sourceType = (BoundTypeExpression?)this.Visit(node.SourceType); Debug.Assert(sourceType is { }); var type = this.VisitType(node.Type); // Emit needs this helper MethodSymbol getTypeFromHandle; if (!TryGetWellKnownTypeMember(node.Syntax, WellKnownMember.System_Type__GetTypeFromHandle, out getTypeFromHandle)) { return new BoundTypeOfOperator(node.Syntax, sourceType, null, type, hasErrors: true); } return node.Update(sourceType, getTypeFromHandle, type); } public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) { Debug.Assert(node.GetTypeFromHandle is null); var operand = this.VisitExpression(node.Operand); var type = this.VisitType(node.Type); // Emit needs this helper MethodSymbol getTypeFromHandle; if (!TryGetWellKnownTypeMember(node.Syntax, WellKnownMember.System_Type__GetTypeFromHandle, out getTypeFromHandle)) { return new BoundRefTypeOperator(node.Syntax, operand, null, type, hasErrors: true); } return node.Update(operand, getTypeFromHandle, type); } public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node) { ImmutableArray<BoundStatement> originalStatements = node.Statements; var statements = ArrayBuilder<BoundStatement?>.GetInstance(node.Statements.Length); foreach (var initializer in originalStatements) { if (IsFieldOrPropertyInitializer(initializer)) { if (initializer.Kind == BoundKind.Block) { var block = (BoundBlock)initializer; var statement = RewriteExpressionStatement((BoundExpressionStatement)block.Statements.Single(), suppressInstrumentation: true); Debug.Assert(statement is { }); statements.Add(block.Update(block.Locals, block.LocalFunctions, ImmutableArray.Create(statement))); } else { statements.Add(RewriteExpressionStatement((BoundExpressionStatement)initializer, suppressInstrumentation: true)); } } else { statements.Add(VisitStatement(initializer)); } } int optimizedInitializers = 0; bool optimize = _compilation.Options.OptimizationLevel == OptimizationLevel.Release; for (int i = 0; i < statements.Count; i++) { var stmt = statements[i]; if (stmt == null || (optimize && IsFieldOrPropertyInitializer(originalStatements[i]) && ShouldOptimizeOutInitializer(stmt))) { optimizedInitializers++; if (_factory.CurrentFunction?.IsStatic == false) { // NOTE: Dev11 removes static initializers if ONLY all of them are optimized out statements[i] = null; } } } ImmutableArray<BoundStatement> rewrittenStatements; if (optimizedInitializers == statements.Count) { // all are optimized away rewrittenStatements = ImmutableArray<BoundStatement>.Empty; statements.Free(); } else { // instrument remaining statements int remaining = 0; for (int i = 0; i < statements.Count; i++) { BoundStatement? rewritten = statements[i]; if (rewritten != null) { if (IsFieldOrPropertyInitializer(originalStatements[i])) { BoundStatement original = originalStatements[i]; if (Instrument && !original.WasCompilerGenerated) { rewritten = _instrumenter.InstrumentFieldOrPropertyInitializer(original, rewritten); } } statements[remaining] = rewritten; remaining++; } } statements.Count = remaining; // trim any trailing nulls rewrittenStatements = statements.ToImmutableAndFree()!; } return new BoundStatementList(node.Syntax, rewrittenStatements, node.HasErrors); } public override BoundNode VisitArrayAccess(BoundArrayAccess node) { // An array access expression can be indexed using any of the following types: // * an integer primitive // * a System.Index // * a System.Range // The last two are only supported on SZArrays. For those cases we need to // lower into the appropriate helper methods. if (node.Indices.Length != 1) { return base.VisitArrayAccess(node)!; } var indexType = VisitType(node.Indices[0].Type); var F = _factory; BoundNode resultExpr; if (TypeSymbol.Equals( indexType, _compilation.GetWellKnownType(WellKnownType.System_Index), TypeCompareKind.ConsiderEverything)) { // array[Index] is treated like a pattern-based System.Index indexing // expression, except that array indexers don't actually exist (they // don't have symbols) var arrayLocal = F.StoreToTemp( VisitExpression(node.Expression), out BoundAssignmentOperator arrayAssign); var indexOffsetExpr = MakePatternIndexOffsetExpression( node.Indices[0], F.ArrayLength(arrayLocal), out _); resultExpr = F.Sequence( ImmutableArray.Create(arrayLocal.LocalSymbol), ImmutableArray.Create<BoundExpression>(arrayAssign), F.ArrayAccess( arrayLocal, ImmutableArray.Create(indexOffsetExpr))); } else if (TypeSymbol.Equals( indexType, _compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything)) { // array[Range] is compiled to: // System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray(array, Range) Debug.Assert(node.Expression.Type is { TypeKind: TypeKind.Array }); var elementType = ((ArrayTypeSymbol)node.Expression.Type).ElementTypeWithAnnotations; resultExpr = F.Call( receiver: null, F.WellKnownMethod(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T) .Construct(ImmutableArray.Create(elementType)), ImmutableArray.Create( VisitExpression(node.Expression), VisitExpression(node.Indices[0]))); } else { resultExpr = base.VisitArrayAccess(node)!; } return resultExpr; } internal static bool IsFieldOrPropertyInitializer(BoundStatement initializer) { var syntax = initializer.Syntax; if (syntax.IsKind(SyntaxKind.Parameter)) { // This is an initialization of a generated property based on record parameter. return true; } if (syntax is ExpressionSyntax { Parent: { } parent } && parent.Kind() == SyntaxKind.EqualsValueClause) // Should be the initial value. { Debug.Assert(parent.Parent is { }); switch (parent.Parent.Kind()) { case SyntaxKind.VariableDeclarator: case SyntaxKind.PropertyDeclaration: switch (initializer.Kind) { case BoundKind.Block: var block = (BoundBlock)initializer; if (block.Statements.Length == 1) { initializer = (BoundStatement)block.Statements.First(); if (initializer.Kind == BoundKind.ExpressionStatement) { goto case BoundKind.ExpressionStatement; } } break; case BoundKind.ExpressionStatement: return ((BoundExpressionStatement)initializer).Expression.Kind == BoundKind.AssignmentOperator; } break; } } return false; } /// <summary> /// Returns true if the initializer is a field initializer which should be optimized out /// </summary> private static bool ShouldOptimizeOutInitializer(BoundStatement initializer) { BoundStatement statement = initializer; if (statement.Kind != BoundKind.ExpressionStatement) { return false; } BoundAssignmentOperator? assignment = ((BoundExpressionStatement)statement).Expression as BoundAssignmentOperator; if (assignment == null) { return false; } Debug.Assert(assignment.Left.Kind == BoundKind.FieldAccess); var lhsField = ((BoundFieldAccess)assignment.Left).FieldSymbol; if (!lhsField.IsStatic && lhsField.ContainingType.IsStructType()) { return false; } BoundExpression rhs = assignment.Right; return rhs.IsDefaultValue(); } // There are three situations in which the language permits passing rvalues by reference. // (technically there are 5, but we can ignore COM and dynamic here, since that results in byval semantics regardless of the parameter ref kind) // // #1: Receiver of a struct/generic method call. // // The language only requires that receivers of method calls must be readable (RValues are ok). // // However the underlying implementation passes receivers of struct methods by reference. // In such situations it may be possible for the call to cause or observe writes to the receiver variable. // As a result it is not valid to replace receiver variable with a reference to it or the other way around. // // Example1: // static int x = 123; // async static Task<string> Test1() // { // // cannot capture "x" by value, since write in M1 is observable // return x.ToString(await M1()); // } // // async static Task<string> M1() // { // x = 42; // await Task.Yield(); // return ""; // } // // Example2: // static int x = 123; // static string Test1() // { // // cannot replace value of "x" with a reference to "x" // // since that would make the method see the mutations in M1(); // return (x + 0).ToString(M1()); // } // // static string M1() // { // x = 42; // return ""; // } // // #2: Ordinary byval argument passed to an "in" parameter. // // The language only requires that ordinary byval arguments must be readable (RValues are ok). // However if the target parameter is an "in" parameter, the underlying implementation passes by reference. // // Example: // static int x = 123; // static void Main(string[] args) // { // // cannot replace value of "x" with a direct reference to x // // since Test will see unexpected changes due to aliasing. // Test(x + 0); // } // // static void Test(in int y) // { // Console.WriteLine(y); // x = 42; // Console.WriteLine(y); // } // // #3: Ordinary byval interpolated string expression passed to a "ref" interpolated string handler value type. // // Interpolated string expressions passed to a builder type are lowered into a handler form. When the handler type // is a value type (struct, or type parameter constrained to struct (though the latter will fail to bind today because // there's no constructor)), the final handler instance type is passed by reference if the parameter is by reference. // // Example: // M($""); // Language lowers this to a sequence of creating CustomHandler, appending all values, and evaluting to the builder // static void M(ref CustomHandler c) { } // // NB: The readonliness is not considered here. // We only care about possible introduction of aliasing. I.E. RValue->LValue change. // Even if we start with a readonly variable, it cannot be lowered into a writeable one, // with one exception - spilling of the value into a local, which is ok. // internal static bool CanBePassedByReference(BoundExpression expr) { if (expr.ConstantValue != null) { return false; } switch (expr.Kind) { case BoundKind.Parameter: case BoundKind.Local: case BoundKind.ArrayAccess: case BoundKind.ThisReference: case BoundKind.PointerIndirectionOperator: case BoundKind.PointerElementAccess: case BoundKind.RefValueOperator: case BoundKind.PseudoVariable: case BoundKind.DiscardExpression: return true; case BoundKind.DeconstructValuePlaceholder: // we will consider that placeholder always represents a temp local // the assumption should be confirmed or changed when https://github.com/dotnet/roslyn/issues/24160 is fixed return true; case BoundKind.InterpolatedStringArgumentPlaceholder: // An argument placeholder is always a reference to some type of temp local, // either representing a user-typed expression that went through this path // itself when it was originally visited, or the trailing out parameter that // is passed by out. return true; case BoundKind.InterpolatedStringHandlerPlaceholder: // A handler placeholder is the receiver of the interpolated string AppendLiteral // or AppendFormatted calls, and should never be defensively copied. return true; case BoundKind.EventAccess: var eventAccess = (BoundEventAccess)expr; if (eventAccess.IsUsableAsField) { if (eventAccess.EventSymbol.IsStatic) return true; Debug.Assert(eventAccess.ReceiverOpt is { }); return CanBePassedByReference(eventAccess.ReceiverOpt); } return false; case BoundKind.FieldAccess: var fieldAccess = (BoundFieldAccess)expr; if (!fieldAccess.FieldSymbol.IsStatic) { Debug.Assert(fieldAccess.ReceiverOpt is { }); return CanBePassedByReference(fieldAccess.ReceiverOpt); } return true; case BoundKind.Sequence: return CanBePassedByReference(((BoundSequence)expr).Value); case BoundKind.AssignmentOperator: return ((BoundAssignmentOperator)expr).IsRef; case BoundKind.ConditionalOperator: return ((BoundConditionalOperator)expr).IsRef; case BoundKind.Call: return ((BoundCall)expr).Method.RefKind != RefKind.None; case BoundKind.PropertyAccess: return ((BoundPropertyAccess)expr).PropertySymbol.RefKind != RefKind.None; case BoundKind.IndexerAccess: return ((BoundIndexerAccess)expr).Indexer.RefKind != RefKind.None; case BoundKind.IndexOrRangePatternIndexerAccess: var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; var refKind = patternIndexer.PatternSymbol switch { PropertySymbol p => p.RefKind, MethodSymbol m => m.RefKind, _ => throw ExceptionUtilities.UnexpectedValue(patternIndexer.PatternSymbol) }; return refKind != RefKind.None; case BoundKind.Conversion: var conversion = ((BoundConversion)expr); return expr is BoundConversion { Conversion: { IsInterpolatedStringHandler: true }, Type: { IsValueType: true } }; } return false; } private void CheckRefReadOnlySymbols(MethodSymbol symbol) { if (symbol.ReturnsByRefReadonly || symbol.Parameters.Any(p => p.RefKind == RefKind.In)) { _factory.CompilationState.ModuleBuilderOpt?.EnsureIsReadOnlyAttributeExists(); } } private CompoundUseSiteInfo<AssemblySymbol> GetNewCompoundUseSiteInfo() { return new CompoundUseSiteInfo<AssemblySymbol>(_diagnostics, _compilation.Assembly); } #if DEBUG /// <summary> /// Note: do not use a static/singleton instance of this type, as it holds state. /// </summary> private sealed class LocalRewritingValidator : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { /// <summary> /// Asserts that no unexpected nodes survived local rewriting. /// </summary> public static void Validate(BoundNode node) { try { new LocalRewritingValidator().Visit(node); } catch (InsufficientExecutionStackException) { // Intentionally ignored to let the overflow get caught in a more crucial visitor } } public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) { Fail(node); return null; } public override BoundNode? VisitUsingStatement(BoundUsingStatement node) { Fail(node); return null; } public override BoundNode? VisitIfStatement(BoundIfStatement node) { Fail(node); return null; } public override BoundNode? VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) { Fail(node); return null; } public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { Fail(node); return null; } public override BoundNode? VisitDisposableValuePlaceholder(BoundDisposableValuePlaceholder node) { Fail(node); return null; } public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { Fail(node); return null; } public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { Fail(node); return null; } private void Fail(BoundNode node) { Debug.Assert(false, $"Bound nodes of kind {node.Kind} should not survive past local rewriting"); } } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter : BoundTreeRewriterWithStackGuard { private readonly CSharpCompilation _compilation; private readonly SyntheticBoundNodeFactory _factory; private readonly SynthesizedSubmissionFields _previousSubmissionFields; private readonly bool _allowOmissionOfConditionalCalls; private LoweredDynamicOperationFactory _dynamicFactory; private bool _sawLambdas; private int _availableLocalFunctionOrdinal; private bool _inExpressionLambda; private bool _sawAwait; private bool _sawAwaitInExceptionHandler; private bool _needsSpilling; private readonly BindingDiagnosticBag _diagnostics; private Instrumenter _instrumenter; private readonly BoundStatement _rootStatement; private Dictionary<BoundValuePlaceholderBase, BoundExpression>? _placeholderReplacementMapDoNotUseDirectly; private LocalRewriter( CSharpCompilation compilation, MethodSymbol containingMethod, int containingMethodOrdinal, BoundStatement rootStatement, NamedTypeSymbol? containingType, SyntheticBoundNodeFactory factory, SynthesizedSubmissionFields previousSubmissionFields, bool allowOmissionOfConditionalCalls, BindingDiagnosticBag diagnostics, Instrumenter instrumenter) { _compilation = compilation; _factory = factory; _factory.CurrentFunction = containingMethod; Debug.Assert(TypeSymbol.Equals(factory.CurrentType, (containingType ?? containingMethod.ContainingType), TypeCompareKind.ConsiderEverything2)); _dynamicFactory = new LoweredDynamicOperationFactory(factory, containingMethodOrdinal); _previousSubmissionFields = previousSubmissionFields; _allowOmissionOfConditionalCalls = allowOmissionOfConditionalCalls; _diagnostics = diagnostics; Debug.Assert(instrumenter != null); #if DEBUG // Ensure that only expected kinds of instrumenters are in use _ = RemoveDynamicAnalysisInjectors(instrumenter); #endif _instrumenter = instrumenter; _rootStatement = rootStatement; } /// <summary> /// Lower a block of code by performing local rewritings. /// </summary> public static BoundStatement Rewrite( CSharpCompilation compilation, MethodSymbol method, int methodOrdinal, NamedTypeSymbol containingType, BoundStatement statement, TypeCompilationState compilationState, SynthesizedSubmissionFields previousSubmissionFields, bool allowOmissionOfConditionalCalls, bool instrumentForDynamicAnalysis, ref ImmutableArray<SourceSpan> dynamicAnalysisSpans, DebugDocumentProvider debugDocumentProvider, BindingDiagnosticBag diagnostics, out bool sawLambdas, out bool sawLocalFunctions, out bool sawAwaitInExceptionHandler) { Debug.Assert(statement != null); Debug.Assert(compilationState != null); try { var factory = new SyntheticBoundNodeFactory(method, statement.Syntax, compilationState, diagnostics); DynamicAnalysisInjector? dynamicInstrumenter = instrumentForDynamicAnalysis ? DynamicAnalysisInjector.TryCreate(method, statement, factory, diagnostics, debugDocumentProvider, Instrumenter.NoOp) : null; // We don’t want IL to differ based upon whether we write the PDB to a file/stream or not. // Presence of sequence points in the tree affects final IL, therefore, we always generate them. var localRewriter = new LocalRewriter(compilation, method, methodOrdinal, statement, containingType, factory, previousSubmissionFields, allowOmissionOfConditionalCalls, diagnostics, dynamicInstrumenter != null ? new DebugInfoInjector(dynamicInstrumenter) : DebugInfoInjector.Singleton); statement.CheckLocalsDefined(); var loweredStatement = localRewriter.VisitStatement(statement); Debug.Assert(loweredStatement is { }); loweredStatement.CheckLocalsDefined(); sawLambdas = localRewriter._sawLambdas; sawLocalFunctions = localRewriter._availableLocalFunctionOrdinal != 0; sawAwaitInExceptionHandler = localRewriter._sawAwaitInExceptionHandler; if (localRewriter._needsSpilling && !loweredStatement.HasErrors) { // Move spill sequences to a top-level statement. This handles "lifting" await and the switch expression. var spilledStatement = SpillSequenceSpiller.Rewrite(loweredStatement, method, compilationState, diagnostics); spilledStatement.CheckLocalsDefined(); loweredStatement = spilledStatement; } if (dynamicInstrumenter != null) { dynamicAnalysisSpans = dynamicInstrumenter.DynamicAnalysisSpans; } #if DEBUG LocalRewritingValidator.Validate(loweredStatement); #endif return loweredStatement; } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); sawLambdas = sawLocalFunctions = sawAwaitInExceptionHandler = false; return new BoundBadStatement(statement.Syntax, ImmutableArray.Create<BoundNode>(statement), hasErrors: true); } } private bool Instrument { get { return !_inExpressionLambda; } } private PEModuleBuilder? EmitModule { get { return _factory.CompilationState.ModuleBuilderOpt; } } /// <summary> /// Return the translated node, or null if no code is necessary in the translation. /// </summary> public override BoundNode? Visit(BoundNode? node) { if (node == null) { return node; } Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered"); BoundExpression? expr = node as BoundExpression; if (expr != null) { return VisitExpressionImpl(expr); } return node.Accept(this); } [return: NotNullIfNotNull("node")] private BoundExpression? VisitExpression(BoundExpression? node) { if (node == null) { return node; } Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered"); // https://github.com/dotnet/roslyn/issues/47682 return VisitExpressionImpl(node)!; } private BoundStatement? VisitStatement(BoundStatement? node) { if (node == null) { return node; } Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered"); return (BoundStatement?)node.Accept(this); } private BoundExpression? VisitExpressionImpl(BoundExpression node) { ConstantValue? constantValue = node.ConstantValue; if (constantValue != null) { TypeSymbol? type = node.Type; if (type?.IsNullableType() != true) { return MakeLiteral(node.Syntax, constantValue, type); } } var visited = VisitExpressionWithStackGuard(node); // If you *really* need to change the type, consider using an indirect method // like compound assignment does (extra flag only passed when it is an expression // statement means that this constraint is not violated). // Dynamic type will be erased in emit phase. It is considered equivalent to Object in lowered bound trees. // Unused deconstructions are lowered to produce a return value that isn't a tuple type. Debug.Assert(visited == null || visited.HasErrors || ReferenceEquals(visited.Type, node.Type) || visited.Type is { } && visited.Type.Equals(node.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) || IsUnusedDeconstruction(node)); if (visited != null && visited != node && node.Kind != BoundKind.ImplicitReceiver && node.Kind != BoundKind.ObjectOrCollectionValuePlaceholder) { if (!CanBePassedByReference(node) && CanBePassedByReference(visited)) { visited = RefAccessMustMakeCopy(visited); } } return visited; } private static BoundExpression RefAccessMustMakeCopy(BoundExpression visited) { visited = new BoundPassByCopy( visited.Syntax, visited, type: visited.Type); return visited; } private static bool IsUnusedDeconstruction(BoundExpression node) { return node.Kind == BoundKind.DeconstructionAssignmentOperator && !((BoundDeconstructionAssignmentOperator)node).IsUsed; } public override BoundNode VisitLambda(BoundLambda node) { _sawLambdas = true; var lambda = node.Symbol; CheckRefReadOnlySymbols(lambda); var oldContainingSymbol = _factory.CurrentFunction; var oldInstrumenter = _instrumenter; try { _factory.CurrentFunction = lambda; if (lambda.IsDirectlyExcludedFromCodeCoverage) { _instrumenter = RemoveDynamicAnalysisInjectors(oldInstrumenter); } return base.VisitLambda(node)!; } finally { _factory.CurrentFunction = oldContainingSymbol; _instrumenter = oldInstrumenter; } } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { int localFunctionOrdinal = _availableLocalFunctionOrdinal++; var localFunction = node.Symbol; CheckRefReadOnlySymbols(localFunction); if (_factory.CompilationState.ModuleBuilderOpt is { } moduleBuilder) { var typeParameters = localFunction.TypeParameters; if (typeParameters.Any(typeParameter => typeParameter.HasUnmanagedTypeConstraint)) { moduleBuilder.EnsureIsUnmanagedAttributeExists(); } if (hasReturnTypeOrParameter(localFunction, t => t.ContainsNativeInteger()) || typeParameters.Any(t => t.ConstraintTypesNoUseSiteDiagnostics.Any(t => t.ContainsNativeInteger()))) { moduleBuilder.EnsureNativeIntegerAttributeExists(); } if (_factory.CompilationState.Compilation.ShouldEmitNullableAttributes(localFunction)) { bool constraintsNeedNullableAttribute = typeParameters.Any( typeParameter => ((SourceTypeParameterSymbolBase)typeParameter).ConstraintsNeedNullableAttribute()); if (constraintsNeedNullableAttribute || hasReturnTypeOrParameter(localFunction, t => t.NeedsNullableAttribute())) { moduleBuilder.EnsureNullableAttributeExists(); } } static bool hasReturnTypeOrParameter(LocalFunctionSymbol localFunction, Func<TypeWithAnnotations, bool> predicate) => predicate(localFunction.ReturnTypeWithAnnotations) || localFunction.ParameterTypesWithAnnotations.Any(predicate); } var oldContainingSymbol = _factory.CurrentFunction; var oldInstrumenter = _instrumenter; var oldDynamicFactory = _dynamicFactory; try { _factory.CurrentFunction = localFunction; if (localFunction.IsDirectlyExcludedFromCodeCoverage) { _instrumenter = RemoveDynamicAnalysisInjectors(oldInstrumenter); } if (localFunction.IsGenericMethod) { // Each generic local function gets its own dynamic factory because it // needs its own container to cache dynamic call-sites. That type (the container) "inherits" // local function's type parameters as well as type parameters of all containing methods. _dynamicFactory = new LoweredDynamicOperationFactory(_factory, _dynamicFactory.MethodOrdinal, localFunctionOrdinal); } return base.VisitLocalFunctionStatement(node)!; } finally { _factory.CurrentFunction = oldContainingSymbol; _instrumenter = oldInstrumenter; _dynamicFactory = oldDynamicFactory; } } private static Instrumenter RemoveDynamicAnalysisInjectors(Instrumenter instrumenter) { switch (instrumenter) { case DynamicAnalysisInjector { Previous: var previous }: return RemoveDynamicAnalysisInjectors(previous); case DebugInfoInjector { Previous: var previous } injector: var newPrevious = RemoveDynamicAnalysisInjectors(previous); if ((object)newPrevious == previous) { return injector; } else if ((object)newPrevious == Instrumenter.NoOp) { return DebugInfoInjector.Singleton; } else { return new DebugInfoInjector(previous); } case CompoundInstrumenter compound: // If we hit this it means a new kind of compound instrumenter is in use. // Either add a new case or add an abstraction that lets us // filter out the unwanted injectors in a more generalized way. throw ExceptionUtilities.UnexpectedValue(compound); default: Debug.Assert((object)instrumenter == Instrumenter.NoOp); return instrumenter; } } public override BoundNode VisitDefaultLiteral(BoundDefaultLiteral node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { return PlaceholderReplacement(node); } public override BoundNode VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { if (_inExpressionLambda) { // Expression trees do not include the 'this' argument for members. return node; } return PlaceholderReplacement(node); } public override BoundNode VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) => PlaceholderReplacement(node); public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) => PlaceholderReplacement(node); /// <summary> /// Returns substitution currently used by the rewriter for a placeholder node. /// Each occurrence of the placeholder node is replaced with the node returned. /// Throws if there is no substitution. /// </summary> private BoundExpression PlaceholderReplacement(BoundValuePlaceholderBase placeholder) { Debug.Assert(_placeholderReplacementMapDoNotUseDirectly is { }); var value = _placeholderReplacementMapDoNotUseDirectly[placeholder]; AssertPlaceholderReplacement(placeholder, value); return value; } [Conditional("DEBUG")] private static void AssertPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value) { Debug.Assert(value.Type is { } && value.Type.Equals(placeholder.Type, TypeCompareKind.AllIgnoreOptions)); } /// <summary> /// Sets substitution used by the rewriter for a placeholder node. /// Each occurrence of the placeholder node is replaced with the node returned. /// Throws if there is already a substitution. /// </summary> private void AddPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value) { AssertPlaceholderReplacement(placeholder, value); if (_placeholderReplacementMapDoNotUseDirectly is null) { _placeholderReplacementMapDoNotUseDirectly = new Dictionary<BoundValuePlaceholderBase, BoundExpression>(); } _placeholderReplacementMapDoNotUseDirectly.Add(placeholder, value); } /// <summary> /// Removes substitution currently used by the rewriter for a placeholder node. /// Asserts if there isn't already a substitution. /// </summary> private void RemovePlaceholderReplacement(BoundValuePlaceholderBase placeholder) { Debug.Assert(placeholder is { }); Debug.Assert(_placeholderReplacementMapDoNotUseDirectly is { }); bool removed = _placeholderReplacementMapDoNotUseDirectly.Remove(placeholder); Debug.Assert(removed); } public sealed override BoundNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node) { // OutDeconstructVarPendingInference nodes are only used within initial binding, but don't survive past that stage throw ExceptionUtilities.Unreachable; } public override BoundNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) { // DeconstructionVariablePendingInference nodes are only used within initial binding, but don't survive past that stage throw ExceptionUtilities.Unreachable; } public override BoundNode VisitBadExpression(BoundBadExpression node) { // Cannot recurse into BadExpression children since the BadExpression // may represent being unable to use the child as an lvalue or rvalue. return node; } private static BoundExpression BadExpression(BoundExpression node) { Debug.Assert(node.Type is { }); return BadExpression(node.Syntax, node.Type, ImmutableArray.Create(node)); } private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child) { return BadExpression(syntax, resultType, ImmutableArray.Create(child)); } private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child1, BoundExpression child2) { return BadExpression(syntax, resultType, ImmutableArray.Create(child1, child2)); } private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, ImmutableArray<BoundExpression> children) { return new BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray<Symbol?>.Empty, children, resultType); } private bool TryGetWellKnownTypeMember<TSymbol>(SyntaxNode? syntax, WellKnownMember member, out TSymbol symbol, bool isOptional = false, Location? location = null) where TSymbol : Symbol { Debug.Assert((syntax != null) ^ (location != null)); symbol = (TSymbol)Binder.GetWellKnownTypeMember(_compilation, member, _diagnostics, syntax: syntax, isOptional: isOptional, location: location); return symbol is { }; } /// <summary> /// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing. /// Recommendation: Do not use, use <see cref="TryGetSpecialTypeMethod(SyntaxNode, SpecialMember, out MethodSymbol)"/> instead! /// If used, a unit-test with a missing member is absolutely a must have. /// </summary> private MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember) { return UnsafeGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics); } /// <summary> /// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing. /// Recommendation: Do not use, use <see cref="TryGetSpecialTypeMethod(SyntaxNode, SpecialMember, CSharpCompilation, BindingDiagnosticBag, out MethodSymbol)"/> instead! /// If used, a unit-test with a missing member is absolutely a must have. /// </summary> private static MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { MethodSymbol method; if (TryGetSpecialTypeMethod(syntax, specialMember, compilation, diagnostics, out method)) { return method; } else { MemberDescriptor descriptor = SpecialMembers.GetDescriptor(specialMember); SpecialType type = (SpecialType)descriptor.DeclaringTypeId; TypeSymbol container = compilation.Assembly.GetSpecialType(type); TypeSymbol returnType = new ExtendedErrorTypeSymbol(compilation: compilation, name: descriptor.Name, errorInfo: null, arity: descriptor.Arity); return new ErrorMethodSymbol(container, returnType, "Missing"); } } private bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, out MethodSymbol method) { return TryGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics, out method); } private static bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, BindingDiagnosticBag diagnostics, out MethodSymbol method) { return Binder.TryGetSpecialTypeMember(compilation, specialMember, syntax, diagnostics, out method); } public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node) { Debug.Assert(node.GetTypeFromHandle is null); var sourceType = (BoundTypeExpression?)this.Visit(node.SourceType); Debug.Assert(sourceType is { }); var type = this.VisitType(node.Type); // Emit needs this helper MethodSymbol getTypeFromHandle; if (!TryGetWellKnownTypeMember(node.Syntax, WellKnownMember.System_Type__GetTypeFromHandle, out getTypeFromHandle)) { return new BoundTypeOfOperator(node.Syntax, sourceType, null, type, hasErrors: true); } return node.Update(sourceType, getTypeFromHandle, type); } public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) { Debug.Assert(node.GetTypeFromHandle is null); var operand = this.VisitExpression(node.Operand); var type = this.VisitType(node.Type); // Emit needs this helper MethodSymbol getTypeFromHandle; if (!TryGetWellKnownTypeMember(node.Syntax, WellKnownMember.System_Type__GetTypeFromHandle, out getTypeFromHandle)) { return new BoundRefTypeOperator(node.Syntax, operand, null, type, hasErrors: true); } return node.Update(operand, getTypeFromHandle, type); } public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node) { ImmutableArray<BoundStatement> originalStatements = node.Statements; var statements = ArrayBuilder<BoundStatement?>.GetInstance(node.Statements.Length); foreach (var initializer in originalStatements) { if (IsFieldOrPropertyInitializer(initializer)) { if (initializer.Kind == BoundKind.Block) { var block = (BoundBlock)initializer; var statement = RewriteExpressionStatement((BoundExpressionStatement)block.Statements.Single(), suppressInstrumentation: true); Debug.Assert(statement is { }); statements.Add(block.Update(block.Locals, block.LocalFunctions, ImmutableArray.Create(statement))); } else { statements.Add(RewriteExpressionStatement((BoundExpressionStatement)initializer, suppressInstrumentation: true)); } } else { statements.Add(VisitStatement(initializer)); } } int optimizedInitializers = 0; bool optimize = _compilation.Options.OptimizationLevel == OptimizationLevel.Release; for (int i = 0; i < statements.Count; i++) { var stmt = statements[i]; if (stmt == null || (optimize && IsFieldOrPropertyInitializer(originalStatements[i]) && ShouldOptimizeOutInitializer(stmt))) { optimizedInitializers++; if (_factory.CurrentFunction?.IsStatic == false) { // NOTE: Dev11 removes static initializers if ONLY all of them are optimized out statements[i] = null; } } } ImmutableArray<BoundStatement> rewrittenStatements; if (optimizedInitializers == statements.Count) { // all are optimized away rewrittenStatements = ImmutableArray<BoundStatement>.Empty; statements.Free(); } else { // instrument remaining statements int remaining = 0; for (int i = 0; i < statements.Count; i++) { BoundStatement? rewritten = statements[i]; if (rewritten != null) { if (IsFieldOrPropertyInitializer(originalStatements[i])) { BoundStatement original = originalStatements[i]; if (Instrument && !original.WasCompilerGenerated) { rewritten = _instrumenter.InstrumentFieldOrPropertyInitializer(original, rewritten); } } statements[remaining] = rewritten; remaining++; } } statements.Count = remaining; // trim any trailing nulls rewrittenStatements = statements.ToImmutableAndFree()!; } return new BoundStatementList(node.Syntax, rewrittenStatements, node.HasErrors); } public override BoundNode VisitArrayAccess(BoundArrayAccess node) { // An array access expression can be indexed using any of the following types: // * an integer primitive // * a System.Index // * a System.Range // The last two are only supported on SZArrays. For those cases we need to // lower into the appropriate helper methods. if (node.Indices.Length != 1) { return base.VisitArrayAccess(node)!; } var indexType = VisitType(node.Indices[0].Type); var F = _factory; BoundNode resultExpr; if (TypeSymbol.Equals( indexType, _compilation.GetWellKnownType(WellKnownType.System_Index), TypeCompareKind.ConsiderEverything)) { // array[Index] is treated like a pattern-based System.Index indexing // expression, except that array indexers don't actually exist (they // don't have symbols) var arrayLocal = F.StoreToTemp( VisitExpression(node.Expression), out BoundAssignmentOperator arrayAssign); var indexOffsetExpr = MakePatternIndexOffsetExpression( node.Indices[0], F.ArrayLength(arrayLocal), out _); resultExpr = F.Sequence( ImmutableArray.Create(arrayLocal.LocalSymbol), ImmutableArray.Create<BoundExpression>(arrayAssign), F.ArrayAccess( arrayLocal, ImmutableArray.Create(indexOffsetExpr))); } else if (TypeSymbol.Equals( indexType, _compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything)) { // array[Range] is compiled to: // System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray(array, Range) Debug.Assert(node.Expression.Type is { TypeKind: TypeKind.Array }); var elementType = ((ArrayTypeSymbol)node.Expression.Type).ElementTypeWithAnnotations; resultExpr = F.Call( receiver: null, F.WellKnownMethod(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T) .Construct(ImmutableArray.Create(elementType)), ImmutableArray.Create( VisitExpression(node.Expression), VisitExpression(node.Indices[0]))); } else { resultExpr = base.VisitArrayAccess(node)!; } return resultExpr; } internal static bool IsFieldOrPropertyInitializer(BoundStatement initializer) { var syntax = initializer.Syntax; if (syntax.IsKind(SyntaxKind.Parameter)) { // This is an initialization of a generated property based on record parameter. return true; } if (syntax is ExpressionSyntax { Parent: { } parent } && parent.Kind() == SyntaxKind.EqualsValueClause) // Should be the initial value. { Debug.Assert(parent.Parent is { }); switch (parent.Parent.Kind()) { case SyntaxKind.VariableDeclarator: case SyntaxKind.PropertyDeclaration: switch (initializer.Kind) { case BoundKind.Block: var block = (BoundBlock)initializer; if (block.Statements.Length == 1) { initializer = (BoundStatement)block.Statements.First(); if (initializer.Kind == BoundKind.ExpressionStatement) { goto case BoundKind.ExpressionStatement; } } break; case BoundKind.ExpressionStatement: return ((BoundExpressionStatement)initializer).Expression.Kind == BoundKind.AssignmentOperator; } break; } } return false; } /// <summary> /// Returns true if the initializer is a field initializer which should be optimized out /// </summary> private static bool ShouldOptimizeOutInitializer(BoundStatement initializer) { BoundStatement statement = initializer; if (statement.Kind != BoundKind.ExpressionStatement) { return false; } BoundAssignmentOperator? assignment = ((BoundExpressionStatement)statement).Expression as BoundAssignmentOperator; if (assignment == null) { return false; } Debug.Assert(assignment.Left.Kind == BoundKind.FieldAccess); var lhsField = ((BoundFieldAccess)assignment.Left).FieldSymbol; if (!lhsField.IsStatic && lhsField.ContainingType.IsStructType()) { return false; } BoundExpression rhs = assignment.Right; return rhs.IsDefaultValue(); } // There are three situations in which the language permits passing rvalues by reference. // (technically there are 5, but we can ignore COM and dynamic here, since that results in byval semantics regardless of the parameter ref kind) // // #1: Receiver of a struct/generic method call. // // The language only requires that receivers of method calls must be readable (RValues are ok). // // However the underlying implementation passes receivers of struct methods by reference. // In such situations it may be possible for the call to cause or observe writes to the receiver variable. // As a result it is not valid to replace receiver variable with a reference to it or the other way around. // // Example1: // static int x = 123; // async static Task<string> Test1() // { // // cannot capture "x" by value, since write in M1 is observable // return x.ToString(await M1()); // } // // async static Task<string> M1() // { // x = 42; // await Task.Yield(); // return ""; // } // // Example2: // static int x = 123; // static string Test1() // { // // cannot replace value of "x" with a reference to "x" // // since that would make the method see the mutations in M1(); // return (x + 0).ToString(M1()); // } // // static string M1() // { // x = 42; // return ""; // } // // #2: Ordinary byval argument passed to an "in" parameter. // // The language only requires that ordinary byval arguments must be readable (RValues are ok). // However if the target parameter is an "in" parameter, the underlying implementation passes by reference. // // Example: // static int x = 123; // static void Main(string[] args) // { // // cannot replace value of "x" with a direct reference to x // // since Test will see unexpected changes due to aliasing. // Test(x + 0); // } // // static void Test(in int y) // { // Console.WriteLine(y); // x = 42; // Console.WriteLine(y); // } // // #3: Ordinary byval interpolated string expression passed to a "ref" interpolated string handler value type. // // Interpolated string expressions passed to a builder type are lowered into a handler form. When the handler type // is a value type (struct, or type parameter constrained to struct (though the latter will fail to bind today because // there's no constructor)), the final handler instance type is passed by reference if the parameter is by reference. // // Example: // M($""); // Language lowers this to a sequence of creating CustomHandler, appending all values, and evaluting to the builder // static void M(ref CustomHandler c) { } // // NB: The readonliness is not considered here. // We only care about possible introduction of aliasing. I.E. RValue->LValue change. // Even if we start with a readonly variable, it cannot be lowered into a writeable one, // with one exception - spilling of the value into a local, which is ok. // internal static bool CanBePassedByReference(BoundExpression expr) { if (expr.ConstantValue != null) { return false; } switch (expr.Kind) { case BoundKind.Parameter: case BoundKind.Local: case BoundKind.ArrayAccess: case BoundKind.ThisReference: case BoundKind.PointerIndirectionOperator: case BoundKind.PointerElementAccess: case BoundKind.RefValueOperator: case BoundKind.PseudoVariable: case BoundKind.DiscardExpression: return true; case BoundKind.DeconstructValuePlaceholder: // we will consider that placeholder always represents a temp local // the assumption should be confirmed or changed when https://github.com/dotnet/roslyn/issues/24160 is fixed return true; case BoundKind.InterpolatedStringArgumentPlaceholder: // An argument placeholder is always a reference to some type of temp local, // either representing a user-typed expression that went through this path // itself when it was originally visited, or the trailing out parameter that // is passed by out. return true; case BoundKind.InterpolatedStringHandlerPlaceholder: // A handler placeholder is the receiver of the interpolated string AppendLiteral // or AppendFormatted calls, and should never be defensively copied. return true; case BoundKind.EventAccess: var eventAccess = (BoundEventAccess)expr; if (eventAccess.IsUsableAsField) { if (eventAccess.EventSymbol.IsStatic) return true; Debug.Assert(eventAccess.ReceiverOpt is { }); return CanBePassedByReference(eventAccess.ReceiverOpt); } return false; case BoundKind.FieldAccess: var fieldAccess = (BoundFieldAccess)expr; if (!fieldAccess.FieldSymbol.IsStatic) { Debug.Assert(fieldAccess.ReceiverOpt is { }); return CanBePassedByReference(fieldAccess.ReceiverOpt); } return true; case BoundKind.Sequence: return CanBePassedByReference(((BoundSequence)expr).Value); case BoundKind.AssignmentOperator: return ((BoundAssignmentOperator)expr).IsRef; case BoundKind.ConditionalOperator: return ((BoundConditionalOperator)expr).IsRef; case BoundKind.Call: return ((BoundCall)expr).Method.RefKind != RefKind.None; case BoundKind.PropertyAccess: return ((BoundPropertyAccess)expr).PropertySymbol.RefKind != RefKind.None; case BoundKind.IndexerAccess: return ((BoundIndexerAccess)expr).Indexer.RefKind != RefKind.None; case BoundKind.IndexOrRangePatternIndexerAccess: var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; var refKind = patternIndexer.PatternSymbol switch { PropertySymbol p => p.RefKind, MethodSymbol m => m.RefKind, _ => throw ExceptionUtilities.UnexpectedValue(patternIndexer.PatternSymbol) }; return refKind != RefKind.None; case BoundKind.Conversion: var conversion = ((BoundConversion)expr); return expr is BoundConversion { Conversion: { IsInterpolatedStringHandler: true }, Type: { IsValueType: true } }; } return false; } private void CheckRefReadOnlySymbols(MethodSymbol symbol) { if (symbol.ReturnsByRefReadonly || symbol.Parameters.Any(p => p.RefKind == RefKind.In)) { _factory.CompilationState.ModuleBuilderOpt?.EnsureIsReadOnlyAttributeExists(); } } private CompoundUseSiteInfo<AssemblySymbol> GetNewCompoundUseSiteInfo() { return new CompoundUseSiteInfo<AssemblySymbol>(_diagnostics, _compilation.Assembly); } #if DEBUG /// <summary> /// Note: do not use a static/singleton instance of this type, as it holds state. /// </summary> private sealed class LocalRewritingValidator : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { /// <summary> /// Asserts that no unexpected nodes survived local rewriting. /// </summary> public static void Validate(BoundNode node) { try { new LocalRewritingValidator().Visit(node); } catch (InsufficientExecutionStackException) { // Intentionally ignored to let the overflow get caught in a more crucial visitor } } public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node) { Fail(node); return null; } public override BoundNode? VisitUsingStatement(BoundUsingStatement node) { Fail(node); return null; } public override BoundNode? VisitIfStatement(BoundIfStatement node) { Fail(node); return null; } public override BoundNode? VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) { Fail(node); return null; } public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { Fail(node); return null; } public override BoundNode? VisitDisposableValuePlaceholder(BoundDisposableValuePlaceholder node) { Fail(node); return null; } public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { Fail(node); return null; } public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { Fail(node); return null; } private void Fail(BoundNode node) { Debug.Assert(false, $"Bound nodes of kind {node.Kind} should not survive past local rewriting"); } } #endif } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./scripts/GenerateSdkPackages/files.txt
Microsoft.VisualStudio.CallHierarchy.Package.Definitions.dll Microsoft.Internal.Performance.CodeMarkers.DesignTime.dll Progression\Microsoft.VisualStudio.Progression.CodeSchema.dll Progression\Microsoft.VisualStudio.Progression.Common.dll Progression\Microsoft.VisualStudio.Progression.Interfaces.dll StaticAnalysis\Microsoft.VisualStudio.CodeAnalysis.Sdk.UI.dll VMP\Microsoft.VisualStudio.GraphModel.dll
Microsoft.VisualStudio.CallHierarchy.Package.Definitions.dll Microsoft.Internal.Performance.CodeMarkers.DesignTime.dll Progression\Microsoft.VisualStudio.Progression.CodeSchema.dll Progression\Microsoft.VisualStudio.Progression.Common.dll Progression\Microsoft.VisualStudio.Progression.Interfaces.dll StaticAnalysis\Microsoft.VisualStudio.CodeAnalysis.Sdk.UI.dll VMP\Microsoft.VisualStudio.GraphModel.dll
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Rebuild/xlf/RebuildResources.ko.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="ko" original="../RebuildResources.resx"> <body> <trans-unit id="0_exists_1_times_in_compilation_options"> <source>'{0}' exists '{1}' times in compilation options.</source> <target state="new">'{0}' exists '{1}' times in compilation options.</target> <note /> </trans-unit> <trans-unit id="A_non_null_PDB_stream_must_be_provided_because_the_compilation_does_not_have_an_embedded_PDB"> <source>A non-null PDB stream must be provided because the compilation does not have an embedded PDB.</source> <target state="new">A non-null PDB stream must be provided because the compilation does not have an embedded PDB.</target> <note /> </trans-unit> <trans-unit id="Cannot_create_compilation_options_0"> <source>Cannot create compilation options: {0}</source> <target state="new">Cannot create compilation options: {0}</target> <note /> </trans-unit> <trans-unit id="Could_not_get_PDB_file_path"> <source>Could not get PDB file path.</source> <target state="new">Could not get PDB file path.</target> <note /> </trans-unit> <trans-unit id="Does_not_contain_metadata_compilation_options"> <source>Does not contain metadata compilation options.</source> <target state="new">Does not contain metadata compilation options.</target> <note /> </trans-unit> <trans-unit id="Encountered_null_or_empty_key_for_compilation_options_pairs"> <source>Encountered null or empty key for compilation options pairs.</source> <target state="new">Encountered null or empty key for compilation options pairs.</target> <note /> </trans-unit> <trans-unit id="Encountered_unexpected_byte_0_when_expecting_a_null_terminator"> <source>Encountered unexpected byte '{0}' when expecting a null terminator.</source> <target state="new">Encountered unexpected byte '{0}' when expecting a null terminator.</target> <note /> </trans-unit> <trans-unit id="Invalid_language_name"> <source>Invalid language name.</source> <target state="new">Invalid language name.</target> <note /> </trans-unit> <trans-unit id="PDB_stream_must_be_null_because_the_compilation_has_an_embedded_PDB"> <source>PDB stream must be null because the compilation has an embedded PDB.</source> <target state="new">PDB stream must be null because the compilation has an embedded PDB.</target> <note /> </trans-unit> <trans-unit id="Unexpected_value_for_EmbedInteropTypes_MetadataImageKind_0"> <source>Unexpected value for EmbedInteropTypes/MetadataImageKind '{0}'.</source> <target state="new">Unexpected value for EmbedInteropTypes/MetadataImageKind '{0}'.</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="ko" original="../RebuildResources.resx"> <body> <trans-unit id="0_exists_1_times_in_compilation_options"> <source>'{0}' exists '{1}' times in compilation options.</source> <target state="new">'{0}' exists '{1}' times in compilation options.</target> <note /> </trans-unit> <trans-unit id="A_non_null_PDB_stream_must_be_provided_because_the_compilation_does_not_have_an_embedded_PDB"> <source>A non-null PDB stream must be provided because the compilation does not have an embedded PDB.</source> <target state="new">A non-null PDB stream must be provided because the compilation does not have an embedded PDB.</target> <note /> </trans-unit> <trans-unit id="Cannot_create_compilation_options_0"> <source>Cannot create compilation options: {0}</source> <target state="new">Cannot create compilation options: {0}</target> <note /> </trans-unit> <trans-unit id="Could_not_get_PDB_file_path"> <source>Could not get PDB file path.</source> <target state="new">Could not get PDB file path.</target> <note /> </trans-unit> <trans-unit id="Does_not_contain_metadata_compilation_options"> <source>Does not contain metadata compilation options.</source> <target state="new">Does not contain metadata compilation options.</target> <note /> </trans-unit> <trans-unit id="Encountered_null_or_empty_key_for_compilation_options_pairs"> <source>Encountered null or empty key for compilation options pairs.</source> <target state="new">Encountered null or empty key for compilation options pairs.</target> <note /> </trans-unit> <trans-unit id="Encountered_unexpected_byte_0_when_expecting_a_null_terminator"> <source>Encountered unexpected byte '{0}' when expecting a null terminator.</source> <target state="new">Encountered unexpected byte '{0}' when expecting a null terminator.</target> <note /> </trans-unit> <trans-unit id="Invalid_language_name"> <source>Invalid language name.</source> <target state="new">Invalid language name.</target> <note /> </trans-unit> <trans-unit id="PDB_stream_must_be_null_because_the_compilation_has_an_embedded_PDB"> <source>PDB stream must be null because the compilation has an embedded PDB.</source> <target state="new">PDB stream must be null because the compilation has an embedded PDB.</target> <note /> </trans-unit> <trans-unit id="Unexpected_value_for_EmbedInteropTypes_MetadataImageKind_0"> <source>Unexpected value for EmbedInteropTypes/MetadataImageKind '{0}'.</source> <target state="new">Unexpected value for EmbedInteropTypes/MetadataImageKind '{0}'.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/DesignerAttribute/InProcDesignerAttributeIncrementalAnalyzerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.DesignerAttribute; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.VisualStudio.LanguageServices.Implementation.DesignerAttribute { /// <remarks>Note: this is explicitly <b>not</b> exported. We don't want the Workspace /// to automatically load this. Instead, VS waits until it is ready /// and then calls into the service to tell it to start analyzing the solution. At that point we'll get /// created and added to the solution crawler. /// </remarks> internal sealed class InProcDesignerAttributeIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly IDesignerAttributeListener _listener; public InProcDesignerAttributeIncrementalAnalyzerProvider(IDesignerAttributeListener listener) { _listener = listener; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new InProcDesignerAttributeIncrementalAnalyzer(_listener); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.DesignerAttribute; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.VisualStudio.LanguageServices.Implementation.DesignerAttribute { /// <remarks>Note: this is explicitly <b>not</b> exported. We don't want the Workspace /// to automatically load this. Instead, VS waits until it is ready /// and then calls into the service to tell it to start analyzing the solution. At that point we'll get /// created and added to the solution crawler. /// </remarks> internal sealed class InProcDesignerAttributeIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly IDesignerAttributeListener _listener; public InProcDesignerAttributeIncrementalAnalyzerProvider(IDesignerAttributeListener listener) { _listener = listener; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new InProcDesignerAttributeIncrementalAnalyzer(_listener); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/ExternalAccess/Pythia/Api/PythiaTypeInferenceServiceWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal readonly struct PythiaTypeInferenceServiceWrapper { internal readonly ITypeInferenceService UnderlyingObject; internal PythiaTypeInferenceServiceWrapper(ITypeInferenceService underlyingObject) => UnderlyingObject = underlyingObject; public static PythiaTypeInferenceServiceWrapper Create(Document document) => new(document.GetRequiredLanguageService<ITypeInferenceService>()); public ImmutableArray<ITypeSymbol> InferTypes(SemanticModel semanticModel, int position, string? name, CancellationToken cancellationToken) => UnderlyingObject.InferTypes(semanticModel, position, name, 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 Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal readonly struct PythiaTypeInferenceServiceWrapper { internal readonly ITypeInferenceService UnderlyingObject; internal PythiaTypeInferenceServiceWrapper(ITypeInferenceService underlyingObject) => UnderlyingObject = underlyingObject; public static PythiaTypeInferenceServiceWrapper Create(Document document) => new(document.GetRequiredLanguageService<ITypeInferenceService>()); public ImmutableArray<ITypeSymbol> InferTypes(SemanticModel semanticModel, int position, string? name, CancellationToken cancellationToken) => UnderlyingObject.InferTypes(semanticModel, position, name, cancellationToken); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/Core/CodeFixes/SimplifyInterpolation/AbstractSimplifyInterpolationCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.SimplifyInterpolation { internal abstract class AbstractSimplifyInterpolationCodeFixProvider< TInterpolationSyntax, TExpressionSyntax, TInterpolationAlignmentClause, TInterpolationFormatClause, TInterpolatedStringExpressionSyntax> : SyntaxEditorBasedCodeFixProvider where TInterpolationSyntax : SyntaxNode where TExpressionSyntax : SyntaxNode where TInterpolationAlignmentClause : SyntaxNode where TInterpolationFormatClause : SyntaxNode where TInterpolatedStringExpressionSyntax : TExpressionSyntax { public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.SimplifyInterpolationId); internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected abstract AbstractSimplifyInterpolationHelpers GetHelpers(); protected abstract TInterpolationSyntax WithExpression(TInterpolationSyntax interpolation, TExpressionSyntax expression); protected abstract TInterpolationSyntax WithAlignmentClause(TInterpolationSyntax interpolation, TInterpolationAlignmentClause alignmentClause); protected abstract TInterpolationSyntax WithFormatClause(TInterpolationSyntax interpolation, TInterpolationFormatClause? formatClause); protected abstract string Escape(TInterpolatedStringExpressionSyntax interpolatedString, string formatString); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var generator = editor.Generator; var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); var helpers = GetHelpers(); foreach (var diagnostic in diagnostics) { var loc = diagnostic.AdditionalLocations[0]; var interpolation = semanticModel.GetOperation(loc.FindNode(getInnermostNodeForTie: true, cancellationToken), cancellationToken) as IInterpolationOperation; if (interpolation?.Syntax is TInterpolationSyntax interpolationSyntax && interpolationSyntax.Parent is TInterpolatedStringExpressionSyntax interpolatedString) { helpers.UnwrapInterpolation<TInterpolationSyntax, TExpressionSyntax>( document.GetRequiredLanguageService<IVirtualCharLanguageService>(), document.GetRequiredLanguageService<ISyntaxFactsService>(), interpolation, out var unwrapped, out var alignment, out var negate, out var formatString, out _); if (unwrapped == null) continue; alignment = negate ? (TExpressionSyntax)generator.NegateExpression(alignment) : alignment; editor.ReplaceNode( interpolationSyntax, Update(generatorInternal, interpolatedString, interpolationSyntax, unwrapped, alignment, formatString)); } } } private TInterpolationSyntax Update( SyntaxGeneratorInternal generator, TInterpolatedStringExpressionSyntax interpolatedString, TInterpolationSyntax interpolation, TExpressionSyntax unwrapped, TExpressionSyntax? alignment, string? formatString) { var result = WithExpression(interpolation, unwrapped); if (alignment != null) { result = WithAlignmentClause( result, (TInterpolationAlignmentClause)generator.InterpolationAlignmentClause(alignment)); } if (!string.IsNullOrEmpty(formatString)) { result = WithFormatClause( result, (TInterpolationFormatClause?)generator.InterpolationFormatClause(Escape(interpolatedString, formatString!))); } return result; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Simplify_interpolation, createChangedDocument, AnalyzersResources.Simplify_interpolation) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.SimplifyInterpolation { internal abstract class AbstractSimplifyInterpolationCodeFixProvider< TInterpolationSyntax, TExpressionSyntax, TInterpolationAlignmentClause, TInterpolationFormatClause, TInterpolatedStringExpressionSyntax> : SyntaxEditorBasedCodeFixProvider where TInterpolationSyntax : SyntaxNode where TExpressionSyntax : SyntaxNode where TInterpolationAlignmentClause : SyntaxNode where TInterpolationFormatClause : SyntaxNode where TInterpolatedStringExpressionSyntax : TExpressionSyntax { public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.SimplifyInterpolationId); internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected abstract AbstractSimplifyInterpolationHelpers GetHelpers(); protected abstract TInterpolationSyntax WithExpression(TInterpolationSyntax interpolation, TExpressionSyntax expression); protected abstract TInterpolationSyntax WithAlignmentClause(TInterpolationSyntax interpolation, TInterpolationAlignmentClause alignmentClause); protected abstract TInterpolationSyntax WithFormatClause(TInterpolationSyntax interpolation, TInterpolationFormatClause? formatClause); protected abstract string Escape(TInterpolatedStringExpressionSyntax interpolatedString, string formatString); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var generator = editor.Generator; var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); var helpers = GetHelpers(); foreach (var diagnostic in diagnostics) { var loc = diagnostic.AdditionalLocations[0]; var interpolation = semanticModel.GetOperation(loc.FindNode(getInnermostNodeForTie: true, cancellationToken), cancellationToken) as IInterpolationOperation; if (interpolation?.Syntax is TInterpolationSyntax interpolationSyntax && interpolationSyntax.Parent is TInterpolatedStringExpressionSyntax interpolatedString) { helpers.UnwrapInterpolation<TInterpolationSyntax, TExpressionSyntax>( document.GetRequiredLanguageService<IVirtualCharLanguageService>(), document.GetRequiredLanguageService<ISyntaxFactsService>(), interpolation, out var unwrapped, out var alignment, out var negate, out var formatString, out _); if (unwrapped == null) continue; alignment = negate ? (TExpressionSyntax)generator.NegateExpression(alignment) : alignment; editor.ReplaceNode( interpolationSyntax, Update(generatorInternal, interpolatedString, interpolationSyntax, unwrapped, alignment, formatString)); } } } private TInterpolationSyntax Update( SyntaxGeneratorInternal generator, TInterpolatedStringExpressionSyntax interpolatedString, TInterpolationSyntax interpolation, TExpressionSyntax unwrapped, TExpressionSyntax? alignment, string? formatString) { var result = WithExpression(interpolation, unwrapped); if (alignment != null) { result = WithAlignmentClause( result, (TInterpolationAlignmentClause)generator.InterpolationAlignmentClause(alignment)); } if (!string.IsNullOrEmpty(formatString)) { result = WithFormatClause( result, (TInterpolationFormatClause?)generator.InterpolationFormatClause(Escape(interpolatedString, formatString!))); } return result; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Simplify_interpolation, createChangedDocument, AnalyzersResources.Simplify_interpolation) { } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/LiveShare/Impl/Microsoft.VisualStudio.LanguageServices.LiveShare.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.VisualStudio.LanguageServices.LiveShare</RootNamespace> <AssemblyName>Microsoft.VisualStudio.LanguageServices.LiveShare</AssemblyName> <TargetFramework>net472</TargetFramework> <IsPackable>true</IsPackable> <PackageDescription> A private package for the liveshare team to grant access to LSP implementations. </PackageDescription> <CreateVsixContainer>false</CreateVsixContainer> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> <ProjectReference Include="..\..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> <ProjectReference Include="..\..\Core\Def\Microsoft.VisualStudio.LanguageServices.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualStudio.ComponentModelHost" Version="$(MicrosoftVisualStudioComponentModelHostVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Editor" Version="$(MicrosoftVisualStudioEditorVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging" Version="$(MicrosoftVisualStudioImagingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.LiveShare.LanguageServices.Guest" Version="$(MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion)" /> <PackageReference Include="Microsoft.VisualStudio.LiveShare.WebEditors" Version="$(MicrosoftVisualStudioLiveShareWebEditorsVersion)" /> <PackageReference Include="Microsoft.VisualStudio.LanguageServer.Protocol.Extensions" Version="$(MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Shell.15.0" Version="$(MicrosoftVisualStudioShell150Version)" /> <PackageReference Include="Microsoft.VisualStudio.Shell.Framework" Version="$(MicrosoftVisualStudioShellFrameworkVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Telemetry" Version="$(MicrosoftVisualStudioTelemetryVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Workspace.VSIntegration" Version="$(MicrosoftVisualStudioWorkspaceVSIntegrationVersion)" /> <PackageReference Include="StreamJsonRpc" Version="$(StreamJsonRpcVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.VisualStudio.LanguageServices.LiveShare</RootNamespace> <AssemblyName>Microsoft.VisualStudio.LanguageServices.LiveShare</AssemblyName> <TargetFramework>net472</TargetFramework> <IsPackable>true</IsPackable> <PackageDescription> A private package for the liveshare team to grant access to LSP implementations. </PackageDescription> <CreateVsixContainer>false</CreateVsixContainer> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> <ProjectReference Include="..\..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> <ProjectReference Include="..\..\Core\Def\Microsoft.VisualStudio.LanguageServices.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualStudio.ComponentModelHost" Version="$(MicrosoftVisualStudioComponentModelHostVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Editor" Version="$(MicrosoftVisualStudioEditorVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging" Version="$(MicrosoftVisualStudioImagingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.LiveShare.LanguageServices.Guest" Version="$(MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion)" /> <PackageReference Include="Microsoft.VisualStudio.LiveShare.WebEditors" Version="$(MicrosoftVisualStudioLiveShareWebEditorsVersion)" /> <PackageReference Include="Microsoft.VisualStudio.LanguageServer.Protocol.Extensions" Version="$(MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Shell.15.0" Version="$(MicrosoftVisualStudioShell150Version)" /> <PackageReference Include="Microsoft.VisualStudio.Shell.Framework" Version="$(MicrosoftVisualStudioShellFrameworkVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Telemetry" Version="$(MicrosoftVisualStudioTelemetryVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Workspace.VSIntegration" Version="$(MicrosoftVisualStudioWorkspaceVSIntegrationVersion)" /> <PackageReference Include="StreamJsonRpc" Version="$(StreamJsonRpcVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests" /> </ItemGroup> </Project>
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/GenerateMember/GenerateConstructor/AbstractGenerateConstructorService.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal abstract partial class AbstractGenerateConstructorService<TService, TExpressionSyntax> { protected internal class State { private readonly TService _service; private readonly SemanticDocument _document; private readonly NamingRule _fieldNamingRule; private readonly NamingRule _propertyNamingRule; private readonly NamingRule _parameterNamingRule; private ImmutableArray<Argument> _arguments; // The type we're creating a constructor for. Will be a class or struct type. public INamedTypeSymbol? TypeToGenerateIn { get; private set; } private ImmutableArray<RefKind> _parameterRefKinds; public ImmutableArray<ITypeSymbol> ParameterTypes; public SyntaxToken Token { get; private set; } public bool IsConstructorInitializerGeneration { get; private set; } private IMethodSymbol? _delegatedConstructor; private ImmutableArray<IParameterSymbol> _parameters; private ImmutableDictionary<string, ISymbol>? _parameterToExistingMemberMap; public ImmutableDictionary<string, string> ParameterToNewFieldMap { get; private set; } public ImmutableDictionary<string, string> ParameterToNewPropertyMap { get; private set; } public bool IsContainedInUnsafeType { get; private set; } private State(TService service, SemanticDocument document, NamingRule fieldNamingRule, NamingRule propertyNamingRule, NamingRule parameterNamingRule) { _service = service; _document = document; _fieldNamingRule = fieldNamingRule; _propertyNamingRule = propertyNamingRule; _parameterNamingRule = parameterNamingRule; ParameterToNewFieldMap = ImmutableDictionary<string, string>.Empty; ParameterToNewPropertyMap = ImmutableDictionary<string, string>.Empty; } public static async Task<State?> GenerateAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { var fieldNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Field, Accessibility.Private, cancellationToken).ConfigureAwait(false); var propertyNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Property, Accessibility.Public, cancellationToken).ConfigureAwait(false); var parameterNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Parameter, Accessibility.NotApplicable, cancellationToken).ConfigureAwait(false); var state = new State(service, document, fieldNamingRule, propertyNamingRule, parameterNamingRule); if (!await state.TryInitializeAsync(node, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( SyntaxNode node, CancellationToken cancellationToken) { if (_service.IsConstructorInitializerGeneration(_document, node, cancellationToken)) { if (!await TryInitializeConstructorInitializerGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsSimpleNameGeneration(_document, node, cancellationToken)) { if (!await TryInitializeSimpleNameGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsImplicitObjectCreation(_document, node, cancellationToken)) { if (!await TryInitializeImplicitObjectCreationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else { return false; } Contract.ThrowIfNull(TypeToGenerateIn); if (!CodeGenerator.CanAdd(_document.Project.Solution, TypeToGenerateIn, cancellationToken)) return false; ParameterTypes = ParameterTypes.IsDefault ? GetParameterTypes(cancellationToken) : ParameterTypes; _parameterRefKinds = _arguments.SelectAsArray(a => a.RefKind); if (ClashesWithExistingConstructor()) return false; if (!TryInitializeDelegatedConstructor(cancellationToken)) InitializeNonDelegatedConstructor(cancellationToken); IsContainedInUnsafeType = _service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn); return true; } private void InitializeNonDelegatedConstructor(CancellationToken cancellationToken) { var typeParametersNames = TypeToGenerateIn.GetAllTypeParameters().Select(t => t.Name).ToImmutableArray(); var parameterNames = GetParameterNames(_arguments, typeParametersNames, cancellationToken); GetParameters(_arguments, ParameterTypes, parameterNames, cancellationToken); } private ImmutableArray<ParameterName> GetParameterNames( ImmutableArray<Argument> arguments, ImmutableArray<string> typeParametersNames, CancellationToken cancellationToken) { return _service.GenerateParameterNames(_document, arguments, typeParametersNames, _parameterNamingRule, cancellationToken); } private bool TryInitializeDelegatedConstructor(CancellationToken cancellationToken) { var parameters = ParameterTypes.Zip(_parameterRefKinds, (t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(r, t, name: "")).ToImmutableArray(); var expressions = _arguments.SelectAsArray(a => a.Expression); var delegatedConstructor = FindConstructorToDelegateTo(parameters, expressions, cancellationToken); if (delegatedConstructor == null) return false; // Map the first N parameters to the other constructor in this type. Then // try to map any further parameters to existing fields. Finally, generate // new fields if no such parameters exist. // Find the names of the parameters that will follow the parameters we're // delegating. var argumentCount = delegatedConstructor.Parameters.Length; var remainingArguments = _arguments.Skip(argumentCount).ToImmutableArray(); var remainingParameterNames = _service.GenerateParameterNames( _document, remainingArguments, delegatedConstructor.Parameters.Select(p => p.Name).ToList(), _parameterNamingRule, cancellationToken); // Can't generate the constructor if the parameter names we're copying over forcibly // conflict with any names we generated. if (delegatedConstructor.Parameters.Select(p => p.Name).Intersect(remainingParameterNames.Select(n => n.BestNameForParameter)).Any()) return false; var remainingParameterTypes = ParameterTypes.Skip(argumentCount).ToImmutableArray(); _delegatedConstructor = delegatedConstructor; GetParameters(remainingArguments, remainingParameterTypes, remainingParameterNames, cancellationToken); return true; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> allParameters, ImmutableArray<TExpressionSyntax?> allExpressions, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); Contract.ThrowIfNull(TypeToGenerateIn.BaseType); for (var i = allParameters.Length; i > 0; i--) { var parameters = allParameters.TakeAsArray(i); var expressions = allExpressions.TakeAsArray(i); var result = FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.InstanceConstructors, cancellationToken) ?? FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.BaseType.InstanceConstructors, cancellationToken); if (result != null) return result; } return null; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> parameters, ImmutableArray<TExpressionSyntax?> expressions, ImmutableArray<IMethodSymbol> constructors, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); foreach (var constructor in constructors) { // Don't bother delegating to an implicit constructor. We don't want to add `: base()` as that's just // redundant for subclasses and `: this()` won't even work as we won't have an implicit constructor once // we add this new constructor. if (constructor.IsImplicitlyDeclared) continue; // Don't delegate to another constructor in this type if it's got the same parameter types as the // one we're generating. This can happen if we're generating the new constructor because parameter // names don't match (when a user explicitly provides named parameters). if (TypeToGenerateIn.Equals(constructor.ContainingType) && constructor.Parameters.Select(p => p.Type).SequenceEqual(ParameterTypes)) { continue; } if (GenerateConstructorHelpers.CanDelegateTo(_document, parameters, expressions, constructor) && !_service.WillCauseConstructorCycle(this, _document, constructor, cancellationToken)) { return constructor; } } return null; } private bool ClashesWithExistingConstructor() { Contract.ThrowIfNull(TypeToGenerateIn); var destinationProvider = _document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var syntaxFacts = destinationProvider.GetRequiredService<ISyntaxFactsService>(); return TypeToGenerateIn.InstanceConstructors.Any(c => Matches(c, syntaxFacts)); } private bool Matches(IMethodSymbol ctor, ISyntaxFactsService service) { if (ctor.Parameters.Length != ParameterTypes.Length) return false; for (var i = 0; i < ParameterTypes.Length; i++) { var ctorParameter = ctor.Parameters[i]; var result = SymbolEquivalenceComparer.Instance.Equals(ctorParameter.Type, ParameterTypes[i]) && ctorParameter.RefKind == _parameterRefKinds[i]; var parameterName = GetParameterName(i); if (!string.IsNullOrEmpty(parameterName)) { result &= service.IsCaseSensitive ? ctorParameter.Name == parameterName : string.Equals(ctorParameter.Name, parameterName, StringComparison.OrdinalIgnoreCase); } if (result == false) return false; } return true; } private string GetParameterName(int index) => _arguments.IsDefault || index >= _arguments.Length ? string.Empty : _arguments[index].Name; internal ImmutableArray<ITypeSymbol> GetParameterTypes(CancellationToken cancellationToken) { var allTypeParameters = TypeToGenerateIn.GetAllTypeParameters(); var semanticModel = _document.SemanticModel; var allTypes = _arguments.Select(a => _service.GetArgumentType(_document.SemanticModel, a, cancellationToken)); return allTypes.Select(t => FixType(t, semanticModel, allTypeParameters)).ToImmutableArray(); } private static ITypeSymbol FixType(ITypeSymbol typeSymbol, SemanticModel semanticModel, IEnumerable<ITypeParameterSymbol> allTypeParameters) { var compilation = semanticModel.Compilation; return typeSymbol.RemoveAnonymousTypes(compilation) .RemoveUnavailableTypeParameters(compilation, allTypeParameters) .RemoveUnnamedErrorTypes(compilation); } private async Task<bool> TryInitializeConstructorInitializerGenerationAsync( SyntaxNode constructorInitializer, CancellationToken cancellationToken) { if (_service.TryInitializeConstructorInitializerGeneration( _document, constructorInitializer, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; IsConstructorInitializerGeneration = true; var semanticInfo = _document.SemanticModel.GetSymbolInfo(constructorInitializer, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeImplicitObjectCreationAsync(SyntaxNode implicitObjectCreation, CancellationToken cancellationToken) { if (_service.TryInitializeImplicitObjectCreation( _document, implicitObjectCreation, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; var semanticInfo = _document.SemanticModel.GetSymbolInfo(implicitObjectCreation, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeSimpleNameGenerationAsync( SyntaxNode simpleName, CancellationToken cancellationToken) { if (_service.TryInitializeSimpleNameGenerationState( _document, simpleName, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; } else if (_service.TryInitializeSimpleAttributeNameGenerationState( _document, simpleName, cancellationToken, out token, out arguments, out typeToGenerateIn)) { Token = token; _arguments = arguments; //// Attribute parameters are restricted to be constant values (simple types or string, etc). if (GetParameterTypes(cancellationToken).Any(t => !IsValidAttributeParameterType(t))) return false; } else { return false; } cancellationToken.ThrowIfCancellationRequested(); return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } private static bool IsValidAttributeParameterType(ITypeSymbol type) { if (type.Kind == SymbolKind.ArrayType) { var arrayType = (IArrayTypeSymbol)type; if (arrayType.Rank != 1) { return false; } type = arrayType.ElementType; } if (type.IsEnumType()) { return true; } switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_String: return true; default: return false; } } private async Task<bool> TryDetermineTypeToGenerateInAsync( INamedTypeSymbol original, CancellationToken cancellationToken) { var definition = await SymbolFinder.FindSourceDefinitionAsync(original, _document.Project.Solution, cancellationToken).ConfigureAwait(false); TypeToGenerateIn = definition as INamedTypeSymbol; return TypeToGenerateIn?.TypeKind is (TypeKind?)TypeKind.Class or (TypeKind?)TypeKind.Struct; } private void GetParameters( ImmutableArray<Argument> arguments, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<ParameterName> parameterNames, CancellationToken cancellationToken) { var parameterToExistingMemberMap = ImmutableDictionary.CreateBuilder<string, ISymbol>(); var parameterToNewFieldMap = ImmutableDictionary.CreateBuilder<string, string>(); var parameterToNewPropertyMap = ImmutableDictionary.CreateBuilder<string, string>(); using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var parameters); for (var i = 0; i < parameterNames.Length; i++) { var parameterName = parameterNames[i]; var parameterType = parameterTypes[i]; var argument = arguments[i]; // See if there's a matching field or property we can use, or create a new member otherwise. FindExistingOrCreateNewMember( ref parameterName, parameterType, argument, parameterToExistingMemberMap, parameterToNewFieldMap, parameterToNewPropertyMap, cancellationToken); parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: argument.RefKind, isParams: false, type: parameterType, name: parameterName.BestNameForParameter)); } _parameters = parameters.ToImmutable(); _parameterToExistingMemberMap = parameterToExistingMemberMap.ToImmutable(); ParameterToNewFieldMap = parameterToNewFieldMap.ToImmutable(); ParameterToNewPropertyMap = parameterToNewPropertyMap.ToImmutable(); } private void FindExistingOrCreateNewMember( ref ParameterName parameterName, ITypeSymbol parameterType, Argument argument, ImmutableDictionary<string, ISymbol>.Builder parameterToExistingMemberMap, ImmutableDictionary<string, string>.Builder parameterToNewFieldMap, ImmutableDictionary<string, string>.Builder parameterToNewPropertyMap, CancellationToken cancellationToken) { var expectedFieldName = _fieldNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var expectedPropertyName = _propertyNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var isFixed = argument.IsNamed; // For non-out parameters, see if there's already a field there with the same name. // If so, and it has a compatible type, then we can just assign to that field. // Otherwise, we'll need to choose a different name for this member so that it // doesn't conflict with something already in the type. First check the current type // for a matching field. If so, defer to it. var unavailableMemberNames = GetUnavailableMemberNames().ToImmutableArray(); var members = from t in TypeToGenerateIn.GetBaseTypesAndThis() let ignoreAccessibility = t.Equals(TypeToGenerateIn) from m in t.GetMembers() where m.Name.Equals(expectedFieldName, StringComparison.OrdinalIgnoreCase) where ignoreAccessibility || IsSymbolAccessible(m, _document) select m; var membersArray = members.ToImmutableArray(); var symbol = membersArray.FirstOrDefault(m => m.Name.Equals(expectedFieldName, StringComparison.Ordinal)) ?? membersArray.FirstOrDefault(); if (symbol != null) { if (IsViableFieldOrProperty(parameterType, symbol)) { // Ok! We can just the existing field. parameterToExistingMemberMap[parameterName.BestNameForParameter] = symbol; } else { // Uh-oh. Now we have a problem. We can't assign this parameter to // this field. So we need to create a new field. Find a name not in // use so we can assign to that. var baseName = _service.GenerateNameForArgument(_document.SemanticModel, argument, cancellationToken); var baseFieldWithNamingStyle = _fieldNamingRule.NamingStyle.MakeCompliant(baseName).First(); var basePropertyWithNamingStyle = _propertyNamingRule.NamingStyle.MakeCompliant(baseName).First(); var newFieldName = NameGenerator.EnsureUniqueness(baseFieldWithNamingStyle, unavailableMemberNames.Concat(parameterToNewFieldMap.Values)); var newPropertyName = NameGenerator.EnsureUniqueness(basePropertyWithNamingStyle, unavailableMemberNames.Concat(parameterToNewPropertyMap.Values)); if (isFixed) { // Can't change the parameter name, so map the existing parameter // name to the new field name. parameterToNewFieldMap[parameterName.NameBasedOnArgument] = newFieldName; parameterToNewPropertyMap[parameterName.NameBasedOnArgument] = newPropertyName; } else { // Can change the parameter name, so do so. // But first remove any prefix added due to field naming styles var fieldNameMinusPrefix = newFieldName[_fieldNamingRule.NamingStyle.Prefix.Length..]; var newParameterName = new ParameterName(fieldNameMinusPrefix, isFixed: false, _parameterNamingRule); parameterName = newParameterName; parameterToNewFieldMap[newParameterName.BestNameForParameter] = newFieldName; parameterToNewPropertyMap[newParameterName.BestNameForParameter] = newPropertyName; } } return; } // If no matching field was found, use the fieldNamingRule to create suitable name var bestNameForParameter = parameterName.BestNameForParameter; var nameBasedOnArgument = parameterName.NameBasedOnArgument; parameterToNewFieldMap[bestNameForParameter] = _fieldNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); parameterToNewPropertyMap[bestNameForParameter] = _propertyNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); } private IEnumerable<string> GetUnavailableMemberNames() { Contract.ThrowIfNull(TypeToGenerateIn); return TypeToGenerateIn.MemberNames.Concat( from type in TypeToGenerateIn.GetBaseTypes() from member in type.GetMembers() select member.Name); } private bool IsViableFieldOrProperty( ITypeSymbol parameterType, ISymbol symbol) { if (parameterType.Language != symbol.Language) return false; if (symbol != null && !symbol.IsStatic) { if (symbol is IFieldSymbol field) { return !field.IsConst && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, field.Type); } else if (symbol is IPropertySymbol property) { return property.Parameters.Length == 0 && property.IsWritableInConstructor() && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, property.Type); } } return false; } public async Task<Document> GetChangedDocumentAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { // See if there's an accessible base constructor that would accept these // types, then just call into that instead of generating fields. // // then, see if there are any constructors that would take the first 'n' arguments // we've provided. If so, delegate to those, and then create a field for any // remaining arguments. Try to match from largest to smallest. // // Otherwise, just generate a normal constructor that assigns any provided // parameters into fields. return await GenerateThisOrBaseDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false) ?? await GenerateMemberDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); } private async Task<Document?> GenerateThisOrBaseDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { if (_delegatedConstructor == null) return null; Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var (members, assignments) = await GenerateMembersAndAssignmentsAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); var isThis = _delegatedConstructor.ContainingType.OriginalDefinition.Equals(TypeToGenerateIn.OriginalDefinition); var delegatingArguments = provider.GetService<SyntaxGenerator>().CreateArguments(_delegatedConstructor.Parameters); var newParameters = _delegatedConstructor.Parameters.Concat(_parameters); var generateUnsafe = !IsContainedInUnsafeType && newParameters.Any(p => p.RequiresUnsafeModifier()); var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isUnsafe: generateUnsafe), typeName: TypeToGenerateIn.Name, parameters: newParameters, statements: assignments, baseConstructorArguments: isThis ? default : delegatingArguments, thisConstructorArguments: isThis ? delegatingArguments : default); return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, members.Concat(constructor), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } private async Task<(ImmutableArray<ISymbol>, ImmutableArray<SyntaxNode>)> GenerateMembersAndAssignmentsAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var members = withFields ? SyntaxGeneratorExtensions.CreateFieldsForParameters(_parameters, ParameterToNewFieldMap, IsContainedInUnsafeType) : withProperties ? SyntaxGeneratorExtensions.CreatePropertiesForParameters(_parameters, ParameterToNewPropertyMap, IsContainedInUnsafeType) : ImmutableArray<ISymbol>.Empty; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var assignments = !withFields && !withProperties ? ImmutableArray<SyntaxNode>.Empty : provider.GetService<SyntaxGenerator>().CreateAssignmentStatements( semanticModel, _parameters, _parameterToExistingMemberMap, withFields ? ParameterToNewFieldMap : ParameterToNewPropertyMap, addNullChecks: false, preferThrowExpression: false); return (members, assignments); } private async Task<Document> GenerateMemberDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newMemberMap = withFields ? ParameterToNewFieldMap : withProperties ? ParameterToNewPropertyMap : ImmutableDictionary<string, string>.Empty; return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, provider.GetService<SyntaxGenerator>().CreateMemberDelegatingConstructor( semanticModel, TypeToGenerateIn.Name, TypeToGenerateIn, _parameters, _parameterToExistingMemberMap, newMemberMap, addNullChecks: false, preferThrowExpression: false, generateProperties: withProperties, IsContainedInUnsafeType), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal abstract partial class AbstractGenerateConstructorService<TService, TExpressionSyntax> { protected internal class State { private readonly TService _service; private readonly SemanticDocument _document; private readonly NamingRule _fieldNamingRule; private readonly NamingRule _propertyNamingRule; private readonly NamingRule _parameterNamingRule; private ImmutableArray<Argument> _arguments; // The type we're creating a constructor for. Will be a class or struct type. public INamedTypeSymbol? TypeToGenerateIn { get; private set; } private ImmutableArray<RefKind> _parameterRefKinds; public ImmutableArray<ITypeSymbol> ParameterTypes; public SyntaxToken Token { get; private set; } public bool IsConstructorInitializerGeneration { get; private set; } private IMethodSymbol? _delegatedConstructor; private ImmutableArray<IParameterSymbol> _parameters; private ImmutableDictionary<string, ISymbol>? _parameterToExistingMemberMap; public ImmutableDictionary<string, string> ParameterToNewFieldMap { get; private set; } public ImmutableDictionary<string, string> ParameterToNewPropertyMap { get; private set; } public bool IsContainedInUnsafeType { get; private set; } private State(TService service, SemanticDocument document, NamingRule fieldNamingRule, NamingRule propertyNamingRule, NamingRule parameterNamingRule) { _service = service; _document = document; _fieldNamingRule = fieldNamingRule; _propertyNamingRule = propertyNamingRule; _parameterNamingRule = parameterNamingRule; ParameterToNewFieldMap = ImmutableDictionary<string, string>.Empty; ParameterToNewPropertyMap = ImmutableDictionary<string, string>.Empty; } public static async Task<State?> GenerateAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { var fieldNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Field, Accessibility.Private, cancellationToken).ConfigureAwait(false); var propertyNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Property, Accessibility.Public, cancellationToken).ConfigureAwait(false); var parameterNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Parameter, Accessibility.NotApplicable, cancellationToken).ConfigureAwait(false); var state = new State(service, document, fieldNamingRule, propertyNamingRule, parameterNamingRule); if (!await state.TryInitializeAsync(node, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( SyntaxNode node, CancellationToken cancellationToken) { if (_service.IsConstructorInitializerGeneration(_document, node, cancellationToken)) { if (!await TryInitializeConstructorInitializerGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsSimpleNameGeneration(_document, node, cancellationToken)) { if (!await TryInitializeSimpleNameGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsImplicitObjectCreation(_document, node, cancellationToken)) { if (!await TryInitializeImplicitObjectCreationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else { return false; } Contract.ThrowIfNull(TypeToGenerateIn); if (!CodeGenerator.CanAdd(_document.Project.Solution, TypeToGenerateIn, cancellationToken)) return false; ParameterTypes = ParameterTypes.IsDefault ? GetParameterTypes(cancellationToken) : ParameterTypes; _parameterRefKinds = _arguments.SelectAsArray(a => a.RefKind); if (ClashesWithExistingConstructor()) return false; if (!TryInitializeDelegatedConstructor(cancellationToken)) InitializeNonDelegatedConstructor(cancellationToken); IsContainedInUnsafeType = _service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn); return true; } private void InitializeNonDelegatedConstructor(CancellationToken cancellationToken) { var typeParametersNames = TypeToGenerateIn.GetAllTypeParameters().Select(t => t.Name).ToImmutableArray(); var parameterNames = GetParameterNames(_arguments, typeParametersNames, cancellationToken); GetParameters(_arguments, ParameterTypes, parameterNames, cancellationToken); } private ImmutableArray<ParameterName> GetParameterNames( ImmutableArray<Argument> arguments, ImmutableArray<string> typeParametersNames, CancellationToken cancellationToken) { return _service.GenerateParameterNames(_document, arguments, typeParametersNames, _parameterNamingRule, cancellationToken); } private bool TryInitializeDelegatedConstructor(CancellationToken cancellationToken) { var parameters = ParameterTypes.Zip(_parameterRefKinds, (t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(r, t, name: "")).ToImmutableArray(); var expressions = _arguments.SelectAsArray(a => a.Expression); var delegatedConstructor = FindConstructorToDelegateTo(parameters, expressions, cancellationToken); if (delegatedConstructor == null) return false; // Map the first N parameters to the other constructor in this type. Then // try to map any further parameters to existing fields. Finally, generate // new fields if no such parameters exist. // Find the names of the parameters that will follow the parameters we're // delegating. var argumentCount = delegatedConstructor.Parameters.Length; var remainingArguments = _arguments.Skip(argumentCount).ToImmutableArray(); var remainingParameterNames = _service.GenerateParameterNames( _document, remainingArguments, delegatedConstructor.Parameters.Select(p => p.Name).ToList(), _parameterNamingRule, cancellationToken); // Can't generate the constructor if the parameter names we're copying over forcibly // conflict with any names we generated. if (delegatedConstructor.Parameters.Select(p => p.Name).Intersect(remainingParameterNames.Select(n => n.BestNameForParameter)).Any()) return false; var remainingParameterTypes = ParameterTypes.Skip(argumentCount).ToImmutableArray(); _delegatedConstructor = delegatedConstructor; GetParameters(remainingArguments, remainingParameterTypes, remainingParameterNames, cancellationToken); return true; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> allParameters, ImmutableArray<TExpressionSyntax?> allExpressions, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); Contract.ThrowIfNull(TypeToGenerateIn.BaseType); for (var i = allParameters.Length; i > 0; i--) { var parameters = allParameters.TakeAsArray(i); var expressions = allExpressions.TakeAsArray(i); var result = FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.InstanceConstructors, cancellationToken) ?? FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.BaseType.InstanceConstructors, cancellationToken); if (result != null) return result; } return null; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> parameters, ImmutableArray<TExpressionSyntax?> expressions, ImmutableArray<IMethodSymbol> constructors, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); foreach (var constructor in constructors) { // Don't bother delegating to an implicit constructor. We don't want to add `: base()` as that's just // redundant for subclasses and `: this()` won't even work as we won't have an implicit constructor once // we add this new constructor. if (constructor.IsImplicitlyDeclared) continue; // Don't delegate to another constructor in this type if it's got the same parameter types as the // one we're generating. This can happen if we're generating the new constructor because parameter // names don't match (when a user explicitly provides named parameters). if (TypeToGenerateIn.Equals(constructor.ContainingType) && constructor.Parameters.Select(p => p.Type).SequenceEqual(ParameterTypes)) { continue; } if (GenerateConstructorHelpers.CanDelegateTo(_document, parameters, expressions, constructor) && !_service.WillCauseConstructorCycle(this, _document, constructor, cancellationToken)) { return constructor; } } return null; } private bool ClashesWithExistingConstructor() { Contract.ThrowIfNull(TypeToGenerateIn); var destinationProvider = _document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var syntaxFacts = destinationProvider.GetRequiredService<ISyntaxFactsService>(); return TypeToGenerateIn.InstanceConstructors.Any(c => Matches(c, syntaxFacts)); } private bool Matches(IMethodSymbol ctor, ISyntaxFactsService service) { if (ctor.Parameters.Length != ParameterTypes.Length) return false; for (var i = 0; i < ParameterTypes.Length; i++) { var ctorParameter = ctor.Parameters[i]; var result = SymbolEquivalenceComparer.Instance.Equals(ctorParameter.Type, ParameterTypes[i]) && ctorParameter.RefKind == _parameterRefKinds[i]; var parameterName = GetParameterName(i); if (!string.IsNullOrEmpty(parameterName)) { result &= service.IsCaseSensitive ? ctorParameter.Name == parameterName : string.Equals(ctorParameter.Name, parameterName, StringComparison.OrdinalIgnoreCase); } if (result == false) return false; } return true; } private string GetParameterName(int index) => _arguments.IsDefault || index >= _arguments.Length ? string.Empty : _arguments[index].Name; internal ImmutableArray<ITypeSymbol> GetParameterTypes(CancellationToken cancellationToken) { var allTypeParameters = TypeToGenerateIn.GetAllTypeParameters(); var semanticModel = _document.SemanticModel; var allTypes = _arguments.Select(a => _service.GetArgumentType(_document.SemanticModel, a, cancellationToken)); return allTypes.Select(t => FixType(t, semanticModel, allTypeParameters)).ToImmutableArray(); } private static ITypeSymbol FixType(ITypeSymbol typeSymbol, SemanticModel semanticModel, IEnumerable<ITypeParameterSymbol> allTypeParameters) { var compilation = semanticModel.Compilation; return typeSymbol.RemoveAnonymousTypes(compilation) .RemoveUnavailableTypeParameters(compilation, allTypeParameters) .RemoveUnnamedErrorTypes(compilation); } private async Task<bool> TryInitializeConstructorInitializerGenerationAsync( SyntaxNode constructorInitializer, CancellationToken cancellationToken) { if (_service.TryInitializeConstructorInitializerGeneration( _document, constructorInitializer, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; IsConstructorInitializerGeneration = true; var semanticInfo = _document.SemanticModel.GetSymbolInfo(constructorInitializer, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeImplicitObjectCreationAsync(SyntaxNode implicitObjectCreation, CancellationToken cancellationToken) { if (_service.TryInitializeImplicitObjectCreation( _document, implicitObjectCreation, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; var semanticInfo = _document.SemanticModel.GetSymbolInfo(implicitObjectCreation, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeSimpleNameGenerationAsync( SyntaxNode simpleName, CancellationToken cancellationToken) { if (_service.TryInitializeSimpleNameGenerationState( _document, simpleName, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; } else if (_service.TryInitializeSimpleAttributeNameGenerationState( _document, simpleName, cancellationToken, out token, out arguments, out typeToGenerateIn)) { Token = token; _arguments = arguments; //// Attribute parameters are restricted to be constant values (simple types or string, etc). if (GetParameterTypes(cancellationToken).Any(t => !IsValidAttributeParameterType(t))) return false; } else { return false; } cancellationToken.ThrowIfCancellationRequested(); return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } private static bool IsValidAttributeParameterType(ITypeSymbol type) { if (type.Kind == SymbolKind.ArrayType) { var arrayType = (IArrayTypeSymbol)type; if (arrayType.Rank != 1) { return false; } type = arrayType.ElementType; } if (type.IsEnumType()) { return true; } switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_String: return true; default: return false; } } private async Task<bool> TryDetermineTypeToGenerateInAsync( INamedTypeSymbol original, CancellationToken cancellationToken) { var definition = await SymbolFinder.FindSourceDefinitionAsync(original, _document.Project.Solution, cancellationToken).ConfigureAwait(false); TypeToGenerateIn = definition as INamedTypeSymbol; return TypeToGenerateIn?.TypeKind is (TypeKind?)TypeKind.Class or (TypeKind?)TypeKind.Struct; } private void GetParameters( ImmutableArray<Argument> arguments, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<ParameterName> parameterNames, CancellationToken cancellationToken) { var parameterToExistingMemberMap = ImmutableDictionary.CreateBuilder<string, ISymbol>(); var parameterToNewFieldMap = ImmutableDictionary.CreateBuilder<string, string>(); var parameterToNewPropertyMap = ImmutableDictionary.CreateBuilder<string, string>(); using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var parameters); for (var i = 0; i < parameterNames.Length; i++) { var parameterName = parameterNames[i]; var parameterType = parameterTypes[i]; var argument = arguments[i]; // See if there's a matching field or property we can use, or create a new member otherwise. FindExistingOrCreateNewMember( ref parameterName, parameterType, argument, parameterToExistingMemberMap, parameterToNewFieldMap, parameterToNewPropertyMap, cancellationToken); parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: argument.RefKind, isParams: false, type: parameterType, name: parameterName.BestNameForParameter)); } _parameters = parameters.ToImmutable(); _parameterToExistingMemberMap = parameterToExistingMemberMap.ToImmutable(); ParameterToNewFieldMap = parameterToNewFieldMap.ToImmutable(); ParameterToNewPropertyMap = parameterToNewPropertyMap.ToImmutable(); } private void FindExistingOrCreateNewMember( ref ParameterName parameterName, ITypeSymbol parameterType, Argument argument, ImmutableDictionary<string, ISymbol>.Builder parameterToExistingMemberMap, ImmutableDictionary<string, string>.Builder parameterToNewFieldMap, ImmutableDictionary<string, string>.Builder parameterToNewPropertyMap, CancellationToken cancellationToken) { var expectedFieldName = _fieldNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var expectedPropertyName = _propertyNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var isFixed = argument.IsNamed; // For non-out parameters, see if there's already a field there with the same name. // If so, and it has a compatible type, then we can just assign to that field. // Otherwise, we'll need to choose a different name for this member so that it // doesn't conflict with something already in the type. First check the current type // for a matching field. If so, defer to it. var unavailableMemberNames = GetUnavailableMemberNames().ToImmutableArray(); var members = from t in TypeToGenerateIn.GetBaseTypesAndThis() let ignoreAccessibility = t.Equals(TypeToGenerateIn) from m in t.GetMembers() where m.Name.Equals(expectedFieldName, StringComparison.OrdinalIgnoreCase) where ignoreAccessibility || IsSymbolAccessible(m, _document) select m; var membersArray = members.ToImmutableArray(); var symbol = membersArray.FirstOrDefault(m => m.Name.Equals(expectedFieldName, StringComparison.Ordinal)) ?? membersArray.FirstOrDefault(); if (symbol != null) { if (IsViableFieldOrProperty(parameterType, symbol)) { // Ok! We can just the existing field. parameterToExistingMemberMap[parameterName.BestNameForParameter] = symbol; } else { // Uh-oh. Now we have a problem. We can't assign this parameter to // this field. So we need to create a new field. Find a name not in // use so we can assign to that. var baseName = _service.GenerateNameForArgument(_document.SemanticModel, argument, cancellationToken); var baseFieldWithNamingStyle = _fieldNamingRule.NamingStyle.MakeCompliant(baseName).First(); var basePropertyWithNamingStyle = _propertyNamingRule.NamingStyle.MakeCompliant(baseName).First(); var newFieldName = NameGenerator.EnsureUniqueness(baseFieldWithNamingStyle, unavailableMemberNames.Concat(parameterToNewFieldMap.Values)); var newPropertyName = NameGenerator.EnsureUniqueness(basePropertyWithNamingStyle, unavailableMemberNames.Concat(parameterToNewPropertyMap.Values)); if (isFixed) { // Can't change the parameter name, so map the existing parameter // name to the new field name. parameterToNewFieldMap[parameterName.NameBasedOnArgument] = newFieldName; parameterToNewPropertyMap[parameterName.NameBasedOnArgument] = newPropertyName; } else { // Can change the parameter name, so do so. // But first remove any prefix added due to field naming styles var fieldNameMinusPrefix = newFieldName[_fieldNamingRule.NamingStyle.Prefix.Length..]; var newParameterName = new ParameterName(fieldNameMinusPrefix, isFixed: false, _parameterNamingRule); parameterName = newParameterName; parameterToNewFieldMap[newParameterName.BestNameForParameter] = newFieldName; parameterToNewPropertyMap[newParameterName.BestNameForParameter] = newPropertyName; } } return; } // If no matching field was found, use the fieldNamingRule to create suitable name var bestNameForParameter = parameterName.BestNameForParameter; var nameBasedOnArgument = parameterName.NameBasedOnArgument; parameterToNewFieldMap[bestNameForParameter] = _fieldNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); parameterToNewPropertyMap[bestNameForParameter] = _propertyNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); } private IEnumerable<string> GetUnavailableMemberNames() { Contract.ThrowIfNull(TypeToGenerateIn); return TypeToGenerateIn.MemberNames.Concat( from type in TypeToGenerateIn.GetBaseTypes() from member in type.GetMembers() select member.Name); } private bool IsViableFieldOrProperty( ITypeSymbol parameterType, ISymbol symbol) { if (parameterType.Language != symbol.Language) return false; if (symbol != null && !symbol.IsStatic) { if (symbol is IFieldSymbol field) { return !field.IsConst && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, field.Type); } else if (symbol is IPropertySymbol property) { return property.Parameters.Length == 0 && property.IsWritableInConstructor() && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, property.Type); } } return false; } public async Task<Document> GetChangedDocumentAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { // See if there's an accessible base constructor that would accept these // types, then just call into that instead of generating fields. // // then, see if there are any constructors that would take the first 'n' arguments // we've provided. If so, delegate to those, and then create a field for any // remaining arguments. Try to match from largest to smallest. // // Otherwise, just generate a normal constructor that assigns any provided // parameters into fields. return await GenerateThisOrBaseDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false) ?? await GenerateMemberDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); } private async Task<Document?> GenerateThisOrBaseDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { if (_delegatedConstructor == null) return null; Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var (members, assignments) = await GenerateMembersAndAssignmentsAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); var isThis = _delegatedConstructor.ContainingType.OriginalDefinition.Equals(TypeToGenerateIn.OriginalDefinition); var delegatingArguments = provider.GetService<SyntaxGenerator>().CreateArguments(_delegatedConstructor.Parameters); var newParameters = _delegatedConstructor.Parameters.Concat(_parameters); var generateUnsafe = !IsContainedInUnsafeType && newParameters.Any(p => p.RequiresUnsafeModifier()); var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isUnsafe: generateUnsafe), typeName: TypeToGenerateIn.Name, parameters: newParameters, statements: assignments, baseConstructorArguments: isThis ? default : delegatingArguments, thisConstructorArguments: isThis ? delegatingArguments : default); return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, members.Concat(constructor), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } private async Task<(ImmutableArray<ISymbol>, ImmutableArray<SyntaxNode>)> GenerateMembersAndAssignmentsAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var members = withFields ? SyntaxGeneratorExtensions.CreateFieldsForParameters(_parameters, ParameterToNewFieldMap, IsContainedInUnsafeType) : withProperties ? SyntaxGeneratorExtensions.CreatePropertiesForParameters(_parameters, ParameterToNewPropertyMap, IsContainedInUnsafeType) : ImmutableArray<ISymbol>.Empty; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var assignments = !withFields && !withProperties ? ImmutableArray<SyntaxNode>.Empty : provider.GetService<SyntaxGenerator>().CreateAssignmentStatements( semanticModel, _parameters, _parameterToExistingMemberMap, withFields ? ParameterToNewFieldMap : ParameterToNewPropertyMap, addNullChecks: false, preferThrowExpression: false); return (members, assignments); } private async Task<Document> GenerateMemberDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newMemberMap = withFields ? ParameterToNewFieldMap : withProperties ? ParameterToNewPropertyMap : ImmutableDictionary<string, string>.Empty; return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, provider.GetService<SyntaxGenerator>().CreateMemberDelegatingConstructor( semanticModel, TypeToGenerateIn.Name, TypeToGenerateIn, _parameters, _parameterToExistingMemberMap, newMemberMap, addNullChecks: false, preferThrowExpression: false, generateProperties: withProperties, IsContainedInUnsafeType), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Emitter/NoPia/EmbeddedType.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; #if !DEBUG using NamedTypeSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol; using FieldSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol; using MethodSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol; using EventSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.EventSymbol; using PropertySymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.PropertySymbol; #endif namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia { internal sealed class EmbeddedType : EmbeddedTypesManager.CommonEmbeddedType { private bool _embeddedAllMembersOfImplementedInterface; public EmbeddedType(EmbeddedTypesManager typeManager, NamedTypeSymbolAdapter underlyingNamedType) : base(typeManager, underlyingNamedType) { Debug.Assert(underlyingNamedType.AdaptedNamedTypeSymbol.IsDefinition); Debug.Assert(underlyingNamedType.AdaptedNamedTypeSymbol.IsTopLevelType()); Debug.Assert(!underlyingNamedType.AdaptedNamedTypeSymbol.IsGenericType); } public void EmbedAllMembersOfImplementedInterface(SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Debug.Assert(UnderlyingNamedType.AdaptedNamedTypeSymbol.IsInterfaceType()); if (_embeddedAllMembersOfImplementedInterface) { return; } _embeddedAllMembersOfImplementedInterface = true; // Embed all members foreach (MethodSymbol m in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMethodsToEmit()) { if ((object)m != null) { TypeManager.EmbedMethod(this, m.GetCciAdapter(), syntaxNodeOpt, diagnostics); } } // We also should embed properties and events, but we don't need to do this explicitly here // because accessors embed them automatically. // Do the same for implemented interfaces. foreach (NamedTypeSymbol @interface in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetInterfacesToEmit()) { TypeManager.ModuleBeingBuilt.Translate(@interface, syntaxNodeOpt, diagnostics, fromImplements: true); } } protected override int GetAssemblyRefIndex() { ImmutableArray<AssemblySymbol> refs = TypeManager.ModuleBeingBuilt.SourceModule.GetReferencedAssemblySymbols(); return refs.IndexOf(UnderlyingNamedType.AdaptedNamedTypeSymbol.ContainingAssembly, ReferenceEqualityComparer.Instance); } protected override bool IsPublic { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.DeclaredAccessibility == Accessibility.Public; } } protected override Cci.ITypeReference GetBaseClass(PEModuleBuilder moduleBuilder, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { NamedTypeSymbol baseType = UnderlyingNamedType.AdaptedNamedTypeSymbol.BaseTypeNoUseSiteDiagnostics; return (object)baseType != null ? moduleBuilder.Translate(baseType, syntaxNodeOpt, diagnostics) : null; } protected override IEnumerable<FieldSymbolAdapter> GetFieldsToEmit() { return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetFieldsToEmit() #if DEBUG .Select(s => s.GetCciAdapter()) #endif ; } protected override IEnumerable<MethodSymbolAdapter> GetMethodsToEmit() { return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMethodsToEmit() #if DEBUG .Select(s => s?.GetCciAdapter()) #endif ; } protected override IEnumerable<EventSymbolAdapter> GetEventsToEmit() { return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetEventsToEmit() #if DEBUG .Select(s => s.GetCciAdapter()) #endif ; } protected override IEnumerable<PropertySymbolAdapter> GetPropertiesToEmit() { return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetPropertiesToEmit() #if DEBUG .Select(s => s.GetCciAdapter()) #endif ; } protected override IEnumerable<Cci.TypeReferenceWithAttributes> GetInterfaces(EmitContext context) { Debug.Assert((object)TypeManager.ModuleBeingBuilt == context.Module); PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module; foreach (NamedTypeSymbol @interface in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetInterfacesToEmit()) { var typeRef = moduleBeingBuilt.Translate( @interface, (CSharpSyntaxNode)context.SyntaxNode, context.Diagnostics); var type = TypeWithAnnotations.Create(@interface); yield return type.GetTypeRefWithAttributes( moduleBeingBuilt, declaringSymbol: UnderlyingNamedType.AdaptedNamedTypeSymbol, typeRef); } } protected override bool IsAbstract { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsMetadataAbstract; } } protected override bool IsBeforeFieldInit { get { switch (UnderlyingNamedType.AdaptedNamedTypeSymbol.TypeKind) { case TypeKind.Enum: case TypeKind.Delegate: //C# interfaces don't have fields so the flag doesn't really matter, but Dev10 omits it case TypeKind.Interface: return false; } // We shouldn't embed static constructor. return true; } } protected override bool IsComImport { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsComImport; } } protected override bool IsInterface { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsInterfaceType(); } } protected override bool IsDelegate { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsDelegateType(); } } protected override bool IsSerializable { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsSerializable; } } protected override bool IsSpecialName { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.HasSpecialName; } } protected override bool IsWindowsRuntimeImport { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsWindowsRuntimeImport; } } protected override bool IsSealed { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsMetadataSealed; } } protected override TypeLayout? GetTypeLayoutIfStruct() { if (UnderlyingNamedType.AdaptedNamedTypeSymbol.IsStructType()) { return UnderlyingNamedType.AdaptedNamedTypeSymbol.Layout; } return null; } protected override System.Runtime.InteropServices.CharSet StringFormat { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.MarshallingCharSet; } } protected override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetCustomAttributesToEmit(moduleBuilder); } protected override CSharpAttributeData CreateTypeIdentifierAttribute(bool hasGuid, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var member = hasGuid ? WellKnownMember.System_Runtime_InteropServices_TypeIdentifierAttribute__ctor : WellKnownMember.System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString; var ctor = TypeManager.GetWellKnownMethod(member, syntaxNodeOpt, diagnostics); if ((object)ctor == null) { return null; } if (hasGuid) { // This is an interface with a GuidAttribute, so we will generate the no-parameter TypeIdentifier. return new SynthesizedAttributeData(ctor, ImmutableArray<TypedConstant>.Empty, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } else { // This is an interface with no GuidAttribute, or some other type, so we will generate the // TypeIdentifier with name and scope parameters. // Look for a GUID attribute attached to type's containing assembly. If we find one, we'll use it; // otherwise, we expect that we will have reported an error (ERRID_PIAHasNoAssemblyGuid1) about this assembly, since // you can't /link against an assembly which lacks a GuidAttribute. var stringType = TypeManager.GetSystemStringType(syntaxNodeOpt, diagnostics); if ((object)stringType != null) { string guidString = TypeManager.GetAssemblyGuidString(UnderlyingNamedType.AdaptedNamedTypeSymbol.ContainingAssembly); return new SynthesizedAttributeData(ctor, ImmutableArray.Create(new TypedConstant(stringType, TypedConstantKind.Primitive, guidString), new TypedConstant(stringType, TypedConstantKind.Primitive, UnderlyingNamedType.AdaptedNamedTypeSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat))), ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } } return null; } protected override void ReportMissingAttribute(AttributeDescription description, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_InteropTypeMissingAttribute, syntaxNodeOpt, UnderlyingNamedType.AdaptedNamedTypeSymbol, description.FullName); } protected override void EmbedDefaultMembers(string defaultMember, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { foreach (Symbol s in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMembers(defaultMember)) { switch (s.Kind) { case SymbolKind.Field: TypeManager.EmbedField(this, ((FieldSymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics); break; case SymbolKind.Method: TypeManager.EmbedMethod(this, ((MethodSymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics); break; case SymbolKind.Property: TypeManager.EmbedProperty(this, ((PropertySymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics); break; case SymbolKind.Event: TypeManager.EmbedEvent(this, ((EventSymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding: false); 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.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; #if !DEBUG using NamedTypeSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol; using FieldSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.FieldSymbol; using MethodSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol; using EventSymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.EventSymbol; using PropertySymbolAdapter = Microsoft.CodeAnalysis.CSharp.Symbols.PropertySymbol; #endif namespace Microsoft.CodeAnalysis.CSharp.Emit.NoPia { internal sealed class EmbeddedType : EmbeddedTypesManager.CommonEmbeddedType { private bool _embeddedAllMembersOfImplementedInterface; public EmbeddedType(EmbeddedTypesManager typeManager, NamedTypeSymbolAdapter underlyingNamedType) : base(typeManager, underlyingNamedType) { Debug.Assert(underlyingNamedType.AdaptedNamedTypeSymbol.IsDefinition); Debug.Assert(underlyingNamedType.AdaptedNamedTypeSymbol.IsTopLevelType()); Debug.Assert(!underlyingNamedType.AdaptedNamedTypeSymbol.IsGenericType); } public void EmbedAllMembersOfImplementedInterface(SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Debug.Assert(UnderlyingNamedType.AdaptedNamedTypeSymbol.IsInterfaceType()); if (_embeddedAllMembersOfImplementedInterface) { return; } _embeddedAllMembersOfImplementedInterface = true; // Embed all members foreach (MethodSymbol m in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMethodsToEmit()) { if ((object)m != null) { TypeManager.EmbedMethod(this, m.GetCciAdapter(), syntaxNodeOpt, diagnostics); } } // We also should embed properties and events, but we don't need to do this explicitly here // because accessors embed them automatically. // Do the same for implemented interfaces. foreach (NamedTypeSymbol @interface in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetInterfacesToEmit()) { TypeManager.ModuleBeingBuilt.Translate(@interface, syntaxNodeOpt, diagnostics, fromImplements: true); } } protected override int GetAssemblyRefIndex() { ImmutableArray<AssemblySymbol> refs = TypeManager.ModuleBeingBuilt.SourceModule.GetReferencedAssemblySymbols(); return refs.IndexOf(UnderlyingNamedType.AdaptedNamedTypeSymbol.ContainingAssembly, ReferenceEqualityComparer.Instance); } protected override bool IsPublic { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.DeclaredAccessibility == Accessibility.Public; } } protected override Cci.ITypeReference GetBaseClass(PEModuleBuilder moduleBuilder, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { NamedTypeSymbol baseType = UnderlyingNamedType.AdaptedNamedTypeSymbol.BaseTypeNoUseSiteDiagnostics; return (object)baseType != null ? moduleBuilder.Translate(baseType, syntaxNodeOpt, diagnostics) : null; } protected override IEnumerable<FieldSymbolAdapter> GetFieldsToEmit() { return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetFieldsToEmit() #if DEBUG .Select(s => s.GetCciAdapter()) #endif ; } protected override IEnumerable<MethodSymbolAdapter> GetMethodsToEmit() { return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMethodsToEmit() #if DEBUG .Select(s => s?.GetCciAdapter()) #endif ; } protected override IEnumerable<EventSymbolAdapter> GetEventsToEmit() { return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetEventsToEmit() #if DEBUG .Select(s => s.GetCciAdapter()) #endif ; } protected override IEnumerable<PropertySymbolAdapter> GetPropertiesToEmit() { return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetPropertiesToEmit() #if DEBUG .Select(s => s.GetCciAdapter()) #endif ; } protected override IEnumerable<Cci.TypeReferenceWithAttributes> GetInterfaces(EmitContext context) { Debug.Assert((object)TypeManager.ModuleBeingBuilt == context.Module); PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module; foreach (NamedTypeSymbol @interface in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetInterfacesToEmit()) { var typeRef = moduleBeingBuilt.Translate( @interface, (CSharpSyntaxNode)context.SyntaxNode, context.Diagnostics); var type = TypeWithAnnotations.Create(@interface); yield return type.GetTypeRefWithAttributes( moduleBeingBuilt, declaringSymbol: UnderlyingNamedType.AdaptedNamedTypeSymbol, typeRef); } } protected override bool IsAbstract { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsMetadataAbstract; } } protected override bool IsBeforeFieldInit { get { switch (UnderlyingNamedType.AdaptedNamedTypeSymbol.TypeKind) { case TypeKind.Enum: case TypeKind.Delegate: //C# interfaces don't have fields so the flag doesn't really matter, but Dev10 omits it case TypeKind.Interface: return false; } // We shouldn't embed static constructor. return true; } } protected override bool IsComImport { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsComImport; } } protected override bool IsInterface { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsInterfaceType(); } } protected override bool IsDelegate { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsDelegateType(); } } protected override bool IsSerializable { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsSerializable; } } protected override bool IsSpecialName { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.HasSpecialName; } } protected override bool IsWindowsRuntimeImport { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsWindowsRuntimeImport; } } protected override bool IsSealed { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.IsMetadataSealed; } } protected override TypeLayout? GetTypeLayoutIfStruct() { if (UnderlyingNamedType.AdaptedNamedTypeSymbol.IsStructType()) { return UnderlyingNamedType.AdaptedNamedTypeSymbol.Layout; } return null; } protected override System.Runtime.InteropServices.CharSet StringFormat { get { return UnderlyingNamedType.AdaptedNamedTypeSymbol.MarshallingCharSet; } } protected override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { return UnderlyingNamedType.AdaptedNamedTypeSymbol.GetCustomAttributesToEmit(moduleBuilder); } protected override CSharpAttributeData CreateTypeIdentifierAttribute(bool hasGuid, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var member = hasGuid ? WellKnownMember.System_Runtime_InteropServices_TypeIdentifierAttribute__ctor : WellKnownMember.System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString; var ctor = TypeManager.GetWellKnownMethod(member, syntaxNodeOpt, diagnostics); if ((object)ctor == null) { return null; } if (hasGuid) { // This is an interface with a GuidAttribute, so we will generate the no-parameter TypeIdentifier. return new SynthesizedAttributeData(ctor, ImmutableArray<TypedConstant>.Empty, ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } else { // This is an interface with no GuidAttribute, or some other type, so we will generate the // TypeIdentifier with name and scope parameters. // Look for a GUID attribute attached to type's containing assembly. If we find one, we'll use it; // otherwise, we expect that we will have reported an error (ERRID_PIAHasNoAssemblyGuid1) about this assembly, since // you can't /link against an assembly which lacks a GuidAttribute. var stringType = TypeManager.GetSystemStringType(syntaxNodeOpt, diagnostics); if ((object)stringType != null) { string guidString = TypeManager.GetAssemblyGuidString(UnderlyingNamedType.AdaptedNamedTypeSymbol.ContainingAssembly); return new SynthesizedAttributeData(ctor, ImmutableArray.Create(new TypedConstant(stringType, TypedConstantKind.Primitive, guidString), new TypedConstant(stringType, TypedConstantKind.Primitive, UnderlyingNamedType.AdaptedNamedTypeSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat))), ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } } return null; } protected override void ReportMissingAttribute(AttributeDescription description, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { EmbeddedTypesManager.Error(diagnostics, ErrorCode.ERR_InteropTypeMissingAttribute, syntaxNodeOpt, UnderlyingNamedType.AdaptedNamedTypeSymbol, description.FullName); } protected override void EmbedDefaultMembers(string defaultMember, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { foreach (Symbol s in UnderlyingNamedType.AdaptedNamedTypeSymbol.GetMembers(defaultMember)) { switch (s.Kind) { case SymbolKind.Field: TypeManager.EmbedField(this, ((FieldSymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics); break; case SymbolKind.Method: TypeManager.EmbedMethod(this, ((MethodSymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics); break; case SymbolKind.Property: TypeManager.EmbedProperty(this, ((PropertySymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics); break; case SymbolKind.Event: TypeManager.EmbedEvent(this, ((EventSymbol)s).GetCciAdapter(), syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding: false); break; } } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Test/Semantic/Diagnostics/GetDiagnosticsTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class GetDiagnosticsTests Inherits BasicTestBase <Fact> Public Sub DiagnosticsFilteredInMethodBody() Dim source = <project><file> Class C Sub S() @ # ! End Sub End Class </file></project> Dim compilation = CreateCompilationWithMscorlib40(source) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()) ' CreateCompilation... method normalizes EOL chars of xml literals, ' so we cannot verify against spans in the original xml here as positions would differ Dim sourceText = compilation.SyntaxTrees.Single().GetText().ToString() DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "(?s)^.*$", "BC30035", "BC30248", "BC30203", "BC30157") DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "@", "BC30035") DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "#", "BC30248") DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "(?<=\!)", "BC30203", "BC30157") DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "!", "BC30203", "BC30157") End Sub <Fact> Public Sub DiagnosticsFilteredInMethodBodyInsideNamespace() Dim source = <project><file> Namespace N Class C Sub S() X End Sub End Class End Namespace Class D ReadOnly Property P As Integer Get Return Y End Get End Property End Class </file></project> Dim compilation = CreateCompilationWithMscorlib40(source) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()) Dim sourceText = compilation.SyntaxTrees.Single().GetText().ToString() DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "X", "BC30451") DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "Y", "BC30451") End Sub <Fact> Public Sub DiagnosticsFilteredForIntersectingIntervals() Dim source = <project><file> Class C Inherits Abracadabra End Class </file></project> Dim compilation = CreateCompilationWithMscorlib40(source) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()) ' CreateCompilation... method normalizes EOL chars of xml literals, ' so we cannot verify against spans in the original xml here as positions would differ Dim sourceText = compilation.SyntaxTrees.Single().GetText().ToString() Const ErrorId = "BC30002" DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "(?s)^.*$", ErrorId) DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "Abracadabra", ErrorId) DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "ts Abracadabra", ErrorId) DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "ts Abracadabr", ErrorId) DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "Abracadabra[\r\n]+", ErrorId) DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "bracadabra[\r\n]+", ErrorId) End Sub <Fact, WorkItem(1066483, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066483")> Public Sub TestDiagnosticWithSeverity() Dim source = <project><file> Class C Sub Goo() Dim x End Sub End Class </file></project> Dim compilation = CreateCompilationWithMscorlib40(source) Dim diag = compilation.GetDiagnostics().Single() Assert.Equal(DiagnosticSeverity.Warning, diag.Severity) Assert.Equal(1, diag.WarningLevel) Dim [error] = diag.WithSeverity(DiagnosticSeverity.Error) Assert.Equal(DiagnosticSeverity.Error, [error].Severity) Assert.Equal(DiagnosticSeverity.Warning, [error].DefaultSeverity) Assert.Equal(0, [error].WarningLevel) Dim warning = [error].WithSeverity(DiagnosticSeverity.Warning) Assert.Equal(DiagnosticSeverity.Warning, warning.Severity) Assert.Equal(DiagnosticSeverity.Warning, warning.DefaultSeverity) Assert.Equal(1, warning.WarningLevel) Dim hidden = warning.WithSeverity(DiagnosticSeverity.Hidden) Assert.Equal(DiagnosticSeverity.Hidden, hidden.Severity) Assert.Equal(DiagnosticSeverity.Warning, hidden.DefaultSeverity) Assert.Equal(1, hidden.WarningLevel) Dim info = warning.WithSeverity(DiagnosticSeverity.Info) Assert.Equal(DiagnosticSeverity.Info, info.Severity) Assert.Equal(DiagnosticSeverity.Warning, info.DefaultSeverity) Assert.Equal(1, info.WarningLevel) End Sub <Fact, WorkItem(7446, "https://github.com/dotnet/roslyn/issues/7446")> Public Sub TestCompilationEventQueueWithSemanticModelGetDiagnostics() Dim source1 = <file> Namespace N1 Partial Class C Private Sub NonPartialMethod1() End Sub End Class End Namespace </file>.Value Dim source2 = <file> Namespace N1 Partial Class C Private Sub NonPartialMethod2() End Sub End Class End Namespace </file>.Value Dim tree1 = VisualBasicSyntaxTree.ParseText(source1, path:="file1") Dim tree2 = VisualBasicSyntaxTree.ParseText(source2, path:="file2") Dim eventQueue = New AsyncQueue(Of CompilationEvent)() Dim compilation = CreateCompilationWithMscorlib45({tree1, tree2}).WithEventQueue(eventQueue) ' Invoke SemanticModel.GetDiagnostics to force populate the event queue for symbols in the first source file. Dim tree = compilation.SyntaxTrees.[Single](Function(t) t Is tree1) Dim root = tree.GetRoot() Dim model = compilation.GetSemanticModel(tree) model.GetDiagnostics(root.FullSpan) Assert.True(eventQueue.Count > 0) Dim compilationStartedFired As Boolean Dim declaredSymbolNames As HashSet(Of String) = Nothing, completedCompilationUnits As HashSet(Of String) = Nothing Assert.True(DequeueCompilationEvents(eventQueue, compilationStartedFired, declaredSymbolNames, completedCompilationUnits)) ' Verify symbol declared events fired for all symbols declared in the first source file. Assert.True(compilationStartedFired) Assert.True(declaredSymbolNames.Contains(compilation.GlobalNamespace.Name)) Assert.True(declaredSymbolNames.Contains("N1")) Assert.True(declaredSymbolNames.Contains("C")) Assert.True(declaredSymbolNames.Contains("NonPartialMethod1")) Assert.True(completedCompilationUnits.Contains(tree.FilePath)) End Sub <Fact, WorkItem(7477, "https://github.com/dotnet/roslyn/issues/7477")> Public Sub TestCompilationEventsForPartialMethod() Dim source1 = <file> Namespace N1 Partial Class C Private Sub NonPartialMethod1() End Sub Private Partial Sub PartialMethod() ' Declaration End Sub Private Partial Sub ImpartialMethod() ' Declaration End Sub End Class End Namespace </file>.Value Dim source2 = <file> Namespace N1 Partial Class C Private Sub NonPartialMethod2() End Sub Private Sub PartialMethod() ' Implementation End Sub End Class End Namespace </file>.Value Dim tree1 = VisualBasicSyntaxTree.ParseText(source1, path:="file1") Dim tree2 = VisualBasicSyntaxTree.ParseText(source2, path:="file2") Dim eventQueue = New AsyncQueue(Of CompilationEvent)() Dim compilation = CreateCompilationWithMscorlib45({tree1, tree2}).WithEventQueue(eventQueue) ' Invoke SemanticModel.GetDiagnostics to force populate the event queue for symbols in the first source file. Dim tree = compilation.SyntaxTrees.[Single](Function(t) t Is tree1) Dim root = tree.GetRoot() Dim model = compilation.GetSemanticModel(tree) model.GetDiagnostics(root.FullSpan) Assert.True(eventQueue.Count > 0) Dim compilationStartedFired As Boolean Dim declaredSymbolNames As HashSet(Of String) = Nothing, completedCompilationUnits As HashSet(Of String) = Nothing Assert.True(DequeueCompilationEvents(eventQueue, compilationStartedFired, declaredSymbolNames, completedCompilationUnits)) ' Verify symbol declared events fired for all symbols declared in the first source file. Assert.True(compilationStartedFired) Assert.True(declaredSymbolNames.Contains(compilation.GlobalNamespace.Name)) Assert.True(declaredSymbolNames.Contains("N1")) Assert.True(declaredSymbolNames.Contains("C")) Assert.True(declaredSymbolNames.Contains("NonPartialMethod1")) Assert.True(declaredSymbolNames.Contains("ImpartialMethod")) Assert.True(declaredSymbolNames.Contains("PartialMethod")) Assert.True(completedCompilationUnits.Contains(tree.FilePath)) End Sub <Fact> Public Sub CompilingCodeWithInvalidPreProcessorSymbolsShouldProvideDiagnostics() Dim dict = New Dictionary(Of String, Object) dict.Add("1", Nothing) Dim compilation = CreateEmptyCompilation(String.Empty, parseOptions:=New VisualBasicParseOptions().WithPreprocessorSymbols(dict)) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC31030: Conditional compilation constant '1' is not valid: Identifier expected. ~ </errors>) End Sub <Fact> Public Sub CompilingCodeWithInvalidSourceCodeKindShouldProvideDiagnostics() #Disable Warning BC40000 ' Type or member is obsolete Dim compilation = CreateCompilationWithMscorlib45(String.Empty, parseOptions:=New VisualBasicParseOptions().WithKind(SourceCodeKind.Interactive)) #Enable Warning BC40000 ' Type or member is obsolete CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC37285: Provided source code kind is unsupported or invalid: 'Interactive' ~ </errors>) End Sub <Fact> Public Sub CompilingCodeWithInvalidLanguageVersionShouldProvideDiagnostics() Dim compilation = CreateEmptyCompilation(String.Empty, parseOptions:=New VisualBasicParseOptions().WithLanguageVersion(DirectCast(10000, LanguageVersion))) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC37287: Provided language version is unsupported or invalid: '10000'. ~ </errors>) End Sub <Fact> Public Sub CompilingCodeWithInvalidDocumentationModeShouldProvideDiagnostics() Dim compilation = CreateEmptyCompilation(String.Empty, parseOptions:=New VisualBasicParseOptions().WithDocumentationMode(CType(100, DocumentationMode))) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC37286: Provided documentation mode is unsupported or invalid: '100'. ~ </errors>) End Sub <Fact> Public Sub CompilingCodeWithInvalidParseOptionsInMultipleSyntaxTreesShouldReportThemAll() Dim dict1 = New Dictionary(Of String, Object) dict1.Add("1", Nothing) Dim dict2 = New Dictionary(Of String, Object) dict2.Add("2", Nothing) Dim dict3 = New Dictionary(Of String, Object) dict3.Add("3", Nothing) Dim syntaxTree1 = Parse(String.Empty, options:=New VisualBasicParseOptions().WithPreprocessorSymbols(dict1)) Dim syntaxTree2 = Parse(String.Empty, options:=New VisualBasicParseOptions().WithPreprocessorSymbols(dict2)) Dim syntaxTree3 = Parse(String.Empty, options:=New VisualBasicParseOptions().WithPreprocessorSymbols(dict3)) Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary) Dim compilation = CreateCompilationWithMscorlib40({syntaxTree1, syntaxTree2, syntaxTree3}, options:=options) Dim diagnostics = compilation.GetDiagnostics() CompilationUtils.AssertTheseDiagnostics(diagnostics, <errors> BC31030: Conditional compilation constant '1' is not valid: Identifier expected. ~ BC31030: Conditional compilation constant '2' is not valid: Identifier expected. ~ BC31030: Conditional compilation constant '3' is not valid: Identifier expected. ~ </errors>) Assert.True(diagnostics(0).Location.SourceTree.Equals(syntaxTree1)) Assert.True(diagnostics(1).Location.SourceTree.Equals(syntaxTree2)) Assert.True(diagnostics(2).Location.SourceTree.Equals(syntaxTree3)) End Sub <Fact> Public Sub CompilingCodeWithSameParseOptionsInMultipleSyntaxTreesShouldReportOnlyNonDuplicates() Dim dict1 = New Dictionary(Of String, Object) dict1.Add("1", Nothing) Dim dict2 = New Dictionary(Of String, Object) dict2.Add("2", Nothing) Dim parseOptions1 = New VisualBasicParseOptions().WithPreprocessorSymbols(dict1) Dim parseOptions2 = New VisualBasicParseOptions().WithPreprocessorSymbols(dict2) Dim syntaxTree1 = Parse(String.Empty, options:=parseOptions1) Dim syntaxTree2 = Parse(String.Empty, options:=parseOptions2) Dim syntaxTree3 = Parse(String.Empty, options:=parseOptions2) Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary) Dim compilation = CreateCompilationWithMscorlib40({syntaxTree1, syntaxTree2, syntaxTree3}, options:=options) Dim diagnostics = compilation.GetDiagnostics() CompilationUtils.AssertTheseDiagnostics(diagnostics, <errors> BC31030: Conditional compilation constant '1' is not valid: Identifier expected. ~ BC31030: Conditional compilation constant '2' is not valid: Identifier expected. ~ </errors>) Assert.True(diagnostics(0).Location.SourceTree.Equals(syntaxTree1)) Assert.True(diagnostics(1).Location.SourceTree.Equals(syntaxTree2)) End Sub <Fact> Public Sub DiagnosticsInCompilationOptionsParseOptionsAreDedupedWithParseTreesParseOptions() Dim dict1 = New Dictionary(Of String, Object) dict1.Add("1", Nothing) Dim dict2 = New Dictionary(Of String, Object) dict2.Add("2", Nothing) Dim parseOptions1 = New VisualBasicParseOptions().WithPreprocessorSymbols(dict1) Dim parseOptions2 = New VisualBasicParseOptions().WithPreprocessorSymbols(dict2) Dim syntaxTree1 = Parse(String.Empty, options:=parseOptions1) Dim syntaxTree2 = Parse(String.Empty, options:=parseOptions2) Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, parseOptions:=parseOptions1) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime({syntaxTree1, syntaxTree2}, options:=options) Dim diagnostics = compilation.GetDiagnostics() CompilationUtils.AssertTheseDiagnostics(diagnostics, <errors> BC31030: Conditional compilation constant '1' is not valid: Identifier expected. BC31030: Conditional compilation constant '2' is not valid: Identifier expected. ~ </errors>) Assert.Equal("2", diagnostics(0).Arguments(1)) Assert.True(diagnostics(0).Location.SourceTree.Equals(syntaxTree2)) ' Syntax tree parse options are reported in CompilationStage.Parse Assert.Equal("1", diagnostics(1).Arguments(1)) Assert.Null(diagnostics(1).Location.SourceTree) ' Compilation parse options are reported in CompilationStage.Declare End Sub <Fact> Public Sub DiagnosticsInCompilationOptionsParseOptionsAreReportedSeparately() Dim dict1 = New Dictionary(Of String, Object) dict1.Add("1", Nothing) Dim dict2 = New Dictionary(Of String, Object) dict2.Add("2", Nothing) Dim parseOptions1 = New VisualBasicParseOptions().WithPreprocessorSymbols(dict1) Dim parseOptions2 = New VisualBasicParseOptions().WithPreprocessorSymbols(dict2) Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, parseOptions:=parseOptions1) CompilationUtils.AssertTheseDiagnostics(options.Errors, <errors> BC31030: Conditional compilation constant '1' is not valid: Identifier expected. </errors>) Dim syntaxTree = Parse(String.Empty, options:=parseOptions2) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime({syntaxTree}, options:=options) Dim diagnostics = compilation.GetDiagnostics() CompilationUtils.AssertTheseDiagnostics(diagnostics, <errors> BC31030: Conditional compilation constant '1' is not valid: Identifier expected. BC31030: Conditional compilation constant '2' is not valid: Identifier expected. ~ </errors>) Assert.Equal("2", diagnostics(0).Arguments(1)) Assert.True(diagnostics(0).Location.SourceTree.Equals(syntaxTree)) ' Syntax tree parse options are reported in CompilationStage.Parse Assert.Equal("1", diagnostics(1).Arguments(1)) Assert.Null(diagnostics(1).Location.SourceTree) ' Compilation parse options are reported in CompilationStage.Declare End Sub Private Shared Function DequeueCompilationEvents(eventQueue As AsyncQueue(Of CompilationEvent), ByRef compilationStartedFired As Boolean, ByRef declaredSymbolNames As HashSet(Of String), ByRef completedCompilationUnits As HashSet(Of String)) As Boolean compilationStartedFired = False declaredSymbolNames = New HashSet(Of String)() completedCompilationUnits = New HashSet(Of String)() If eventQueue.Count = 0 Then Return False End If Dim compEvent As CompilationEvent = Nothing While eventQueue.TryDequeue(compEvent) If TypeOf compEvent Is CompilationStartedEvent Then Assert.[False](compilationStartedFired, "Unexpected multiple compilation stated events") compilationStartedFired = True Else Dim symbolDeclaredEvent = TryCast(compEvent, SymbolDeclaredCompilationEvent) If symbolDeclaredEvent IsNot Nothing Then Dim symbol = symbolDeclaredEvent.Symbol Dim added = declaredSymbolNames.Add(symbol.Name) If Not added Then Dim method = TryCast(symbol, Symbols.MethodSymbol) Assert.NotNull(method) Dim isPartialMethod = method.PartialDefinitionPart IsNot Nothing OrElse method.PartialImplementationPart IsNot Nothing Assert.True(isPartialMethod, "Unexpected multiple symbol declared events for same symbol " + symbol.Name) End If Else Dim compilationCompletedEvent = TryCast(compEvent, CompilationUnitCompletedEvent) If compilationCompletedEvent IsNot Nothing Then Assert.True(completedCompilationUnits.Add(compilationCompletedEvent.CompilationUnit.FilePath)) End If End If End If End While Return True End Function <Fact> Public Sub TestEventQueueCompletionForEmptyCompilation() Dim compilation = CreateCompilationWithMscorlib45(source:=Nothing).WithEventQueue(New AsyncQueue(Of CompilationEvent)()) ' Force complete compilation event queue Dim unused = compilation.GetDiagnostics() Assert.True(compilation.EventQueue.IsCompleted) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class GetDiagnosticsTests Inherits BasicTestBase <Fact> Public Sub DiagnosticsFilteredInMethodBody() Dim source = <project><file> Class C Sub S() @ # ! End Sub End Class </file></project> Dim compilation = CreateCompilationWithMscorlib40(source) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()) ' CreateCompilation... method normalizes EOL chars of xml literals, ' so we cannot verify against spans in the original xml here as positions would differ Dim sourceText = compilation.SyntaxTrees.Single().GetText().ToString() DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "(?s)^.*$", "BC30035", "BC30248", "BC30203", "BC30157") DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "@", "BC30035") DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "#", "BC30248") DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "(?<=\!)", "BC30203", "BC30157") DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "!", "BC30203", "BC30157") End Sub <Fact> Public Sub DiagnosticsFilteredInMethodBodyInsideNamespace() Dim source = <project><file> Namespace N Class C Sub S() X End Sub End Class End Namespace Class D ReadOnly Property P As Integer Get Return Y End Get End Property End Class </file></project> Dim compilation = CreateCompilationWithMscorlib40(source) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()) Dim sourceText = compilation.SyntaxTrees.Single().GetText().ToString() DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "X", "BC30451") DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "Y", "BC30451") End Sub <Fact> Public Sub DiagnosticsFilteredForIntersectingIntervals() Dim source = <project><file> Class C Inherits Abracadabra End Class </file></project> Dim compilation = CreateCompilationWithMscorlib40(source) Dim model = compilation.GetSemanticModel(compilation.SyntaxTrees.Single()) ' CreateCompilation... method normalizes EOL chars of xml literals, ' so we cannot verify against spans in the original xml here as positions would differ Dim sourceText = compilation.SyntaxTrees.Single().GetText().ToString() Const ErrorId = "BC30002" DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "(?s)^.*$", ErrorId) DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "Abracadabra", ErrorId) DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "ts Abracadabra", ErrorId) DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "ts Abracadabr", ErrorId) DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "Abracadabra[\r\n]+", ErrorId) DiagnosticsHelper.VerifyDiagnostics(model, sourceText, "bracadabra[\r\n]+", ErrorId) End Sub <Fact, WorkItem(1066483, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066483")> Public Sub TestDiagnosticWithSeverity() Dim source = <project><file> Class C Sub Goo() Dim x End Sub End Class </file></project> Dim compilation = CreateCompilationWithMscorlib40(source) Dim diag = compilation.GetDiagnostics().Single() Assert.Equal(DiagnosticSeverity.Warning, diag.Severity) Assert.Equal(1, diag.WarningLevel) Dim [error] = diag.WithSeverity(DiagnosticSeverity.Error) Assert.Equal(DiagnosticSeverity.Error, [error].Severity) Assert.Equal(DiagnosticSeverity.Warning, [error].DefaultSeverity) Assert.Equal(0, [error].WarningLevel) Dim warning = [error].WithSeverity(DiagnosticSeverity.Warning) Assert.Equal(DiagnosticSeverity.Warning, warning.Severity) Assert.Equal(DiagnosticSeverity.Warning, warning.DefaultSeverity) Assert.Equal(1, warning.WarningLevel) Dim hidden = warning.WithSeverity(DiagnosticSeverity.Hidden) Assert.Equal(DiagnosticSeverity.Hidden, hidden.Severity) Assert.Equal(DiagnosticSeverity.Warning, hidden.DefaultSeverity) Assert.Equal(1, hidden.WarningLevel) Dim info = warning.WithSeverity(DiagnosticSeverity.Info) Assert.Equal(DiagnosticSeverity.Info, info.Severity) Assert.Equal(DiagnosticSeverity.Warning, info.DefaultSeverity) Assert.Equal(1, info.WarningLevel) End Sub <Fact, WorkItem(7446, "https://github.com/dotnet/roslyn/issues/7446")> Public Sub TestCompilationEventQueueWithSemanticModelGetDiagnostics() Dim source1 = <file> Namespace N1 Partial Class C Private Sub NonPartialMethod1() End Sub End Class End Namespace </file>.Value Dim source2 = <file> Namespace N1 Partial Class C Private Sub NonPartialMethod2() End Sub End Class End Namespace </file>.Value Dim tree1 = VisualBasicSyntaxTree.ParseText(source1, path:="file1") Dim tree2 = VisualBasicSyntaxTree.ParseText(source2, path:="file2") Dim eventQueue = New AsyncQueue(Of CompilationEvent)() Dim compilation = CreateCompilationWithMscorlib45({tree1, tree2}).WithEventQueue(eventQueue) ' Invoke SemanticModel.GetDiagnostics to force populate the event queue for symbols in the first source file. Dim tree = compilation.SyntaxTrees.[Single](Function(t) t Is tree1) Dim root = tree.GetRoot() Dim model = compilation.GetSemanticModel(tree) model.GetDiagnostics(root.FullSpan) Assert.True(eventQueue.Count > 0) Dim compilationStartedFired As Boolean Dim declaredSymbolNames As HashSet(Of String) = Nothing, completedCompilationUnits As HashSet(Of String) = Nothing Assert.True(DequeueCompilationEvents(eventQueue, compilationStartedFired, declaredSymbolNames, completedCompilationUnits)) ' Verify symbol declared events fired for all symbols declared in the first source file. Assert.True(compilationStartedFired) Assert.True(declaredSymbolNames.Contains(compilation.GlobalNamespace.Name)) Assert.True(declaredSymbolNames.Contains("N1")) Assert.True(declaredSymbolNames.Contains("C")) Assert.True(declaredSymbolNames.Contains("NonPartialMethod1")) Assert.True(completedCompilationUnits.Contains(tree.FilePath)) End Sub <Fact, WorkItem(7477, "https://github.com/dotnet/roslyn/issues/7477")> Public Sub TestCompilationEventsForPartialMethod() Dim source1 = <file> Namespace N1 Partial Class C Private Sub NonPartialMethod1() End Sub Private Partial Sub PartialMethod() ' Declaration End Sub Private Partial Sub ImpartialMethod() ' Declaration End Sub End Class End Namespace </file>.Value Dim source2 = <file> Namespace N1 Partial Class C Private Sub NonPartialMethod2() End Sub Private Sub PartialMethod() ' Implementation End Sub End Class End Namespace </file>.Value Dim tree1 = VisualBasicSyntaxTree.ParseText(source1, path:="file1") Dim tree2 = VisualBasicSyntaxTree.ParseText(source2, path:="file2") Dim eventQueue = New AsyncQueue(Of CompilationEvent)() Dim compilation = CreateCompilationWithMscorlib45({tree1, tree2}).WithEventQueue(eventQueue) ' Invoke SemanticModel.GetDiagnostics to force populate the event queue for symbols in the first source file. Dim tree = compilation.SyntaxTrees.[Single](Function(t) t Is tree1) Dim root = tree.GetRoot() Dim model = compilation.GetSemanticModel(tree) model.GetDiagnostics(root.FullSpan) Assert.True(eventQueue.Count > 0) Dim compilationStartedFired As Boolean Dim declaredSymbolNames As HashSet(Of String) = Nothing, completedCompilationUnits As HashSet(Of String) = Nothing Assert.True(DequeueCompilationEvents(eventQueue, compilationStartedFired, declaredSymbolNames, completedCompilationUnits)) ' Verify symbol declared events fired for all symbols declared in the first source file. Assert.True(compilationStartedFired) Assert.True(declaredSymbolNames.Contains(compilation.GlobalNamespace.Name)) Assert.True(declaredSymbolNames.Contains("N1")) Assert.True(declaredSymbolNames.Contains("C")) Assert.True(declaredSymbolNames.Contains("NonPartialMethod1")) Assert.True(declaredSymbolNames.Contains("ImpartialMethod")) Assert.True(declaredSymbolNames.Contains("PartialMethod")) Assert.True(completedCompilationUnits.Contains(tree.FilePath)) End Sub <Fact> Public Sub CompilingCodeWithInvalidPreProcessorSymbolsShouldProvideDiagnostics() Dim dict = New Dictionary(Of String, Object) dict.Add("1", Nothing) Dim compilation = CreateEmptyCompilation(String.Empty, parseOptions:=New VisualBasicParseOptions().WithPreprocessorSymbols(dict)) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC31030: Conditional compilation constant '1' is not valid: Identifier expected. ~ </errors>) End Sub <Fact> Public Sub CompilingCodeWithInvalidSourceCodeKindShouldProvideDiagnostics() #Disable Warning BC40000 ' Type or member is obsolete Dim compilation = CreateCompilationWithMscorlib45(String.Empty, parseOptions:=New VisualBasicParseOptions().WithKind(SourceCodeKind.Interactive)) #Enable Warning BC40000 ' Type or member is obsolete CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC37285: Provided source code kind is unsupported or invalid: 'Interactive' ~ </errors>) End Sub <Fact> Public Sub CompilingCodeWithInvalidLanguageVersionShouldProvideDiagnostics() Dim compilation = CreateEmptyCompilation(String.Empty, parseOptions:=New VisualBasicParseOptions().WithLanguageVersion(DirectCast(10000, LanguageVersion))) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC37287: Provided language version is unsupported or invalid: '10000'. ~ </errors>) End Sub <Fact> Public Sub CompilingCodeWithInvalidDocumentationModeShouldProvideDiagnostics() Dim compilation = CreateEmptyCompilation(String.Empty, parseOptions:=New VisualBasicParseOptions().WithDocumentationMode(CType(100, DocumentationMode))) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC37286: Provided documentation mode is unsupported or invalid: '100'. ~ </errors>) End Sub <Fact> Public Sub CompilingCodeWithInvalidParseOptionsInMultipleSyntaxTreesShouldReportThemAll() Dim dict1 = New Dictionary(Of String, Object) dict1.Add("1", Nothing) Dim dict2 = New Dictionary(Of String, Object) dict2.Add("2", Nothing) Dim dict3 = New Dictionary(Of String, Object) dict3.Add("3", Nothing) Dim syntaxTree1 = Parse(String.Empty, options:=New VisualBasicParseOptions().WithPreprocessorSymbols(dict1)) Dim syntaxTree2 = Parse(String.Empty, options:=New VisualBasicParseOptions().WithPreprocessorSymbols(dict2)) Dim syntaxTree3 = Parse(String.Empty, options:=New VisualBasicParseOptions().WithPreprocessorSymbols(dict3)) Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary) Dim compilation = CreateCompilationWithMscorlib40({syntaxTree1, syntaxTree2, syntaxTree3}, options:=options) Dim diagnostics = compilation.GetDiagnostics() CompilationUtils.AssertTheseDiagnostics(diagnostics, <errors> BC31030: Conditional compilation constant '1' is not valid: Identifier expected. ~ BC31030: Conditional compilation constant '2' is not valid: Identifier expected. ~ BC31030: Conditional compilation constant '3' is not valid: Identifier expected. ~ </errors>) Assert.True(diagnostics(0).Location.SourceTree.Equals(syntaxTree1)) Assert.True(diagnostics(1).Location.SourceTree.Equals(syntaxTree2)) Assert.True(diagnostics(2).Location.SourceTree.Equals(syntaxTree3)) End Sub <Fact> Public Sub CompilingCodeWithSameParseOptionsInMultipleSyntaxTreesShouldReportOnlyNonDuplicates() Dim dict1 = New Dictionary(Of String, Object) dict1.Add("1", Nothing) Dim dict2 = New Dictionary(Of String, Object) dict2.Add("2", Nothing) Dim parseOptions1 = New VisualBasicParseOptions().WithPreprocessorSymbols(dict1) Dim parseOptions2 = New VisualBasicParseOptions().WithPreprocessorSymbols(dict2) Dim syntaxTree1 = Parse(String.Empty, options:=parseOptions1) Dim syntaxTree2 = Parse(String.Empty, options:=parseOptions2) Dim syntaxTree3 = Parse(String.Empty, options:=parseOptions2) Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary) Dim compilation = CreateCompilationWithMscorlib40({syntaxTree1, syntaxTree2, syntaxTree3}, options:=options) Dim diagnostics = compilation.GetDiagnostics() CompilationUtils.AssertTheseDiagnostics(diagnostics, <errors> BC31030: Conditional compilation constant '1' is not valid: Identifier expected. ~ BC31030: Conditional compilation constant '2' is not valid: Identifier expected. ~ </errors>) Assert.True(diagnostics(0).Location.SourceTree.Equals(syntaxTree1)) Assert.True(diagnostics(1).Location.SourceTree.Equals(syntaxTree2)) End Sub <Fact> Public Sub DiagnosticsInCompilationOptionsParseOptionsAreDedupedWithParseTreesParseOptions() Dim dict1 = New Dictionary(Of String, Object) dict1.Add("1", Nothing) Dim dict2 = New Dictionary(Of String, Object) dict2.Add("2", Nothing) Dim parseOptions1 = New VisualBasicParseOptions().WithPreprocessorSymbols(dict1) Dim parseOptions2 = New VisualBasicParseOptions().WithPreprocessorSymbols(dict2) Dim syntaxTree1 = Parse(String.Empty, options:=parseOptions1) Dim syntaxTree2 = Parse(String.Empty, options:=parseOptions2) Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, parseOptions:=parseOptions1) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime({syntaxTree1, syntaxTree2}, options:=options) Dim diagnostics = compilation.GetDiagnostics() CompilationUtils.AssertTheseDiagnostics(diagnostics, <errors> BC31030: Conditional compilation constant '1' is not valid: Identifier expected. BC31030: Conditional compilation constant '2' is not valid: Identifier expected. ~ </errors>) Assert.Equal("2", diagnostics(0).Arguments(1)) Assert.True(diagnostics(0).Location.SourceTree.Equals(syntaxTree2)) ' Syntax tree parse options are reported in CompilationStage.Parse Assert.Equal("1", diagnostics(1).Arguments(1)) Assert.Null(diagnostics(1).Location.SourceTree) ' Compilation parse options are reported in CompilationStage.Declare End Sub <Fact> Public Sub DiagnosticsInCompilationOptionsParseOptionsAreReportedSeparately() Dim dict1 = New Dictionary(Of String, Object) dict1.Add("1", Nothing) Dim dict2 = New Dictionary(Of String, Object) dict2.Add("2", Nothing) Dim parseOptions1 = New VisualBasicParseOptions().WithPreprocessorSymbols(dict1) Dim parseOptions2 = New VisualBasicParseOptions().WithPreprocessorSymbols(dict2) Dim options = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, parseOptions:=parseOptions1) CompilationUtils.AssertTheseDiagnostics(options.Errors, <errors> BC31030: Conditional compilation constant '1' is not valid: Identifier expected. </errors>) Dim syntaxTree = Parse(String.Empty, options:=parseOptions2) Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime({syntaxTree}, options:=options) Dim diagnostics = compilation.GetDiagnostics() CompilationUtils.AssertTheseDiagnostics(diagnostics, <errors> BC31030: Conditional compilation constant '1' is not valid: Identifier expected. BC31030: Conditional compilation constant '2' is not valid: Identifier expected. ~ </errors>) Assert.Equal("2", diagnostics(0).Arguments(1)) Assert.True(diagnostics(0).Location.SourceTree.Equals(syntaxTree)) ' Syntax tree parse options are reported in CompilationStage.Parse Assert.Equal("1", diagnostics(1).Arguments(1)) Assert.Null(diagnostics(1).Location.SourceTree) ' Compilation parse options are reported in CompilationStage.Declare End Sub Private Shared Function DequeueCompilationEvents(eventQueue As AsyncQueue(Of CompilationEvent), ByRef compilationStartedFired As Boolean, ByRef declaredSymbolNames As HashSet(Of String), ByRef completedCompilationUnits As HashSet(Of String)) As Boolean compilationStartedFired = False declaredSymbolNames = New HashSet(Of String)() completedCompilationUnits = New HashSet(Of String)() If eventQueue.Count = 0 Then Return False End If Dim compEvent As CompilationEvent = Nothing While eventQueue.TryDequeue(compEvent) If TypeOf compEvent Is CompilationStartedEvent Then Assert.[False](compilationStartedFired, "Unexpected multiple compilation stated events") compilationStartedFired = True Else Dim symbolDeclaredEvent = TryCast(compEvent, SymbolDeclaredCompilationEvent) If symbolDeclaredEvent IsNot Nothing Then Dim symbol = symbolDeclaredEvent.Symbol Dim added = declaredSymbolNames.Add(symbol.Name) If Not added Then Dim method = TryCast(symbol, Symbols.MethodSymbol) Assert.NotNull(method) Dim isPartialMethod = method.PartialDefinitionPart IsNot Nothing OrElse method.PartialImplementationPart IsNot Nothing Assert.True(isPartialMethod, "Unexpected multiple symbol declared events for same symbol " + symbol.Name) End If Else Dim compilationCompletedEvent = TryCast(compEvent, CompilationUnitCompletedEvent) If compilationCompletedEvent IsNot Nothing Then Assert.True(completedCompilationUnits.Add(compilationCompletedEvent.CompilationUnit.FilePath)) End If End If End If End While Return True End Function <Fact> Public Sub TestEventQueueCompletionForEmptyCompilation() Dim compilation = CreateCompilationWithMscorlib45(source:=Nothing).WithEventQueue(New AsyncQueue(Of CompilationEvent)()) ' Force complete compilation event queue Dim unused = compilation.GetDiagnostics() Assert.True(compilation.EventQueue.IsCompleted) End Sub End Class End Namespace
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/Tests/UseVarTestExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; #if CODE_STYLE using AbstractCodeActionOrUserDiagnosticTest = Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest; #endif namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions { internal static class UseVarTestExtensions { private static readonly CodeStyleOption2<bool> onWithNone = new CodeStyleOption2<bool>(true, NotificationOption2.None); private static readonly CodeStyleOption2<bool> offWithNone = new CodeStyleOption2<bool>(false, NotificationOption2.None); private static readonly CodeStyleOption2<bool> onWithSilent = new CodeStyleOption2<bool>(true, NotificationOption2.Silent); private static readonly CodeStyleOption2<bool> offWithSilent = new CodeStyleOption2<bool>(false, NotificationOption2.Silent); private static readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); private static readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion); private static readonly CodeStyleOption2<bool> onWithWarning = new CodeStyleOption2<bool>(true, NotificationOption2.Warning); private static readonly CodeStyleOption2<bool> offWithWarning = new CodeStyleOption2<bool>(false, NotificationOption2.Warning); private static readonly CodeStyleOption2<bool> offWithError = new CodeStyleOption2<bool>(false, NotificationOption2.Error); private static readonly CodeStyleOption2<bool> onWithError = new CodeStyleOption2<bool>(true, NotificationOption2.Error); public static OptionsCollection PreferExplicitTypeWithError(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithError }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithError }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithError }, }; public static OptionsCollection PreferImplicitTypeWithError(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithError }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithError }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithError }, }; public static OptionsCollection PreferExplicitTypeWithWarning(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithWarning }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithWarning }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithWarning }, }; public static OptionsCollection PreferImplicitTypeWithWarning(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithWarning }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithWarning }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithWarning }, }; public static OptionsCollection PreferExplicitTypeWithInfo(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; public static OptionsCollection PreferImplicitTypeWithInfo(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithInfo }, }; public static OptionsCollection PreferExplicitTypeWithSilent(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithSilent }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithSilent }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithSilent }, }; public static OptionsCollection PreferImplicitTypeWithSilent(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithSilent }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithSilent }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithSilent }, }; public static OptionsCollection PreferExplicitTypeWithNone(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithNone }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithNone }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithNone }, }; public static OptionsCollection PreferImplicitTypeWithNone(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithNone }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithNone }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithNone }, }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; #if CODE_STYLE using AbstractCodeActionOrUserDiagnosticTest = Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest; #endif namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions { internal static class UseVarTestExtensions { private static readonly CodeStyleOption2<bool> onWithNone = new CodeStyleOption2<bool>(true, NotificationOption2.None); private static readonly CodeStyleOption2<bool> offWithNone = new CodeStyleOption2<bool>(false, NotificationOption2.None); private static readonly CodeStyleOption2<bool> onWithSilent = new CodeStyleOption2<bool>(true, NotificationOption2.Silent); private static readonly CodeStyleOption2<bool> offWithSilent = new CodeStyleOption2<bool>(false, NotificationOption2.Silent); private static readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); private static readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion); private static readonly CodeStyleOption2<bool> onWithWarning = new CodeStyleOption2<bool>(true, NotificationOption2.Warning); private static readonly CodeStyleOption2<bool> offWithWarning = new CodeStyleOption2<bool>(false, NotificationOption2.Warning); private static readonly CodeStyleOption2<bool> offWithError = new CodeStyleOption2<bool>(false, NotificationOption2.Error); private static readonly CodeStyleOption2<bool> onWithError = new CodeStyleOption2<bool>(true, NotificationOption2.Error); public static OptionsCollection PreferExplicitTypeWithError(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithError }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithError }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithError }, }; public static OptionsCollection PreferImplicitTypeWithError(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithError }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithError }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithError }, }; public static OptionsCollection PreferExplicitTypeWithWarning(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithWarning }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithWarning }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithWarning }, }; public static OptionsCollection PreferImplicitTypeWithWarning(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithWarning }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithWarning }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithWarning }, }; public static OptionsCollection PreferExplicitTypeWithInfo(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; public static OptionsCollection PreferImplicitTypeWithInfo(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithInfo }, }; public static OptionsCollection PreferExplicitTypeWithSilent(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithSilent }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithSilent }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithSilent }, }; public static OptionsCollection PreferImplicitTypeWithSilent(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithSilent }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithSilent }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithSilent }, }; public static OptionsCollection PreferExplicitTypeWithNone(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithNone }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithNone }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithNone }, }; public static OptionsCollection PreferImplicitTypeWithNone(this AbstractCodeActionOrUserDiagnosticTest test) => new OptionsCollection(test.GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithNone }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithNone }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithNone }, }; } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/IdeCoreBenchmarks/IdeCoreBenchmarks.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <Import Project="$(RepositoryEngineeringDir)targets\GenerateCompilerExecutableBindingRedirects.targets" /> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFrameworks>net5.0;netcoreapp3.1;net472</TargetFrameworks> <IsShipping>false</IsShipping> <PlatformTarget>AnyCPU</PlatformTarget> <!-- Automatically generate the necessary assembly binding redirects --> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <LangVersion>9</LangVersion> </PropertyGroup> <ItemGroup> <Compile Include="..\..\VisualStudio\Core\Def\Storage\AbstractCloudCachePersistentStorageService.cs" Link="CloudCache\AbstractCloudCachePersistentStorageService.cs" /> <Compile Include="..\..\VisualStudio\Core\Def\Storage\CloudCachePersistentStorage.cs" Link="CloudCache\CloudCachePersistentStorage.cs" /> <Compile Include="..\..\VisualStudio\Core\Def\Storage\Nerdbank\ReadOnlySequenceStream.cs" Link="CloudCache\ReadOnlySequenceStream.cs" /> <Compile Include="..\..\VisualStudio\Core\Def\Storage\ProjectContainerKeyCache.cs" Link="CloudCache\ProjectContainerKeyCache.cs" /> <Compile Include="..\..\VisualStudio\CSharp\Test\PersistentStorage\Mocks\AuthorizationServiceMock.cs" Link="CloudCache\AuthorizationServiceMock.cs" /> <Compile Include="..\..\VisualStudio\CSharp\Test\PersistentStorage\Mocks\FileSystemServiceMock.cs" Link="CloudCache\FileSystemServiceMock.cs" /> <Compile Include="..\..\VisualStudio\CSharp\Test\PersistentStorage\Mocks\MockCloudCachePersistentStorageService.cs" Link="CloudCache\MockCloudCachePersistentStorageService.cs" /> <Compile Include="..\..\VisualStudio\CSharp\Test\PersistentStorage\Mocks\ServiceBrokerMock.cs" Link="CloudCache\ServiceBrokerMock.cs" /> <Compile Include="..\..\VisualStudio\CSharp\Test\PersistentStorage\Mocks\SolutionServiceMock.cs" Link="CloudCache\SolutionServiceMock.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="BenchmarkDotNet" Version="$(BenchmarkDotNetVersion)" /> <PackageReference Include="BenchmarkDotNet.Diagnostics.Windows" Version="$(BenchmarkDotNetDiagnosticsWindowsVersion)" /> <!-- This is to avoid a version conflict during build --> <PackageReference Include="System.CodeDom" Version="$(SystemCodeDomVersion)" /> <PackageReference Include="Microsoft.Build.Framework" Version="$(MicrosoftBuildFrameworkVersion)" ExcludeAssets="Runtime" PrivateAssets="All" /> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.Build.Locator" Version="$(MicrosoftBuildLocatorVersion)" /> <PackageReference Include="System.Buffers" Version="$(SystemBuffersVersion)" /> <PackageReference Include="System.ComponentModel.Composition" Version="$(SystemComponentModelCompositionVersion)" /> <PackageReference Include="System.Threading.Tasks.Dataflow" Version="$(SystemThreadingTasksDataflowVersion)" /> <PackageReference Include="Microsoft.Win32.Registry" Version="$(MicrosoftWin32RegistryVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Cache" Version="$(MicrosoftVisualStudioCacheVersion)" /> <PackageReference Include="Nerdbank.Streams" Version="$(NerdbankStreamsVersion)" /> <PackageReference Include="SQLitePCLRaw.bundle_green" Version="$(SQLitePCLRawbundle_greenVersion)" PrivateAssets="all" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\MSBuild\Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj" /> <ProjectReference Include="..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\AnalyzerRunner\AnalyzerRunner.csproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net472'"> <!-- These aren't used by the build, but it allows the tool to locate dependencies of the built-in analyzers. --> <ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <Import Project="$(RepositoryEngineeringDir)targets\GenerateCompilerExecutableBindingRedirects.targets" /> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFrameworks>net5.0;netcoreapp3.1;net472</TargetFrameworks> <IsShipping>false</IsShipping> <PlatformTarget>AnyCPU</PlatformTarget> <!-- Automatically generate the necessary assembly binding redirects --> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <LangVersion>9</LangVersion> </PropertyGroup> <ItemGroup> <Compile Include="..\..\VisualStudio\Core\Def\Storage\AbstractCloudCachePersistentStorageService.cs" Link="CloudCache\AbstractCloudCachePersistentStorageService.cs" /> <Compile Include="..\..\VisualStudio\Core\Def\Storage\CloudCachePersistentStorage.cs" Link="CloudCache\CloudCachePersistentStorage.cs" /> <Compile Include="..\..\VisualStudio\Core\Def\Storage\Nerdbank\ReadOnlySequenceStream.cs" Link="CloudCache\ReadOnlySequenceStream.cs" /> <Compile Include="..\..\VisualStudio\Core\Def\Storage\ProjectContainerKeyCache.cs" Link="CloudCache\ProjectContainerKeyCache.cs" /> <Compile Include="..\..\VisualStudio\CSharp\Test\PersistentStorage\Mocks\AuthorizationServiceMock.cs" Link="CloudCache\AuthorizationServiceMock.cs" /> <Compile Include="..\..\VisualStudio\CSharp\Test\PersistentStorage\Mocks\FileSystemServiceMock.cs" Link="CloudCache\FileSystemServiceMock.cs" /> <Compile Include="..\..\VisualStudio\CSharp\Test\PersistentStorage\Mocks\MockCloudCachePersistentStorageService.cs" Link="CloudCache\MockCloudCachePersistentStorageService.cs" /> <Compile Include="..\..\VisualStudio\CSharp\Test\PersistentStorage\Mocks\ServiceBrokerMock.cs" Link="CloudCache\ServiceBrokerMock.cs" /> <Compile Include="..\..\VisualStudio\CSharp\Test\PersistentStorage\Mocks\SolutionServiceMock.cs" Link="CloudCache\SolutionServiceMock.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="BenchmarkDotNet" Version="$(BenchmarkDotNetVersion)" /> <PackageReference Include="BenchmarkDotNet.Diagnostics.Windows" Version="$(BenchmarkDotNetDiagnosticsWindowsVersion)" /> <!-- This is to avoid a version conflict during build --> <PackageReference Include="System.CodeDom" Version="$(SystemCodeDomVersion)" /> <PackageReference Include="Microsoft.Build.Framework" Version="$(MicrosoftBuildFrameworkVersion)" ExcludeAssets="Runtime" PrivateAssets="All" /> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.Build.Locator" Version="$(MicrosoftBuildLocatorVersion)" /> <PackageReference Include="System.Buffers" Version="$(SystemBuffersVersion)" /> <PackageReference Include="System.ComponentModel.Composition" Version="$(SystemComponentModelCompositionVersion)" /> <PackageReference Include="System.Threading.Tasks.Dataflow" Version="$(SystemThreadingTasksDataflowVersion)" /> <PackageReference Include="Microsoft.Win32.Registry" Version="$(MicrosoftWin32RegistryVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Cache" Version="$(MicrosoftVisualStudioCacheVersion)" /> <PackageReference Include="Nerdbank.Streams" Version="$(NerdbankStreamsVersion)" /> <PackageReference Include="SQLitePCLRaw.bundle_green" Version="$(SQLitePCLRawbundle_greenVersion)" PrivateAssets="all" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\MSBuild\Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj" /> <ProjectReference Include="..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\AnalyzerRunner\AnalyzerRunner.csproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net472'"> <!-- These aren't used by the build, but it allows the tool to locate dependencies of the built-in analyzers. --> <ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> </ItemGroup> </Project>
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Utilities/VisualBasic/BasicTestBase.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 Roslyn.Test.Utilities Imports Xunit Public MustInherit Class BasicTestBase Inherits CommonTestBase Public Function XCDataToString(Optional data As XCData = Nothing) As String Return data?.Value.Replace(vbLf, Environment.NewLine) End Function Private Function Translate(action As Action(Of ModuleSymbol)) As Action(Of IModuleSymbol) If action IsNot Nothing Then Return Sub(m) action(DirectCast(m, ModuleSymbol)) Else Return Nothing End If End Function Friend Shadows Function CompileAndVerify( source As XElement, expectedOutput As XCData, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional references As MetadataReference() = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional verify As Verification = Verification.Passes ) As CompilationVerifier Return CompileAndVerify( source, XCDataToString(expectedOutput), expectedReturnCode, args, references, dependencies, sourceSymbolValidator, validator, symbolValidator, expectedSignatures, options, parseOptions, emitOptions, verify) End Function Friend Shadows Function CompileAndVerify( compilation As Compilation, Optional manifestResources As IEnumerable(Of ResourceDescription) = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional expectedOutput As String = Nothing, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional verify As Verification = Verification.Passes) As CompilationVerifier Return MyBase.CompileAndVerifyCommon( compilation, manifestResources, dependencies, Translate(sourceSymbolValidator), validator, Translate(symbolValidator), expectedSignatures, expectedOutput, expectedReturnCode, args, emitOptions, verify) End Function Friend Shadows Function CompileAndVerify( compilation As Compilation, expectedOutput As XCData, Optional args As String() = Nothing, Optional manifestResources As IEnumerable(Of ResourceDescription) = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional verify As Verification = Verification.Passes) As CompilationVerifier Return CompileAndVerify( compilation, manifestResources, dependencies, sourceSymbolValidator, validator, symbolValidator, expectedSignatures, XCDataToString(expectedOutput), Nothing, args, emitOptions, verify) End Function Friend Shadows Function CompileAndVerify( source As XElement, Optional expectedOutput As String = Nothing, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional references As MetadataReference() = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional verify As Verification = Verification.Passes, Optional useLatestFramework As Boolean = False ) As CompilationVerifier Dim defaultRefs = If(useLatestFramework, LatestVbReferences, DefaultVbReferences) Dim allReferences = If(references IsNot Nothing, defaultRefs.Concat(references), defaultRefs) Return Me.CompileAndVerify(source, allReferences, expectedOutput, expectedReturnCode, args, dependencies, sourceSymbolValidator, validator, symbolValidator, expectedSignatures, options, parseOptions, emitOptions, verify) End Function Friend Shadows Function CompileAndVerify( source As XElement, allReferences As IEnumerable(Of MetadataReference), Optional expectedOutput As String = Nothing, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional verify As Verification = Verification.Passes ) As CompilationVerifier If options Is Nothing Then options = If(expectedOutput Is Nothing, TestOptions.ReleaseDll, TestOptions.ReleaseExe) End If Dim assemblyName As String = Nothing Dim sourceTrees = ParseSourceXml(source, parseOptions, assemblyName) Dim compilation = CreateEmptyCompilation(sourceTrees.ToArray(), allReferences, options, assemblyName:=assemblyName) Return MyBase.CompileAndVerifyCommon( compilation, Nothing, dependencies, Translate(sourceSymbolValidator), validator, Translate(symbolValidator), expectedSignatures, expectedOutput, expectedReturnCode, args, emitOptions, verify) End Function Friend Shadows Function CompileAndVerifyOnWin8Only( source As XElement, allReferences As IEnumerable(Of MetadataReference), Optional expectedOutput As String = Nothing, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional verify As Verification = Verification.Passes ) As CompilationVerifier Return Me.CompileAndVerify( source, allReferences, If(OSVersion.IsWin8, expectedOutput, Nothing), If(OSVersion.IsWin8, expectedReturnCode, Nothing), args, dependencies, sourceSymbolValidator, validator, symbolValidator, expectedSignatures, options, parseOptions, verify:=If(OSVersion.IsWin8, verify, Verification.Skipped)) End Function Friend Shadows Function CompileAndVerifyOnWin8Only( source As XElement, expectedOutput As XCData, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional allReferences() As MetadataReference = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional verify As Verification = Verification.Passes ) As CompilationVerifier Return CompileAndVerifyOnWin8Only( source, allReferences, XCDataToString(expectedOutput), expectedReturnCode, args, dependencies, sourceSymbolValidator, validator, symbolValidator, expectedSignatures, options, parseOptions, verify) End Function Friend Shadows Function CompileAndVerifyOnWin8Only( source As XElement, Optional expectedOutput As String = Nothing, Optional references() As MetadataReference = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional verify As Verification = Verification.Passes, Optional useLatestFramework As Boolean = False ) As CompilationVerifier Return CompileAndVerify( source, expectedOutput:=If(OSVersion.IsWin8, expectedOutput, Nothing), references:=references, dependencies:=dependencies, sourceSymbolValidator:=sourceSymbolValidator, validator:=validator, symbolValidator:=symbolValidator, expectedSignatures:=expectedSignatures, options:=options, parseOptions:=parseOptions, verify:=If(OSVersion.IsWin8, verify, Verification.Skipped), useLatestFramework:=useLatestFramework) End Function Friend Shadows Function CompileAndVerifyEx( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional expectedOutput As String = Nothing, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional assemblyName As String = Nothing, Optional verify As Verification = Verification.Passes, Optional targetFramework As TargetFramework = TargetFramework.StandardAndVBRuntime ) As CompilationVerifier If options Is Nothing Then options = If(expectedOutput Is Nothing, TestOptions.ReleaseDll, TestOptions.ReleaseExe) End If Dim compilation = CreateCompilation(source, references, options, parseOptions, targetFramework, assemblyName) Return MyBase.CompileAndVerifyCommon( compilation, Nothing, dependencies, Translate(sourceSymbolValidator), validator, Translate(symbolValidator), expectedSignatures, expectedOutput, expectedReturnCode, args, emitOptions, verify) End Function ''' <summary> ''' Compile sources and adds a custom reference using a custom IL ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Friend Function CompileWithCustomILSource(source As XElement, ilSource As XCData) As CompilationVerifier Return CompileWithCustomILSource(source, ilSource.Value) End Function ''' <summary> ''' Compile sources and adds a custom reference using a custom IL ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Friend Function CompileWithCustomILSource(source As XElement, ilSource As String, Optional options As VisualBasicCompilationOptions = Nothing, Optional compilationVerifier As Action(Of VisualBasicCompilation) = Nothing, Optional expectedOutput As String = Nothing) As CompilationVerifier If expectedOutput IsNot Nothing Then options = options.WithOutputKind(OutputKind.ConsoleApplication) End If If ilSource = Nothing Then Return CompileAndVerify(source) End If Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef, MsvbRef, reference}, options) If compilationVerifier IsNot Nothing Then compilationVerifier(compilation) End If Return CompileAndVerify(compilation, expectedOutput:=expectedOutput) End Function Friend Overloads Function CompileAndVerifyFieldMarshal(source As String, expectedBlobs As Dictionary(Of String, Byte()), Optional getExpectedBlob As Func(Of String, PEAssembly, Byte()) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional isField As Boolean = True) As CompilationVerifier Dim xmlSource = <compilation><field><%= source %></field></compilation> Return CompileAndVerifyFieldMarshal(xmlSource, expectedBlobs, getExpectedBlob, expectedSignatures, isField) End Function Friend Overloads Function CompileAndVerifyFieldMarshal(source As XElement, expectedBlobs As Dictionary(Of String, Byte()), Optional getExpectedBlob As Func(Of String, PEAssembly, Byte()) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional isField As Boolean = True) As CompilationVerifier Return CompileAndVerifyFieldMarshal(source, Function(s, _omitted1) Assert.True(expectedBlobs.ContainsKey(s), "Expecting marshalling blob for " & If(isField, "field ", "parameter ") & s) Return expectedBlobs(s) End Function, expectedSignatures, isField) End Function Friend Overloads Function CompileAndVerifyFieldMarshal(source As XElement, getExpectedBlob As Func(Of String, PEAssembly, Byte()), Optional expectedSignatures As SignatureDescription() = Nothing, Optional isField As Boolean = True) As CompilationVerifier Return CompileAndVerify(source, options:=TestOptions.ReleaseDll, validator:=Sub(assembly) MetadataValidation.MarshalAsMetadataValidator(assembly, getExpectedBlob, isField), expectedSignatures:=expectedSignatures) End Function Public Shared Function CreateSubmission(code As String, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional previous As VisualBasicCompilation = Nothing, Optional returnType As Type = Nothing, Optional hostObjectType As Type = Nothing) As VisualBasicCompilation Return VisualBasicCompilation.CreateScriptCompilation( GetUniqueName(), references:=If(references Is Nothing, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}.Concat(references)), options:=options, syntaxTree:=Parse(code, options:=If(parseOptions, TestOptions.Script)), previousScriptCompilation:=previous, returnType:=returnType, globalsType:=hostObjectType) End Function Friend Shared Function GetAttributeNames(attributes As ImmutableArray(Of SynthesizedAttributeData)) As IEnumerable(Of String) Return attributes.Select(Function(a) a.AttributeClass.Name) End Function Friend Shared Function GetAttributeNames(attributes As ImmutableArray(Of VisualBasicAttributeData)) As IEnumerable(Of String) Return attributes.Select(Function(a) a.AttributeClass.Name) End Function Friend Overrides Function VisualizeRealIL(peModule As IModuleSymbol, methodData As CompilationTestData.MethodData, markers As IReadOnlyDictionary(Of Integer, String), areLocalsZeroed As Boolean) As String Throw New NotImplementedException() End Function Friend Function GetSymbolsFromBinaryReference(bytes() As Byte) As AssemblySymbol Return MetadataTestHelpers.GetSymbolsForReferences({bytes}).Single() End Function Public Shared Shadows Function GetPdbXml(compilation As VisualBasicCompilation, Optional methodName As String = "") As XElement Return XElement.Parse(PdbValidation.GetPdbXml(compilation, qualifiedMethodName:=methodName)) End Function Public Shared Shadows Function GetPdbXml(source As XElement, Optional options As VisualBasicCompilationOptions = Nothing, Optional methodName As String = "") As XElement Dim compilation = CreateCompilationWithMscorlib40(source, options:=options) compilation.VerifyDiagnostics() Return GetPdbXml(compilation, methodName) End Function Public Shared Shadows Function GetSequencePoints(pdbXml As XElement) As XElement Return <sequencePoints> <%= From entry In pdbXml.<methods>.<method>.<sequencePoints>.<entry> Select <entry startLine=<%= entry.@startLine %> startColumn=<%= entry.@startColumn %> endLine=<%= entry.@endLine %> endColumn=<%= entry.@endColumn %>/> %> </sequencePoints> End Function Public Shared ReadOnly ClassesWithReadWriteProperties As XCData = <![CDATA[ .class public auto ansi beforefieldinit B extends [mscorlib]System.Object { .method public hidebysig newslot specialname virtual instance int32 get_P_rw_r_w() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method B::get_P_rw_r_w .method public hidebysig newslot specialname virtual instance void set_P_rw_r_w(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method B::set_P_rw_r_w .method public hidebysig newslot specialname virtual instance int32 get_P_rw_rw_w() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method B::get_P_rw_rw_w .method public hidebysig newslot specialname virtual instance void set_P_rw_rw_w(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method B::set_P_rw_rw_w .method public hidebysig newslot specialname virtual instance int32 get_P_rw_rw_r() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method B::get_P_rw_rw_r .method public hidebysig newslot specialname virtual instance void set_P_rw_rw_r(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method B::set_P_rw_rw_r .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method B::.ctor .property instance int32 P_rw_r_w() { .get instance int32 B::get_P_rw_r_w() .set instance void B::set_P_rw_r_w(int32) } // end of property B::P_rw_r_w .property instance int32 P_rw_rw_w() { .set instance void B::set_P_rw_rw_w(int32) .get instance int32 B::get_P_rw_rw_w() } // end of property B::P_rw_rw_w .property instance int32 P_rw_rw_r() { .get instance int32 B::get_P_rw_rw_r() .set instance void B::set_P_rw_rw_r(int32) } // end of property B::P_rw_rw_r } // end of class B .class public auto ansi beforefieldinit D1 extends B { .method public hidebysig specialname virtual instance int32 get_P_rw_r_w() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method D1::get_P_rw_r_w .method public hidebysig specialname virtual instance int32 get_P_rw_rw_w() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method D1::get_P_rw_rw_w .method public hidebysig specialname virtual instance void set_P_rw_rw_w(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method D1::set_P_rw_rw_w .method public hidebysig specialname virtual instance int32 get_P_rw_rw_r() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method D1::get_P_rw_rw_r .method public hidebysig specialname virtual instance void set_P_rw_rw_r(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method D1::set_P_rw_rw_r .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void B::.ctor() IL_0006: ret } // end of method D1::.ctor .property instance int32 P_rw_r_w() { .get instance int32 D1::get_P_rw_r_w() } // end of property D1::P_rw_r_w .property instance int32 P_rw_rw_w() { .get instance int32 D1::get_P_rw_rw_w() .set instance void D1::set_P_rw_rw_w(int32) } // end of property D1::P_rw_rw_w .property instance int32 P_rw_rw_r() { .get instance int32 D1::get_P_rw_rw_r() .set instance void D1::set_P_rw_rw_r(int32) } // end of property D1::P_rw_rw_r } // end of class D1 .class public auto ansi beforefieldinit D2 extends D1 { .method public hidebysig specialname virtual instance void set_P_rw_r_w(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method D2::set_P_rw_r_w .method public hidebysig specialname virtual instance void set_P_rw_rw_w(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method D2::set_P_rw_rw_w .method public hidebysig specialname virtual instance int32 get_P_rw_rw_r() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method D2::get_P_rw_rw_r .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void D1::.ctor() IL_0006: ret } // end of method D2::.ctor .property instance int32 P_rw_r_w() { .set instance void D2::set_P_rw_r_w(int32) } // end of property D2::P_rw_r_w .property instance int32 P_rw_rw_w() { .set instance void D2::set_P_rw_rw_w(int32) } // end of property D2::P_rw_rw_w .property instance int32 P_rw_rw_r() { .get instance int32 D2::get_P_rw_rw_r() } // end of property D2::P_rw_rw_r } // end of class D2 ]]> Public Class NameSyntaxFinder Inherits VisualBasicSyntaxWalker Private Sub New() MyBase.New(SyntaxWalkerDepth.StructuredTrivia) End Sub Public Overrides Sub DefaultVisit(node As SyntaxNode) Dim name = TryCast(node, NameSyntax) If name IsNot Nothing Then Me._names.Add(name) End If MyBase.DefaultVisit(node) End Sub Private ReadOnly _names As New List(Of NameSyntax) Public Shared Function FindNames(node As SyntaxNode) As List(Of NameSyntax) Dim finder As New NameSyntaxFinder() finder.Visit(node) Return finder._names End Function End Class Public Class ExpressionSyntaxFinder Inherits VisualBasicSyntaxWalker Private Sub New() MyBase.New(SyntaxWalkerDepth.StructuredTrivia) End Sub Public Overrides Sub DefaultVisit(node As SyntaxNode) Dim expr = TryCast(node, ExpressionSyntax) If expr IsNot Nothing Then Me._expressions.Add(expr) End If MyBase.DefaultVisit(node) End Sub Private ReadOnly _expressions As New List(Of ExpressionSyntax) Public Shared Function FindExpression(node As SyntaxNode) As List(Of ExpressionSyntax) Dim finder As New ExpressionSyntaxFinder() finder.Visit(node) Return finder._expressions End Function End Class Public Class SyntaxNodeFinder Inherits VisualBasicSyntaxWalker Private Sub New() MyBase.New(SyntaxWalkerDepth.StructuredTrivia) End Sub Public Overrides Sub DefaultVisit(node As SyntaxNode) If node IsNot Nothing AndAlso Me._kinds.Contains(node.Kind) Then Me._nodes.Add(node) End If MyBase.DefaultVisit(node) End Sub Private ReadOnly _nodes As New List(Of SyntaxNode) Private ReadOnly _kinds As New HashSet(Of SyntaxKind)(SyntaxFacts.EqualityComparer) Public Shared Function FindNodes(Of T As SyntaxNode)(node As SyntaxNode, ParamArray kinds() As SyntaxKind) As List(Of T) Return New List(Of T)(From s In FindNodes(node, kinds) Select DirectCast(s, T)) End Function Public Shared Function FindNodes(node As SyntaxNode, ParamArray kinds() As SyntaxKind) As List(Of SyntaxNode) Dim finder As New SyntaxNodeFinder() finder._kinds.AddAll(kinds) finder.Visit(node) Return finder._nodes End Function End Class Public Class TypeComparer Implements IComparer(Of NamedTypeSymbol) Private Function Compare(x As NamedTypeSymbol, y As NamedTypeSymbol) As Integer Implements IComparer(Of NamedTypeSymbol).Compare Dim result As Integer = StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name) If result <> 0 Then Return result End If Return x.Arity - y.Arity End Function End Class #Region "IOperation tree validation" Friend Shared Function GetOperationTreeForTest(Of TSyntaxNode As SyntaxNode)(compilation As VisualBasicCompilation, fileName As String, Optional which As Integer = 0) As (tree As String, syntax As SyntaxNode, operation As IOperation) Dim node As SyntaxNode = CompilationUtils.FindBindingText(Of TSyntaxNode)(compilation, fileName, which, prefixMatch:=True) If node Is Nothing Then Return Nothing End If Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim operation = semanticModel.GetOperation(node) If operation IsNot Nothing Then Assert.Same(semanticModel, operation.SemanticModel) Return (OperationTreeVerifier.GetOperationTree(compilation, operation), node, operation) Else Return (Nothing, Nothing, Nothing) End If End Function Friend Shared Function GetOperationTreeForTest(Of TSyntaxNode As SyntaxNode)( source As String, Optional compilationOptions As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional which As Integer = 0, Optional useLatestFrameworkReferences As Boolean = False) As (tree As String, syntax As SyntaxNode, operation As IOperation, compilation As Compilation) Dim fileName = "a.vb" Dim syntaxTree = Parse(source, fileName, parseOptions) Dim allReferences = TargetFrameworkUtil.Mscorlib45ExtendedReferences.Add( If(useLatestFrameworkReferences, TestBase.MsvbRef_v4_0_30319_17929, TestBase.MsvbRef)) Dim compilation = CreateEmptyCompilation({syntaxTree}, references:=allReferences, options:=If(compilationOptions, TestOptions.ReleaseDll)) Dim operationTree = GetOperationTreeForTest(Of TSyntaxNode)(compilation, fileName, which) Return (operationTree.tree, operationTree.syntax, operationTree.operation, compilation) End Function Friend Shared Sub VerifyOperationTreeForTest(Of TSyntaxNode As SyntaxNode)(compilation As VisualBasicCompilation, fileName As String, expectedOperationTree As String, Optional which As Integer = 0, Optional additionalOperationTreeVerifier As Action(Of IOperation, Compilation, SyntaxNode) = Nothing) Dim operationTree = GetOperationTreeForTest(Of TSyntaxNode)(compilation, fileName, which) OperationTreeVerifier.Verify(expectedOperationTree, operationTree.tree) If additionalOperationTreeVerifier IsNot Nothing Then additionalOperationTreeVerifier(operationTree.operation, compilation, operationTree.syntax) End If End Sub Protected Shared Sub VerifyFlowGraphForTest(Of TSyntaxNode As SyntaxNode)(compilation As VisualBasicCompilation, expectedFlowGraph As String, Optional which As Integer = 0) Dim tree = compilation.SyntaxTrees(0) Dim syntaxNode As SyntaxNode = CompilationUtils.FindBindingText(Of TSyntaxNode)(compilation, tree.FilePath, which, prefixMatch:=True) VerifyFlowGraph(compilation, syntaxNode, expectedFlowGraph) End Sub Protected Shared Sub VerifyFlowGraph(compilation As VisualBasicCompilation, syntaxNode As SyntaxNode, expectedFlowGraph As String) Dim model = compilation.GetSemanticModel(syntaxNode.SyntaxTree) Dim graphAndSymbol As (Graph As FlowAnalysis.ControlFlowGraph, AssociatedSymbol As ISymbol) = ControlFlowGraphVerifier.GetControlFlowGraph(syntaxNode, model) ControlFlowGraphVerifier.VerifyGraph(compilation, expectedFlowGraph, graphAndSymbol.Graph, graphAndSymbol.AssociatedSymbol) End Sub Friend Shared Sub VerifyOperationTreeForTest(Of TSyntaxNode As SyntaxNode)( source As String, expectedOperationTree As String, Optional compilationOptions As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional which As Integer = 0, Optional additionalOperationTreeVerifier As Action(Of IOperation, Compilation, SyntaxNode) = Nothing, Optional useLatestFrameworkReferences As Boolean = False) Dim operationTree = GetOperationTreeForTest(Of TSyntaxNode)(source, compilationOptions, parseOptions, which, useLatestFrameworkReferences) OperationTreeVerifier.Verify(expectedOperationTree, operationTree.tree) If additionalOperationTreeVerifier IsNot Nothing Then additionalOperationTreeVerifier(operationTree.operation, operationTree.compilation, operationTree.syntax) End If End Sub Friend Shared Sub VerifyNoOperationTreeForTest(Of TSyntaxNode As SyntaxNode)( source As String, Optional compilationOptions As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional which As Integer = 0, Optional useLatestFrameworkReferences As Boolean = False) Dim operationTree = GetOperationTreeForTest(Of TSyntaxNode)(source, compilationOptions, parseOptions, which, useLatestFrameworkReferences) Assert.Null(operationTree.tree) End Sub Friend Shared Sub VerifyOperationTreeAndDiagnosticsForTest(Of TSyntaxNode As SyntaxNode)(compilation As VisualBasicCompilation, fileName As String, expectedOperationTree As String, expectedDiagnostics As String, Optional which As Integer = 0, Optional additionalOperationTreeVerifier As Action(Of IOperation, Compilation, SyntaxNode) = Nothing) compilation.AssertTheseDiagnostics(FilterString(expectedDiagnostics)) VerifyOperationTreeForTest(Of TSyntaxNode)(compilation, fileName, expectedOperationTree, which, additionalOperationTreeVerifier) End Sub Friend Shared Sub VerifyFlowGraphAndDiagnosticsForTest(Of TSyntaxNode As SyntaxNode)(compilation As VisualBasicCompilation, expectedFlowGraph As String, expectedDiagnostics As String, Optional which As Integer = 0) compilation.AssertTheseDiagnostics(FilterString(expectedDiagnostics)) VerifyFlowGraphForTest(Of TSyntaxNode)(compilation, expectedFlowGraph, which) End Sub Friend Shared Sub VerifyOperationTreeAndDiagnosticsForTest(Of TSyntaxNode As SyntaxNode)( source As String, expectedOperationTree As String, expectedDiagnostics As String, Optional compilationOptions As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional which As Integer = 0, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional additionalOperationTreeVerifier As Action(Of IOperation, Compilation, SyntaxNode) = Nothing, Optional useLatestFramework As Boolean = False) Dim fileName = "a.vb" Dim syntaxTree = Parse(source, fileName, parseOptions) Dim allReferences As IEnumerable(Of MetadataReference) = TargetFrameworkUtil.Mscorlib45ExtendedReferences.Add( If(useLatestFramework, TestBase.MsvbRef_v4_0_30319_17929, TestBase.MsvbRef)) allReferences = If(references IsNot Nothing, allReferences.Concat(references), allReferences) Dim compilation = CreateEmptyCompilation({syntaxTree}, references:=allReferences, options:=If(compilationOptions, TestOptions.ReleaseDll)) VerifyOperationTreeAndDiagnosticsForTest(Of TSyntaxNode)(compilation, fileName, expectedOperationTree, expectedDiagnostics, which, additionalOperationTreeVerifier) End Sub Friend Shared Sub VerifyFlowGraphAndDiagnosticsForTest(Of TSyntaxNode As SyntaxNode)( testSrc As String, expectedFlowGraph As String, expectedDiagnostics As String, Optional compilationOptions As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional which As Integer = 0, Optional additionalReferences As IEnumerable(Of MetadataReference) = Nothing, Optional useLatestFramework As Boolean = False) Dim fileName = "a.vb" Dim syntaxTree = Parse(testSrc, fileName, parseOptions) Dim references As IEnumerable(Of MetadataReference) = TargetFrameworkUtil.Mscorlib45ExtendedReferences.Add( If(useLatestFramework, TestBase.MsvbRef_v4_0_30319_17929, TestBase.MsvbRef)) references = If(additionalReferences IsNot Nothing, references.Concat(additionalReferences), references) Dim compilation = CreateEmptyCompilation({syntaxTree}, references:=references, options:=If(compilationOptions, TestOptions.ReleaseDll)) VerifyFlowGraphAndDiagnosticsForTest(Of TSyntaxNode)(compilation, expectedFlowGraph, expectedDiagnostics, which) End Sub Public Shared Function GetAssertTheseDiagnosticsString(allDiagnostics As ImmutableArray(Of Diagnostic), suppressInfos As Boolean) As String Return DumpAllDiagnostics(allDiagnostics, suppressInfos) End Function Friend Shared Function GetOperationAndSyntaxForTest(Of TSyntaxNode As SyntaxNode)(compilation As Compilation, fileName As String, Optional which As Integer = 0) As (operation As IOperation, syntaxNode As SyntaxNode) Dim node As SyntaxNode = CompilationUtils.FindBindingText(Of TSyntaxNode)(compilation, fileName, which, prefixMatch:=True) If node Is Nothing Then Return (Nothing, Nothing) End If Dim semanticModel = compilation.GetSemanticModel(node.SyntaxTree) Dim operation = semanticModel.GetOperation(node) Assert.Same(semanticModel, operation.SemanticModel) Return (operation, node) End Function #End Region End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Imports Xunit Public MustInherit Class BasicTestBase Inherits CommonTestBase Public Function XCDataToString(Optional data As XCData = Nothing) As String Return data?.Value.Replace(vbLf, Environment.NewLine) End Function Private Function Translate(action As Action(Of ModuleSymbol)) As Action(Of IModuleSymbol) If action IsNot Nothing Then Return Sub(m) action(DirectCast(m, ModuleSymbol)) Else Return Nothing End If End Function Friend Shadows Function CompileAndVerify( source As XElement, expectedOutput As XCData, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional references As MetadataReference() = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional verify As Verification = Verification.Passes ) As CompilationVerifier Return CompileAndVerify( source, XCDataToString(expectedOutput), expectedReturnCode, args, references, dependencies, sourceSymbolValidator, validator, symbolValidator, expectedSignatures, options, parseOptions, emitOptions, verify) End Function Friend Shadows Function CompileAndVerify( compilation As Compilation, Optional manifestResources As IEnumerable(Of ResourceDescription) = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional expectedOutput As String = Nothing, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional verify As Verification = Verification.Passes) As CompilationVerifier Return MyBase.CompileAndVerifyCommon( compilation, manifestResources, dependencies, Translate(sourceSymbolValidator), validator, Translate(symbolValidator), expectedSignatures, expectedOutput, expectedReturnCode, args, emitOptions, verify) End Function Friend Shadows Function CompileAndVerify( compilation As Compilation, expectedOutput As XCData, Optional args As String() = Nothing, Optional manifestResources As IEnumerable(Of ResourceDescription) = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional verify As Verification = Verification.Passes) As CompilationVerifier Return CompileAndVerify( compilation, manifestResources, dependencies, sourceSymbolValidator, validator, symbolValidator, expectedSignatures, XCDataToString(expectedOutput), Nothing, args, emitOptions, verify) End Function Friend Shadows Function CompileAndVerify( source As XElement, Optional expectedOutput As String = Nothing, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional references As MetadataReference() = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional verify As Verification = Verification.Passes, Optional useLatestFramework As Boolean = False ) As CompilationVerifier Dim defaultRefs = If(useLatestFramework, LatestVbReferences, DefaultVbReferences) Dim allReferences = If(references IsNot Nothing, defaultRefs.Concat(references), defaultRefs) Return Me.CompileAndVerify(source, allReferences, expectedOutput, expectedReturnCode, args, dependencies, sourceSymbolValidator, validator, symbolValidator, expectedSignatures, options, parseOptions, emitOptions, verify) End Function Friend Shadows Function CompileAndVerify( source As XElement, allReferences As IEnumerable(Of MetadataReference), Optional expectedOutput As String = Nothing, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional verify As Verification = Verification.Passes ) As CompilationVerifier If options Is Nothing Then options = If(expectedOutput Is Nothing, TestOptions.ReleaseDll, TestOptions.ReleaseExe) End If Dim assemblyName As String = Nothing Dim sourceTrees = ParseSourceXml(source, parseOptions, assemblyName) Dim compilation = CreateEmptyCompilation(sourceTrees.ToArray(), allReferences, options, assemblyName:=assemblyName) Return MyBase.CompileAndVerifyCommon( compilation, Nothing, dependencies, Translate(sourceSymbolValidator), validator, Translate(symbolValidator), expectedSignatures, expectedOutput, expectedReturnCode, args, emitOptions, verify) End Function Friend Shadows Function CompileAndVerifyOnWin8Only( source As XElement, allReferences As IEnumerable(Of MetadataReference), Optional expectedOutput As String = Nothing, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional verify As Verification = Verification.Passes ) As CompilationVerifier Return Me.CompileAndVerify( source, allReferences, If(OSVersion.IsWin8, expectedOutput, Nothing), If(OSVersion.IsWin8, expectedReturnCode, Nothing), args, dependencies, sourceSymbolValidator, validator, symbolValidator, expectedSignatures, options, parseOptions, verify:=If(OSVersion.IsWin8, verify, Verification.Skipped)) End Function Friend Shadows Function CompileAndVerifyOnWin8Only( source As XElement, expectedOutput As XCData, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional allReferences() As MetadataReference = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional verify As Verification = Verification.Passes ) As CompilationVerifier Return CompileAndVerifyOnWin8Only( source, allReferences, XCDataToString(expectedOutput), expectedReturnCode, args, dependencies, sourceSymbolValidator, validator, symbolValidator, expectedSignatures, options, parseOptions, verify) End Function Friend Shadows Function CompileAndVerifyOnWin8Only( source As XElement, Optional expectedOutput As String = Nothing, Optional references() As MetadataReference = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional verify As Verification = Verification.Passes, Optional useLatestFramework As Boolean = False ) As CompilationVerifier Return CompileAndVerify( source, expectedOutput:=If(OSVersion.IsWin8, expectedOutput, Nothing), references:=references, dependencies:=dependencies, sourceSymbolValidator:=sourceSymbolValidator, validator:=validator, symbolValidator:=symbolValidator, expectedSignatures:=expectedSignatures, options:=options, parseOptions:=parseOptions, verify:=If(OSVersion.IsWin8, verify, Verification.Skipped), useLatestFramework:=useLatestFramework) End Function Friend Shadows Function CompileAndVerifyEx( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional expectedOutput As String = Nothing, Optional expectedReturnCode As Integer? = Nothing, Optional args As String() = Nothing, Optional dependencies As IEnumerable(Of ModuleData) = Nothing, Optional sourceSymbolValidator As Action(Of ModuleSymbol) = Nothing, Optional validator As Action(Of PEAssembly) = Nothing, Optional symbolValidator As Action(Of ModuleSymbol) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional emitOptions As EmitOptions = Nothing, Optional assemblyName As String = Nothing, Optional verify As Verification = Verification.Passes, Optional targetFramework As TargetFramework = TargetFramework.StandardAndVBRuntime ) As CompilationVerifier If options Is Nothing Then options = If(expectedOutput Is Nothing, TestOptions.ReleaseDll, TestOptions.ReleaseExe) End If Dim compilation = CreateCompilation(source, references, options, parseOptions, targetFramework, assemblyName) Return MyBase.CompileAndVerifyCommon( compilation, Nothing, dependencies, Translate(sourceSymbolValidator), validator, Translate(symbolValidator), expectedSignatures, expectedOutput, expectedReturnCode, args, emitOptions, verify) End Function ''' <summary> ''' Compile sources and adds a custom reference using a custom IL ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Friend Function CompileWithCustomILSource(source As XElement, ilSource As XCData) As CompilationVerifier Return CompileWithCustomILSource(source, ilSource.Value) End Function ''' <summary> ''' Compile sources and adds a custom reference using a custom IL ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Friend Function CompileWithCustomILSource(source As XElement, ilSource As String, Optional options As VisualBasicCompilationOptions = Nothing, Optional compilationVerifier As Action(Of VisualBasicCompilation) = Nothing, Optional expectedOutput As String = Nothing) As CompilationVerifier If expectedOutput IsNot Nothing Then options = options.WithOutputKind(OutputKind.ConsoleApplication) End If If ilSource = Nothing Then Return CompileAndVerify(source) End If Dim reference As MetadataReference = Nothing Using tempAssembly = IlasmUtilities.CreateTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateEmptyCompilationWithReferences(source, {MscorlibRef, MsvbRef, reference}, options) If compilationVerifier IsNot Nothing Then compilationVerifier(compilation) End If Return CompileAndVerify(compilation, expectedOutput:=expectedOutput) End Function Friend Overloads Function CompileAndVerifyFieldMarshal(source As String, expectedBlobs As Dictionary(Of String, Byte()), Optional getExpectedBlob As Func(Of String, PEAssembly, Byte()) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional isField As Boolean = True) As CompilationVerifier Dim xmlSource = <compilation><field><%= source %></field></compilation> Return CompileAndVerifyFieldMarshal(xmlSource, expectedBlobs, getExpectedBlob, expectedSignatures, isField) End Function Friend Overloads Function CompileAndVerifyFieldMarshal(source As XElement, expectedBlobs As Dictionary(Of String, Byte()), Optional getExpectedBlob As Func(Of String, PEAssembly, Byte()) = Nothing, Optional expectedSignatures As SignatureDescription() = Nothing, Optional isField As Boolean = True) As CompilationVerifier Return CompileAndVerifyFieldMarshal(source, Function(s, _omitted1) Assert.True(expectedBlobs.ContainsKey(s), "Expecting marshalling blob for " & If(isField, "field ", "parameter ") & s) Return expectedBlobs(s) End Function, expectedSignatures, isField) End Function Friend Overloads Function CompileAndVerifyFieldMarshal(source As XElement, getExpectedBlob As Func(Of String, PEAssembly, Byte()), Optional expectedSignatures As SignatureDescription() = Nothing, Optional isField As Boolean = True) As CompilationVerifier Return CompileAndVerify(source, options:=TestOptions.ReleaseDll, validator:=Sub(assembly) MetadataValidation.MarshalAsMetadataValidator(assembly, getExpectedBlob, isField), expectedSignatures:=expectedSignatures) End Function Public Shared Function CreateSubmission(code As String, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional previous As VisualBasicCompilation = Nothing, Optional returnType As Type = Nothing, Optional hostObjectType As Type = Nothing) As VisualBasicCompilation Return VisualBasicCompilation.CreateScriptCompilation( GetUniqueName(), references:=If(references Is Nothing, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}.Concat(references)), options:=options, syntaxTree:=Parse(code, options:=If(parseOptions, TestOptions.Script)), previousScriptCompilation:=previous, returnType:=returnType, globalsType:=hostObjectType) End Function Friend Shared Function GetAttributeNames(attributes As ImmutableArray(Of SynthesizedAttributeData)) As IEnumerable(Of String) Return attributes.Select(Function(a) a.AttributeClass.Name) End Function Friend Shared Function GetAttributeNames(attributes As ImmutableArray(Of VisualBasicAttributeData)) As IEnumerable(Of String) Return attributes.Select(Function(a) a.AttributeClass.Name) End Function Friend Overrides Function VisualizeRealIL(peModule As IModuleSymbol, methodData As CompilationTestData.MethodData, markers As IReadOnlyDictionary(Of Integer, String), areLocalsZeroed As Boolean) As String Throw New NotImplementedException() End Function Friend Function GetSymbolsFromBinaryReference(bytes() As Byte) As AssemblySymbol Return MetadataTestHelpers.GetSymbolsForReferences({bytes}).Single() End Function Public Shared Shadows Function GetPdbXml(compilation As VisualBasicCompilation, Optional methodName As String = "") As XElement Return XElement.Parse(PdbValidation.GetPdbXml(compilation, qualifiedMethodName:=methodName)) End Function Public Shared Shadows Function GetPdbXml(source As XElement, Optional options As VisualBasicCompilationOptions = Nothing, Optional methodName As String = "") As XElement Dim compilation = CreateCompilationWithMscorlib40(source, options:=options) compilation.VerifyDiagnostics() Return GetPdbXml(compilation, methodName) End Function Public Shared Shadows Function GetSequencePoints(pdbXml As XElement) As XElement Return <sequencePoints> <%= From entry In pdbXml.<methods>.<method>.<sequencePoints>.<entry> Select <entry startLine=<%= entry.@startLine %> startColumn=<%= entry.@startColumn %> endLine=<%= entry.@endLine %> endColumn=<%= entry.@endColumn %>/> %> </sequencePoints> End Function Public Shared ReadOnly ClassesWithReadWriteProperties As XCData = <![CDATA[ .class public auto ansi beforefieldinit B extends [mscorlib]System.Object { .method public hidebysig newslot specialname virtual instance int32 get_P_rw_r_w() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method B::get_P_rw_r_w .method public hidebysig newslot specialname virtual instance void set_P_rw_r_w(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method B::set_P_rw_r_w .method public hidebysig newslot specialname virtual instance int32 get_P_rw_rw_w() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method B::get_P_rw_rw_w .method public hidebysig newslot specialname virtual instance void set_P_rw_rw_w(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method B::set_P_rw_rw_w .method public hidebysig newslot specialname virtual instance int32 get_P_rw_rw_r() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method B::get_P_rw_rw_r .method public hidebysig newslot specialname virtual instance void set_P_rw_rw_r(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method B::set_P_rw_rw_r .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method B::.ctor .property instance int32 P_rw_r_w() { .get instance int32 B::get_P_rw_r_w() .set instance void B::set_P_rw_r_w(int32) } // end of property B::P_rw_r_w .property instance int32 P_rw_rw_w() { .set instance void B::set_P_rw_rw_w(int32) .get instance int32 B::get_P_rw_rw_w() } // end of property B::P_rw_rw_w .property instance int32 P_rw_rw_r() { .get instance int32 B::get_P_rw_rw_r() .set instance void B::set_P_rw_rw_r(int32) } // end of property B::P_rw_rw_r } // end of class B .class public auto ansi beforefieldinit D1 extends B { .method public hidebysig specialname virtual instance int32 get_P_rw_r_w() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method D1::get_P_rw_r_w .method public hidebysig specialname virtual instance int32 get_P_rw_rw_w() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method D1::get_P_rw_rw_w .method public hidebysig specialname virtual instance void set_P_rw_rw_w(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method D1::set_P_rw_rw_w .method public hidebysig specialname virtual instance int32 get_P_rw_rw_r() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method D1::get_P_rw_rw_r .method public hidebysig specialname virtual instance void set_P_rw_rw_r(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method D1::set_P_rw_rw_r .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void B::.ctor() IL_0006: ret } // end of method D1::.ctor .property instance int32 P_rw_r_w() { .get instance int32 D1::get_P_rw_r_w() } // end of property D1::P_rw_r_w .property instance int32 P_rw_rw_w() { .get instance int32 D1::get_P_rw_rw_w() .set instance void D1::set_P_rw_rw_w(int32) } // end of property D1::P_rw_rw_w .property instance int32 P_rw_rw_r() { .get instance int32 D1::get_P_rw_rw_r() .set instance void D1::set_P_rw_rw_r(int32) } // end of property D1::P_rw_rw_r } // end of class D1 .class public auto ansi beforefieldinit D2 extends D1 { .method public hidebysig specialname virtual instance void set_P_rw_r_w(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method D2::set_P_rw_r_w .method public hidebysig specialname virtual instance void set_P_rw_rw_w(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } // end of method D2::set_P_rw_rw_w .method public hidebysig specialname virtual instance int32 get_P_rw_rw_r() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } // end of method D2::get_P_rw_rw_r .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void D1::.ctor() IL_0006: ret } // end of method D2::.ctor .property instance int32 P_rw_r_w() { .set instance void D2::set_P_rw_r_w(int32) } // end of property D2::P_rw_r_w .property instance int32 P_rw_rw_w() { .set instance void D2::set_P_rw_rw_w(int32) } // end of property D2::P_rw_rw_w .property instance int32 P_rw_rw_r() { .get instance int32 D2::get_P_rw_rw_r() } // end of property D2::P_rw_rw_r } // end of class D2 ]]> Public Class NameSyntaxFinder Inherits VisualBasicSyntaxWalker Private Sub New() MyBase.New(SyntaxWalkerDepth.StructuredTrivia) End Sub Public Overrides Sub DefaultVisit(node As SyntaxNode) Dim name = TryCast(node, NameSyntax) If name IsNot Nothing Then Me._names.Add(name) End If MyBase.DefaultVisit(node) End Sub Private ReadOnly _names As New List(Of NameSyntax) Public Shared Function FindNames(node As SyntaxNode) As List(Of NameSyntax) Dim finder As New NameSyntaxFinder() finder.Visit(node) Return finder._names End Function End Class Public Class ExpressionSyntaxFinder Inherits VisualBasicSyntaxWalker Private Sub New() MyBase.New(SyntaxWalkerDepth.StructuredTrivia) End Sub Public Overrides Sub DefaultVisit(node As SyntaxNode) Dim expr = TryCast(node, ExpressionSyntax) If expr IsNot Nothing Then Me._expressions.Add(expr) End If MyBase.DefaultVisit(node) End Sub Private ReadOnly _expressions As New List(Of ExpressionSyntax) Public Shared Function FindExpression(node As SyntaxNode) As List(Of ExpressionSyntax) Dim finder As New ExpressionSyntaxFinder() finder.Visit(node) Return finder._expressions End Function End Class Public Class SyntaxNodeFinder Inherits VisualBasicSyntaxWalker Private Sub New() MyBase.New(SyntaxWalkerDepth.StructuredTrivia) End Sub Public Overrides Sub DefaultVisit(node As SyntaxNode) If node IsNot Nothing AndAlso Me._kinds.Contains(node.Kind) Then Me._nodes.Add(node) End If MyBase.DefaultVisit(node) End Sub Private ReadOnly _nodes As New List(Of SyntaxNode) Private ReadOnly _kinds As New HashSet(Of SyntaxKind)(SyntaxFacts.EqualityComparer) Public Shared Function FindNodes(Of T As SyntaxNode)(node As SyntaxNode, ParamArray kinds() As SyntaxKind) As List(Of T) Return New List(Of T)(From s In FindNodes(node, kinds) Select DirectCast(s, T)) End Function Public Shared Function FindNodes(node As SyntaxNode, ParamArray kinds() As SyntaxKind) As List(Of SyntaxNode) Dim finder As New SyntaxNodeFinder() finder._kinds.AddAll(kinds) finder.Visit(node) Return finder._nodes End Function End Class Public Class TypeComparer Implements IComparer(Of NamedTypeSymbol) Private Function Compare(x As NamedTypeSymbol, y As NamedTypeSymbol) As Integer Implements IComparer(Of NamedTypeSymbol).Compare Dim result As Integer = StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name) If result <> 0 Then Return result End If Return x.Arity - y.Arity End Function End Class #Region "IOperation tree validation" Friend Shared Function GetOperationTreeForTest(Of TSyntaxNode As SyntaxNode)(compilation As VisualBasicCompilation, fileName As String, Optional which As Integer = 0) As (tree As String, syntax As SyntaxNode, operation As IOperation) Dim node As SyntaxNode = CompilationUtils.FindBindingText(Of TSyntaxNode)(compilation, fileName, which, prefixMatch:=True) If node Is Nothing Then Return Nothing End If Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim operation = semanticModel.GetOperation(node) If operation IsNot Nothing Then Assert.Same(semanticModel, operation.SemanticModel) Return (OperationTreeVerifier.GetOperationTree(compilation, operation), node, operation) Else Return (Nothing, Nothing, Nothing) End If End Function Friend Shared Function GetOperationTreeForTest(Of TSyntaxNode As SyntaxNode)( source As String, Optional compilationOptions As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional which As Integer = 0, Optional useLatestFrameworkReferences As Boolean = False) As (tree As String, syntax As SyntaxNode, operation As IOperation, compilation As Compilation) Dim fileName = "a.vb" Dim syntaxTree = Parse(source, fileName, parseOptions) Dim allReferences = TargetFrameworkUtil.Mscorlib45ExtendedReferences.Add( If(useLatestFrameworkReferences, TestBase.MsvbRef_v4_0_30319_17929, TestBase.MsvbRef)) Dim compilation = CreateEmptyCompilation({syntaxTree}, references:=allReferences, options:=If(compilationOptions, TestOptions.ReleaseDll)) Dim operationTree = GetOperationTreeForTest(Of TSyntaxNode)(compilation, fileName, which) Return (operationTree.tree, operationTree.syntax, operationTree.operation, compilation) End Function Friend Shared Sub VerifyOperationTreeForTest(Of TSyntaxNode As SyntaxNode)(compilation As VisualBasicCompilation, fileName As String, expectedOperationTree As String, Optional which As Integer = 0, Optional additionalOperationTreeVerifier As Action(Of IOperation, Compilation, SyntaxNode) = Nothing) Dim operationTree = GetOperationTreeForTest(Of TSyntaxNode)(compilation, fileName, which) OperationTreeVerifier.Verify(expectedOperationTree, operationTree.tree) If additionalOperationTreeVerifier IsNot Nothing Then additionalOperationTreeVerifier(operationTree.operation, compilation, operationTree.syntax) End If End Sub Protected Shared Sub VerifyFlowGraphForTest(Of TSyntaxNode As SyntaxNode)(compilation As VisualBasicCompilation, expectedFlowGraph As String, Optional which As Integer = 0) Dim tree = compilation.SyntaxTrees(0) Dim syntaxNode As SyntaxNode = CompilationUtils.FindBindingText(Of TSyntaxNode)(compilation, tree.FilePath, which, prefixMatch:=True) VerifyFlowGraph(compilation, syntaxNode, expectedFlowGraph) End Sub Protected Shared Sub VerifyFlowGraph(compilation As VisualBasicCompilation, syntaxNode As SyntaxNode, expectedFlowGraph As String) Dim model = compilation.GetSemanticModel(syntaxNode.SyntaxTree) Dim graphAndSymbol As (Graph As FlowAnalysis.ControlFlowGraph, AssociatedSymbol As ISymbol) = ControlFlowGraphVerifier.GetControlFlowGraph(syntaxNode, model) ControlFlowGraphVerifier.VerifyGraph(compilation, expectedFlowGraph, graphAndSymbol.Graph, graphAndSymbol.AssociatedSymbol) End Sub Friend Shared Sub VerifyOperationTreeForTest(Of TSyntaxNode As SyntaxNode)( source As String, expectedOperationTree As String, Optional compilationOptions As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional which As Integer = 0, Optional additionalOperationTreeVerifier As Action(Of IOperation, Compilation, SyntaxNode) = Nothing, Optional useLatestFrameworkReferences As Boolean = False) Dim operationTree = GetOperationTreeForTest(Of TSyntaxNode)(source, compilationOptions, parseOptions, which, useLatestFrameworkReferences) OperationTreeVerifier.Verify(expectedOperationTree, operationTree.tree) If additionalOperationTreeVerifier IsNot Nothing Then additionalOperationTreeVerifier(operationTree.operation, operationTree.compilation, operationTree.syntax) End If End Sub Friend Shared Sub VerifyNoOperationTreeForTest(Of TSyntaxNode As SyntaxNode)( source As String, Optional compilationOptions As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional which As Integer = 0, Optional useLatestFrameworkReferences As Boolean = False) Dim operationTree = GetOperationTreeForTest(Of TSyntaxNode)(source, compilationOptions, parseOptions, which, useLatestFrameworkReferences) Assert.Null(operationTree.tree) End Sub Friend Shared Sub VerifyOperationTreeAndDiagnosticsForTest(Of TSyntaxNode As SyntaxNode)(compilation As VisualBasicCompilation, fileName As String, expectedOperationTree As String, expectedDiagnostics As String, Optional which As Integer = 0, Optional additionalOperationTreeVerifier As Action(Of IOperation, Compilation, SyntaxNode) = Nothing) compilation.AssertTheseDiagnostics(FilterString(expectedDiagnostics)) VerifyOperationTreeForTest(Of TSyntaxNode)(compilation, fileName, expectedOperationTree, which, additionalOperationTreeVerifier) End Sub Friend Shared Sub VerifyFlowGraphAndDiagnosticsForTest(Of TSyntaxNode As SyntaxNode)(compilation As VisualBasicCompilation, expectedFlowGraph As String, expectedDiagnostics As String, Optional which As Integer = 0) compilation.AssertTheseDiagnostics(FilterString(expectedDiagnostics)) VerifyFlowGraphForTest(Of TSyntaxNode)(compilation, expectedFlowGraph, which) End Sub Friend Shared Sub VerifyOperationTreeAndDiagnosticsForTest(Of TSyntaxNode As SyntaxNode)( source As String, expectedOperationTree As String, expectedDiagnostics As String, Optional compilationOptions As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional which As Integer = 0, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional additionalOperationTreeVerifier As Action(Of IOperation, Compilation, SyntaxNode) = Nothing, Optional useLatestFramework As Boolean = False) Dim fileName = "a.vb" Dim syntaxTree = Parse(source, fileName, parseOptions) Dim allReferences As IEnumerable(Of MetadataReference) = TargetFrameworkUtil.Mscorlib45ExtendedReferences.Add( If(useLatestFramework, TestBase.MsvbRef_v4_0_30319_17929, TestBase.MsvbRef)) allReferences = If(references IsNot Nothing, allReferences.Concat(references), allReferences) Dim compilation = CreateEmptyCompilation({syntaxTree}, references:=allReferences, options:=If(compilationOptions, TestOptions.ReleaseDll)) VerifyOperationTreeAndDiagnosticsForTest(Of TSyntaxNode)(compilation, fileName, expectedOperationTree, expectedDiagnostics, which, additionalOperationTreeVerifier) End Sub Friend Shared Sub VerifyFlowGraphAndDiagnosticsForTest(Of TSyntaxNode As SyntaxNode)( testSrc As String, expectedFlowGraph As String, expectedDiagnostics As String, Optional compilationOptions As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional which As Integer = 0, Optional additionalReferences As IEnumerable(Of MetadataReference) = Nothing, Optional useLatestFramework As Boolean = False) Dim fileName = "a.vb" Dim syntaxTree = Parse(testSrc, fileName, parseOptions) Dim references As IEnumerable(Of MetadataReference) = TargetFrameworkUtil.Mscorlib45ExtendedReferences.Add( If(useLatestFramework, TestBase.MsvbRef_v4_0_30319_17929, TestBase.MsvbRef)) references = If(additionalReferences IsNot Nothing, references.Concat(additionalReferences), references) Dim compilation = CreateEmptyCompilation({syntaxTree}, references:=references, options:=If(compilationOptions, TestOptions.ReleaseDll)) VerifyFlowGraphAndDiagnosticsForTest(Of TSyntaxNode)(compilation, expectedFlowGraph, expectedDiagnostics, which) End Sub Public Shared Function GetAssertTheseDiagnosticsString(allDiagnostics As ImmutableArray(Of Diagnostic), suppressInfos As Boolean) As String Return DumpAllDiagnostics(allDiagnostics, suppressInfos) End Function Friend Shared Function GetOperationAndSyntaxForTest(Of TSyntaxNode As SyntaxNode)(compilation As Compilation, fileName As String, Optional which As Integer = 0) As (operation As IOperation, syntaxNode As SyntaxNode) Dim node As SyntaxNode = CompilationUtils.FindBindingText(Of TSyntaxNode)(compilation, fileName, which, prefixMatch:=True) If node Is Nothing Then Return (Nothing, Nothing) End If Dim semanticModel = compilation.GetSemanticModel(node.SyntaxTree) Dim operation = semanticModel.GetOperation(node) Assert.Same(semanticModel, operation.SemanticModel) Return (operation, node) End Function #End Region End Class
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/AnonymousTypes/AnonymousTypesEmittedSymbolsTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.IO Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods Public Class AnonymousTypesEmittedSymbolsTests : Inherits BasicTestBase <Fact> Public Sub EmitAnonymousTypeTemplate_NoNeededSymbols() Dim compilationDef = <compilation name="EmitAnonymousTypeTemplate_NoNeededSymbols"> <file name="a.vb"> Class ModuleB Private v1 = New With { .aa = 1 } End Class </file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source:=compilationDef, references:={}) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30002: Type 'System.Void' is not defined. Class ModuleB ~~~~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'EmitAnonymousTypeTemplate_NoNeededSymbols.dll' failed. Class ModuleB ~~~~~~~ BC30002: Type 'System.Object' is not defined. Private v1 = New With { .aa = 1 } ~~ BC30002: Type 'System.Object' is not defined. Private v1 = New With { .aa = 1 } ~~~~~~~~~~~~~~~~ BC30002: Type 'System.Int32' is not defined. Private v1 = New With { .aa = 1 } ~ </errors>) End Sub <Fact> Public Sub EmitAnonymousTypeTemplateGenericTest() Dim compilationDef = <compilation name="EmitGenericAnonymousTypeTemplate"> <file name="a.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Assert.Equal(GetNamedTypeSymbol(m, "System.Object"), type.BaseType) Assert.True(type.IsGenericType) Assert.Equal(3, type.TypeParameters.Length) End Sub) End Sub <Fact> Public Sub EmitAnonymousTypeUnification01() Dim compilationDef = <compilation name="EmitAnonymousTypeUnification01"> <file name="a.vb"> Module ModuleB Sub Test1(x As Integer) Dim at1 As Object = New With { .aa = 1, .b1 = "", .Int = x + x, .Object=Nothing } Dim at2 As Object = New With { .aA = "X"c, .B1 = 0.123# * x, .int = new Object(), .objecT = Nothing } at1 = at2 End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim types = m.ContainingAssembly.GlobalNamespace.GetTypeMembers() Dim list = types.Where(Function(t) t.Name.StartsWith("VB$AnonymousType_", StringComparison.Ordinal)).ToList() Assert.Equal(1, list.Count()) Dim type = list.First() Assert.Equal("VB$AnonymousType_0", type.Name) Assert.Equal(4, type.Arity) Dim mems = type.GetMembers() ' 4 fields, 4 get, 4 set, 1 ctor, 1 ToString Assert.Equal(14, mems.Length) Dim mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt) Assert.Equal(0, mlist.Count) End Sub) End Sub <Fact> Public Sub EmitAnonymousTypeUnification02() Dim compilationDef = <compilation name="EmitAnonymousTypeUnification02"> <file name="b.vb"> Imports System Imports System.Collections.Generic Class A Sub Test(p As List(Of String)) Dim local = New Char() {"a"c, "b"c} Dim at1 As Object = New With {.test = p, Key .key = local, Key .k2 = "QC" + p(0)} End Sub End Class </file> <file name="a.vb"> Structure S Function Test(p As Char()) As Object Dim at2 As Object = New With {.TEST = New System.Collections.Generic.List(Of String)(), Key .Key = p, Key .K2 = ""} Return at2 End Function End Structure </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim types = m.ContainingAssembly.GlobalNamespace.GetTypeMembers() Dim list = types.Where(Function(t) t.Name.StartsWith("VB$AnonymousType", StringComparison.Ordinal)).ToList() Assert.Equal(1, list.Count()) Dim type = list.First() Assert.Equal("VB$AnonymousType_0", type.Name) Assert.Equal(3, type.Arity) Dim mems = type.GetMembers() ' 3 fields, 3 get, 1 set, 1 ctor, 1 ToString, 1 GetHashCode, 2 Equals Assert.Equal(12, mems.Length) Dim mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt) Assert.Equal(3, mlist.Count) End Sub) End Sub <Fact> Public Sub EmitAnonymousTypeUnification03() Dim compilationDef = <compilation name="EmitAnonymousTypeUnification03"> <file name="b.vb"> Imports System Imports System.Collections.Generic Class A Sub Test(p As List(Of String)) Dim local = New Char() {"a"c, "b"c} Dim at1 As Object = New With {.test = p, Key .key = local, Key .k2 = "QC" + p(0)} End Sub End Class </file> <file name="a.vb"> Imports System Imports System.Collections.Generic Class B Sub Test(p As List(Of String)) Dim local = New Char() {"a"c, "b"c} Dim at1 As Object = New With {.test = p, Key .key = local, .k2 = "QC" + p(0)} End Sub End Class </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim types = m.ContainingAssembly.GlobalNamespace.GetTypeMembers() Dim list = types.Where(Function(t) t.Name.StartsWith("VB$AnonymousType", StringComparison.Ordinal)).ToList() ' no unification - diff in key Assert.Equal(2, list.Count()) Dim type = m.ContainingAssembly.GlobalNamespace.GetTypeMembers("VB$AnonymousType_1").Single() Assert.Equal("VB$AnonymousType_1", type.Name) Assert.Equal(3, type.Arity) Dim mems = type.GetMembers() ' Second: 3 fields, 3 get, 2 set, 1 ctor, 1 ToString, 1 GetHashCode, 2 Equals Assert.Equal(13, mems.Length) Dim mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt) Assert.Equal(3, mlist.Count) ' type = m.ContainingAssembly.GlobalNamespace.GetTypeMembers("VB$AnonymousType_0").Single() Assert.Equal("VB$AnonymousType_0", type.Name) Assert.Equal(3, type.Arity) mems = type.GetMembers() ' First: 3 fields, 3 get, 1 set, 1 ctor, 1 ToString, 1 GetHashCode, 2 Equals Assert.Equal(12, mems.Length) mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt) Assert.Equal(3, mlist.Count) End Sub) End Sub <Fact> Public Sub EmitAnonymousTypeCustomModifiers() Dim compilationDef = <compilation name="EmitAnonymousTypeCustomModifiers"> <file name="b.vb"> Imports System Imports System.Collections.Generic Class A Sub Test(p As List(Of String)) Dim intArrMod = Modifiers.F9() Dim at1 = New With { Key .f = intArrMod} Dim at2 = New With { Key .f = New Integer() {}} at1 = at2 at2 = at1 End Sub End Class </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef, TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll}) End Sub <Fact> Public Sub AnonymousTypes_MultiplyEmitOfTheSameAssembly() Dim compilationDef = <compilation name="AnonymousTypes_MultiplyEmitOfTheSameAssembly"> <file name="b.vb"> Module ModuleB Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1 } Dim v2 As Object = New With { Key .AA = "a" } End Sub End Module </file> <file name="a.vb"> Module ModuleA Sub Test1(x As Integer) Dim v1 As Object = New With { .Aa = 1 } Dim v2 As Object = New With { Key .aA = "A" } End Sub End Module </file> <file name="c.vb"> Module ModuleC Sub Test1(x As Integer) Dim v1 As Object = New With { .AA = 1 } Dim v2 As Object = New With { Key .aa = "A" } End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim position = compilationDef.<file>.Value.IndexOf("Dim v2", StringComparison.Ordinal) - 1 ' The sole purpose of this is to check if there will be any asserts ' or exceptions related to adjusted names/locations of anonymous types ' symbols when Emit is called several times for the same compilation For i = 0 To 10 Using stream As New MemoryStream() compilation.Emit(stream) End Using ' do some speculative semantic query Dim expr1 = SyntaxFactory.ParseExpression(<text>New With { .aa = 1, .BB<%= i %> = "" }</text>.Value) Dim info1 = model.GetSpeculativeTypeInfo(position, expr1, SpeculativeBindingOption.BindAsExpression) Assert.NotNull(info1.Type) Next End Sub <Fact> Public Sub EmitCompilerGeneratedAttributeTest() Dim compilationDef = <compilation name="EmitCompilerGeneratedAttributeTest"> <file name="a.vb"> Module Module1 Sub Test1(x As Integer) Dim v As Object = New With { .a = 1 } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`1") Assert.NotNull(type) Dim attr = type.GetAttribute( GetNamedTypeSymbol(m, "System.Runtime.CompilerServices.CompilerGeneratedAttribute")) Assert.NotNull(attr) End Sub) End Sub <Fact> <WorkItem(48417, "https://github.com/dotnet/roslyn/issues/48417")> Public Sub CheckPropertyFieldAndAccessorsNamesTest() Dim compilationDef = <compilation name="CheckPropertyFieldAndAccessorsNamesTest"> <file name="b.vb"> Module ModuleB Sub Test1(x As Integer) Dim v1 As Object = New With { .aab = 1 }.aab Dim v2 As Object = New With { Key .AAB = "a" }.aab End Sub End Module </file> <file name="a.vb"> Module ModuleA Sub Test1(x As Integer) Dim v1 As Object = New With { .Aab = 1 }.aab Dim v2 As Object = New With { Key .aAB = "A" }.aab End Sub End Module </file> <file name="c.vb"> Module ModuleC Sub Test1(x As Integer) Dim v1 As Object = New With { .AAb = 1 }.aab Dim v2 As Object = New With { Key .aaB = "A" }.aab End Sub End Module </file> </compilation> ' Cycle to hopefully get different order of files For i = 0 To 50 CompileAndVerify(compilationDef, references:={SystemCoreRef}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`1") Assert.NotNull(type) CheckPropertyAccessorsAndField(m, type, "aab", type.TypeParameters(0), False) type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_1`1") Assert.NotNull(type) CheckPropertyAccessorsAndField(m, type, "AAB", type.TypeParameters(0), True) End Sub) Next End Sub <Fact> Public Sub CheckEmittedSymbol_ctor() Dim compilationDef = <compilation name="CheckEmittedSymbol_ctor"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Assert.Equal(1, type.InstanceConstructors.Length) Dim constr = type.InstanceConstructors(0) CheckMethod(m, constr, ".ctor", Accessibility.Public, isSub:=True, paramCount:=3) Assert.Equal(type.TypeParameters(0), constr.Parameters(0).Type) Assert.Equal("aa", constr.Parameters(0).Name) Assert.Equal(type.TypeParameters(1), constr.Parameters(1).Type) Assert.Equal("BB", constr.Parameters(1).Name) Assert.Equal(type.TypeParameters(2), constr.Parameters(2).Type) Assert.Equal("CCC", constr.Parameters(2).Name) End Sub) End Sub <Fact> Public Sub CheckEmittedSymbol_ToString() Dim compilationDef = <compilation name="CheckEmittedSymbol_ToString"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Dim toStr = type.GetMember(Of MethodSymbol)("ToString") CheckMethod(m, toStr, "ToString", Accessibility.Public, retType:=GetNamedTypeSymbol(m, "System.String"), isOverrides:=True, isOverloads:=True) Assert.Equal(GetNamedTypeSymbol(m, "System.Object").GetMember("ToString"), toStr.OverriddenMethod) End Sub) End Sub <Fact> Public Sub CheckNoExtraMethodsAreEmittedIfThereIsNoKeyFields() Dim compilationDef = <compilation name="CheckNoExtraMethodsAreEmittedIfThereIsNoKeyFields"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Assert.Equal(0, type.Interfaces.Length) Assert.Equal(0, type.GetMembers("GetHashCode").Length) Assert.Equal(0, type.GetMembers("Equals").Length) End Sub) End Sub <Fact> Public Sub CheckEmittedSymbol_SystemObject_Equals() Dim compilationDef = <compilation name="CheckEmittedSymbol_SystemObject_Equals"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { Key .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Dim method = DirectCast(type.GetMembers("Equals"). Where(Function(s) Return DirectCast(s, MethodSymbol).ExplicitInterfaceImplementations.Length = 0 End Function).Single(), MethodSymbol) CheckMethod(m, method, "Equals", Accessibility.Public, retType:=GetNamedTypeSymbol(m, "System.Boolean"), isOverrides:=True, isOverloads:=True, paramCount:=1) Assert.Equal(GetNamedTypeSymbol(m, "System.Object"), method.Parameters(0).Type) Assert.Equal(GetNamedTypeSymbol(m, "System.Object"). GetMembers("Equals").Where(Function(s) Not s.IsShared).Single(), method.OverriddenMethod) End Sub) End Sub <Fact> Public Sub CheckEmittedSymbol_GetHashCode() Dim compilationDef = <compilation name="CheckEmittedSymbol_GetHashCode"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { Key .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Dim method = type.GetMember(Of MethodSymbol)("GetHashCode") CheckMethod(m, method, "GetHashCode", Accessibility.Public, retType:=GetNamedTypeSymbol(m, "System.Int32"), isOverrides:=True, isOverloads:=True) Assert.Equal(GetNamedTypeSymbol(m, "System.Object").GetMember("GetHashCode"), method.OverriddenMethod) End Sub) End Sub <Fact> Public Sub CheckEmittedSymbol_IEquatableImplementation() Dim compilationDef = <compilation name="CheckEmittedSymbol_GetHashCode"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { Key .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Assert.Equal(1, type.Interfaces.Length) Dim [interface] = type.Interfaces(0) Assert.Equal(GetNamedTypeSymbol(m, "System.IEquatable").Construct(type), [interface]) Dim method = DirectCast(type.GetMembers("Equals"). Where(Function(s) Return DirectCast(s, MethodSymbol).ExplicitInterfaceImplementations.Length = 1 End Function).Single(), MethodSymbol) CheckMethod(m, method, "Equals", Accessibility.Public, retType:=GetNamedTypeSymbol(m, "System.Boolean"), paramCount:=1, isOverloads:=True) Assert.Equal(type, method.Parameters(0).Type) Assert.Equal([interface].GetMember("Equals"), method.ExplicitInterfaceImplementations(0)) End Sub) End Sub <Fact> Public Sub NotEmittingAnonymousTypeCreatedSolelyViaSemanticAPI() Dim compilationDef = <compilation name="NotEmittingAnonymousTypeCreatedSolelyViaSemanticAPI"> <file name="a.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() } 'POSITION End Sub End Module </file> </compilation> Dim position = compilationDef.<file>.Value.IndexOf("'POSITION", StringComparison.Ordinal) CompileAndVerify(compilationDef, references:={SystemCoreRef}, sourceSymbolValidator:=Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node0 = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.AnonymousObjectCreationExpression).AsNode(), ExpressionSyntax) Dim info0 = model.GetSemanticInfoSummary(node0) Assert.NotNull(info0.Type) Assert.IsType(GetType(AnonymousTypeManager.AnonymousTypePublicSymbol), info0.Type) Assert.False(DirectCast(info0.Type, INamedTypeSymbol).IsSerializable) Dim expr1 = SyntaxFactory.ParseExpression(<text>New With { .aa = 1, .BB = "", .CCC = new SSS() }</text>.Value) Dim info1 = model.GetSpeculativeTypeInfo(position, expr1, SpeculativeBindingOption.BindAsExpression) Assert.NotNull(info1.Type) Assert.Equal(info0.Type.OriginalDefinition, info1.Type.OriginalDefinition) Dim expr2 = SyntaxFactory.ParseExpression(<text>New With { .aa = 1, Key .BB = "", .CCC = new SSS() }</text>.Value) Dim info2 = model.GetSpeculativeTypeInfo(position, expr2, SpeculativeBindingOption.BindAsExpression) Assert.NotNull(info2.Type) Assert.NotEqual(info0.Type.OriginalDefinition, info2.Type.OriginalDefinition) End Sub, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Assert.Equal(GetNamedTypeSymbol(m, "System.Object"), type.BaseType) Assert.True(type.IsGenericType) Assert.Equal(3, type.TypeParameters.Length) ' Only one type should be emitted!! Dim type2 = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_1`3") Assert.Null(type2) End Sub) End Sub <Fact> <WorkItem(641639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/641639")> Public Sub Bug641639() Dim moduleDef = <compilation name="TestModule"> <file name="a.vb"> Module ModuleB Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1 } Dim v2 As Object = Function(y as Integer) y + 1 End Sub End Module </file> </compilation> Dim testModule = CreateCompilationWithMscorlib40AndVBRuntime(moduleDef, TestOptions.ReleaseModule) Dim compilationDef = <compilation> <file name="a.vb"> Module ModuleA End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(moduleDef, {testModule.EmitToImageReference()}, TestOptions.ReleaseDll) Assert.Equal(1, compilation.Assembly.Modules(1).GlobalNamespace.GetTypeMembers("VB$AnonymousDelegate_0<TestModule>", 2).Length) Assert.Equal(1, compilation.Assembly.Modules(1).GlobalNamespace.GetTypeMembers("VB$AnonymousType_0<TestModule>", 1).Length) End Sub #Region "Utils" Private Shared Sub CheckPropertyAccessorsAndField(m As ModuleSymbol, type As NamedTypeSymbol, propName As String, propType As TypeSymbol, isKey As Boolean) Dim prop = type.GetMembers().OfType(Of PropertySymbol)().Single() Assert.Equal(propType, prop.Type) Assert.Equal(propName, prop.Name) Assert.Equal(propName, prop.MetadataName) Assert.Equal(Accessibility.Public, prop.DeclaredAccessibility) Assert.False(prop.IsDefault) Assert.False(prop.IsMustOverride) Assert.False(prop.IsNotOverridable) Assert.False(prop.IsOverridable) Assert.False(prop.IsOverrides) Assert.False(prop.IsOverloads) Assert.Equal(isKey, prop.IsReadOnly) Assert.False(prop.IsShared) Assert.False(prop.IsWriteOnly) Assert.Equal(0, prop.Parameters.Length) Assert.False(prop.ShadowsExplicitly) Dim getter = prop.GetMethod CheckMethod(m, getter, "get_" & prop.Name, Accessibility.Public, retType:=getter.ReturnType) If Not isKey Then Dim setter = prop.SetMethod CheckMethod(m, setter, "set_" & prop.Name, Accessibility.Public, paramCount:=1, isSub:=True) Assert.Equal(propType, setter.Parameters(0).Type) Else Assert.Null(prop.SetMethod) End If Dim field = type.GetMembers().OfType(Of FieldSymbol)().Single() Assert.Equal(propType, field.Type) Assert.Equal("$" & propName, field.Name) Assert.Equal("$" & propName, field.MetadataName) Assert.Equal(Accessibility.Private, field.DeclaredAccessibility) Dim parameter = type.Constructors.Single().Parameters(0) Assert.Equal(propType, parameter.Type) Assert.Equal(propName, parameter.Name) Assert.Equal(propName, parameter.MetadataName) End Sub Private Shared Sub CheckMethod(m As ModuleSymbol, method As MethodSymbol, name As String, accessibility As Accessibility, Optional paramCount As Integer = 0, Optional retType As TypeSymbol = Nothing, Optional isSub As Boolean = False, Optional isOverloads As Boolean = False, Optional isOverrides As Boolean = False, Optional isOverridable As Boolean = False, Optional isNotOverridable As Boolean = False) Assert.NotNull(method) Assert.Equal(name, method.Name) Assert.Equal(name, method.MetadataName) Assert.Equal(paramCount, method.ParameterCount) If isSub Then Assert.Null(retType) Assert.Equal(GetNamedTypeSymbol(m, "System.Void"), method.ReturnType) Assert.True(method.IsSub) End If If retType IsNot Nothing Then Assert.False(isSub) Assert.Equal(retType, method.ReturnType) Assert.False(method.IsSub) End If Assert.Equal(accessibility, method.DeclaredAccessibility) Assert.Equal(isOverloads, method.IsOverloads) Assert.Equal(isOverrides, method.IsOverrides) Assert.Equal(isOverridable, method.IsOverridable) Assert.Equal(isNotOverridable, method.IsNotOverridable) Assert.False(method.IsShared) Assert.False(method.IsMustOverride) Assert.False(method.IsGenericMethod) Assert.False(method.ShadowsExplicitly) End Sub Private Shared Function GetNamedTypeSymbol(m As ModuleSymbol, namedTypeName As String) As NamedTypeSymbol Dim nameParts = namedTypeName.Split("."c) Dim peAssembly = DirectCast(m.ContainingAssembly, PEAssemblySymbol) Dim nsSymbol As NamespaceSymbol = Nothing For Each ns In nameParts.Take(nameParts.Length - 1) nsSymbol = DirectCast(If(nsSymbol Is Nothing, m.ContainingAssembly.CorLibrary.GlobalNamespace.GetMember(ns), nsSymbol.GetMember(ns)), NamespaceSymbol) Next Return DirectCast(nsSymbol.GetTypeMember(nameParts(nameParts.Length - 1)), NamedTypeSymbol) End Function #End Region <WorkItem(1319, "https://github.com/dotnet/roslyn/issues/1319")> <ConditionalFact(GetType(DesktopOnly), Reason:=ConditionalSkipReason.NetModulesNeedDesktop)> Public Sub MultipleNetmodulesWithAnonymousTypes() Dim compilationDef1 = <compilation> <file name="a.vb"> Class A Friend o1 As Object = new with { .hello = 1, .world = 2 } Friend d1 As Object = Function() 1 public shared Function M1() As String return "Hello, " End Function End Class </file> </compilation> Dim compilationDef2 = <compilation> <file name="a.vb"> Class B Inherits A Friend o2 As Object = new with { .hello = 1, .world = 2 } Friend d2 As Object = Function() 1 public shared Function M2() As String return "world!" End Function End Class </file> </compilation> Dim compilationDef3 = <compilation> <file name="a.vb"> Class Module1 Friend o3 As Object = new with { .hello = 1, .world = 2 } Friend d3 As Object = Function() 1 public shared Sub Main() System.Console.Write(A.M1()) System.Console.WriteLine(B.M2()) End Sub End Class </file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(compilationDef1, options:=TestOptions.ReleaseModule.WithModuleName("A")) comp1.VerifyDiagnostics() Dim ref1 = comp1.EmitToImageReference() Dim comp2 = CreateCompilationWithMscorlib40AndReferences(compilationDef2, {ref1}, options:=TestOptions.ReleaseModule.WithModuleName("B")) comp2.VerifyDiagnostics() Dim ref2 = comp2.EmitToImageReference() Dim comp3 = CreateCompilationWithMscorlib40AndReferences(compilationDef3, {ref1, ref2}, options:=TestOptions.ReleaseExe.WithModuleName("C")) comp3.VerifyDiagnostics() Dim mA = comp3.Assembly.Modules(1) Assert.Equal("VB$AnonymousType_0<A>`2", mA.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousType")).Single().MetadataName) Assert.Equal("VB$AnonymousDelegate_0<A>`1", mA.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousDelegate")).Single().MetadataName) Dim mB = comp3.Assembly.Modules(2) Assert.Equal("VB$AnonymousType_0<B>`2", mB.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousType")).Single().MetadataName) Assert.Equal("VB$AnonymousDelegate_0<B>`1", mB.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousDelegate")).Single().MetadataName) CompileAndVerify(comp3, expectedOutput:="Hello, world!", symbolValidator:= Sub(m) Dim mC = DirectCast(m, PEModuleSymbol) Assert.Equal("VB$AnonymousType_0`2", mC.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousType")).Single().MetadataName) Assert.Equal("VB$AnonymousDelegate_0`1", mC.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousDelegate")).Single().MetadataName) End Sub) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.IO Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods Public Class AnonymousTypesEmittedSymbolsTests : Inherits BasicTestBase <Fact> Public Sub EmitAnonymousTypeTemplate_NoNeededSymbols() Dim compilationDef = <compilation name="EmitAnonymousTypeTemplate_NoNeededSymbols"> <file name="a.vb"> Class ModuleB Private v1 = New With { .aa = 1 } End Class </file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source:=compilationDef, references:={}) CompilationUtils.AssertTheseDiagnostics(compilation, <errors> BC30002: Type 'System.Void' is not defined. Class ModuleB ~~~~~~~~~~~~~~ BC31091: Import of type 'Object' from assembly or module 'EmitAnonymousTypeTemplate_NoNeededSymbols.dll' failed. Class ModuleB ~~~~~~~ BC30002: Type 'System.Object' is not defined. Private v1 = New With { .aa = 1 } ~~ BC30002: Type 'System.Object' is not defined. Private v1 = New With { .aa = 1 } ~~~~~~~~~~~~~~~~ BC30002: Type 'System.Int32' is not defined. Private v1 = New With { .aa = 1 } ~ </errors>) End Sub <Fact> Public Sub EmitAnonymousTypeTemplateGenericTest() Dim compilationDef = <compilation name="EmitGenericAnonymousTypeTemplate"> <file name="a.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Assert.Equal(GetNamedTypeSymbol(m, "System.Object"), type.BaseType) Assert.True(type.IsGenericType) Assert.Equal(3, type.TypeParameters.Length) End Sub) End Sub <Fact> Public Sub EmitAnonymousTypeUnification01() Dim compilationDef = <compilation name="EmitAnonymousTypeUnification01"> <file name="a.vb"> Module ModuleB Sub Test1(x As Integer) Dim at1 As Object = New With { .aa = 1, .b1 = "", .Int = x + x, .Object=Nothing } Dim at2 As Object = New With { .aA = "X"c, .B1 = 0.123# * x, .int = new Object(), .objecT = Nothing } at1 = at2 End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim types = m.ContainingAssembly.GlobalNamespace.GetTypeMembers() Dim list = types.Where(Function(t) t.Name.StartsWith("VB$AnonymousType_", StringComparison.Ordinal)).ToList() Assert.Equal(1, list.Count()) Dim type = list.First() Assert.Equal("VB$AnonymousType_0", type.Name) Assert.Equal(4, type.Arity) Dim mems = type.GetMembers() ' 4 fields, 4 get, 4 set, 1 ctor, 1 ToString Assert.Equal(14, mems.Length) Dim mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt) Assert.Equal(0, mlist.Count) End Sub) End Sub <Fact> Public Sub EmitAnonymousTypeUnification02() Dim compilationDef = <compilation name="EmitAnonymousTypeUnification02"> <file name="b.vb"> Imports System Imports System.Collections.Generic Class A Sub Test(p As List(Of String)) Dim local = New Char() {"a"c, "b"c} Dim at1 As Object = New With {.test = p, Key .key = local, Key .k2 = "QC" + p(0)} End Sub End Class </file> <file name="a.vb"> Structure S Function Test(p As Char()) As Object Dim at2 As Object = New With {.TEST = New System.Collections.Generic.List(Of String)(), Key .Key = p, Key .K2 = ""} Return at2 End Function End Structure </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim types = m.ContainingAssembly.GlobalNamespace.GetTypeMembers() Dim list = types.Where(Function(t) t.Name.StartsWith("VB$AnonymousType", StringComparison.Ordinal)).ToList() Assert.Equal(1, list.Count()) Dim type = list.First() Assert.Equal("VB$AnonymousType_0", type.Name) Assert.Equal(3, type.Arity) Dim mems = type.GetMembers() ' 3 fields, 3 get, 1 set, 1 ctor, 1 ToString, 1 GetHashCode, 2 Equals Assert.Equal(12, mems.Length) Dim mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt) Assert.Equal(3, mlist.Count) End Sub) End Sub <Fact> Public Sub EmitAnonymousTypeUnification03() Dim compilationDef = <compilation name="EmitAnonymousTypeUnification03"> <file name="b.vb"> Imports System Imports System.Collections.Generic Class A Sub Test(p As List(Of String)) Dim local = New Char() {"a"c, "b"c} Dim at1 As Object = New With {.test = p, Key .key = local, Key .k2 = "QC" + p(0)} End Sub End Class </file> <file name="a.vb"> Imports System Imports System.Collections.Generic Class B Sub Test(p As List(Of String)) Dim local = New Char() {"a"c, "b"c} Dim at1 As Object = New With {.test = p, Key .key = local, .k2 = "QC" + p(0)} End Sub End Class </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim types = m.ContainingAssembly.GlobalNamespace.GetTypeMembers() Dim list = types.Where(Function(t) t.Name.StartsWith("VB$AnonymousType", StringComparison.Ordinal)).ToList() ' no unification - diff in key Assert.Equal(2, list.Count()) Dim type = m.ContainingAssembly.GlobalNamespace.GetTypeMembers("VB$AnonymousType_1").Single() Assert.Equal("VB$AnonymousType_1", type.Name) Assert.Equal(3, type.Arity) Dim mems = type.GetMembers() ' Second: 3 fields, 3 get, 2 set, 1 ctor, 1 ToString, 1 GetHashCode, 2 Equals Assert.Equal(13, mems.Length) Dim mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt) Assert.Equal(3, mlist.Count) ' type = m.ContainingAssembly.GlobalNamespace.GetTypeMembers("VB$AnonymousType_0").Single() Assert.Equal("VB$AnonymousType_0", type.Name) Assert.Equal(3, type.Arity) mems = type.GetMembers() ' First: 3 fields, 3 get, 1 set, 1 ctor, 1 ToString, 1 GetHashCode, 2 Equals Assert.Equal(12, mems.Length) mlist = mems.Where(Function(mt) mt.Name = "GetHashCode" OrElse mt.Name = "Equals").Select(Function(mt) mt) Assert.Equal(3, mlist.Count) End Sub) End Sub <Fact> Public Sub EmitAnonymousTypeCustomModifiers() Dim compilationDef = <compilation name="EmitAnonymousTypeCustomModifiers"> <file name="b.vb"> Imports System Imports System.Collections.Generic Class A Sub Test(p As List(Of String)) Dim intArrMod = Modifiers.F9() Dim at1 = New With { Key .f = intArrMod} Dim at2 = New With { Key .f = New Integer() {}} at1 = at2 at2 = at1 End Sub End Class </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef, TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll}) End Sub <Fact> Public Sub AnonymousTypes_MultiplyEmitOfTheSameAssembly() Dim compilationDef = <compilation name="AnonymousTypes_MultiplyEmitOfTheSameAssembly"> <file name="b.vb"> Module ModuleB Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1 } Dim v2 As Object = New With { Key .AA = "a" } End Sub End Module </file> <file name="a.vb"> Module ModuleA Sub Test1(x As Integer) Dim v1 As Object = New With { .Aa = 1 } Dim v2 As Object = New With { Key .aA = "A" } End Sub End Module </file> <file name="c.vb"> Module ModuleC Sub Test1(x As Integer) Dim v1 As Object = New With { .AA = 1 } Dim v2 As Object = New With { Key .aa = "A" } End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim position = compilationDef.<file>.Value.IndexOf("Dim v2", StringComparison.Ordinal) - 1 ' The sole purpose of this is to check if there will be any asserts ' or exceptions related to adjusted names/locations of anonymous types ' symbols when Emit is called several times for the same compilation For i = 0 To 10 Using stream As New MemoryStream() compilation.Emit(stream) End Using ' do some speculative semantic query Dim expr1 = SyntaxFactory.ParseExpression(<text>New With { .aa = 1, .BB<%= i %> = "" }</text>.Value) Dim info1 = model.GetSpeculativeTypeInfo(position, expr1, SpeculativeBindingOption.BindAsExpression) Assert.NotNull(info1.Type) Next End Sub <Fact> Public Sub EmitCompilerGeneratedAttributeTest() Dim compilationDef = <compilation name="EmitCompilerGeneratedAttributeTest"> <file name="a.vb"> Module Module1 Sub Test1(x As Integer) Dim v As Object = New With { .a = 1 } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`1") Assert.NotNull(type) Dim attr = type.GetAttribute( GetNamedTypeSymbol(m, "System.Runtime.CompilerServices.CompilerGeneratedAttribute")) Assert.NotNull(attr) End Sub) End Sub <Fact> <WorkItem(48417, "https://github.com/dotnet/roslyn/issues/48417")> Public Sub CheckPropertyFieldAndAccessorsNamesTest() Dim compilationDef = <compilation name="CheckPropertyFieldAndAccessorsNamesTest"> <file name="b.vb"> Module ModuleB Sub Test1(x As Integer) Dim v1 As Object = New With { .aab = 1 }.aab Dim v2 As Object = New With { Key .AAB = "a" }.aab End Sub End Module </file> <file name="a.vb"> Module ModuleA Sub Test1(x As Integer) Dim v1 As Object = New With { .Aab = 1 }.aab Dim v2 As Object = New With { Key .aAB = "A" }.aab End Sub End Module </file> <file name="c.vb"> Module ModuleC Sub Test1(x As Integer) Dim v1 As Object = New With { .AAb = 1 }.aab Dim v2 As Object = New With { Key .aaB = "A" }.aab End Sub End Module </file> </compilation> ' Cycle to hopefully get different order of files For i = 0 To 50 CompileAndVerify(compilationDef, references:={SystemCoreRef}, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`1") Assert.NotNull(type) CheckPropertyAccessorsAndField(m, type, "aab", type.TypeParameters(0), False) type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_1`1") Assert.NotNull(type) CheckPropertyAccessorsAndField(m, type, "AAB", type.TypeParameters(0), True) End Sub) Next End Sub <Fact> Public Sub CheckEmittedSymbol_ctor() Dim compilationDef = <compilation name="CheckEmittedSymbol_ctor"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Assert.Equal(1, type.InstanceConstructors.Length) Dim constr = type.InstanceConstructors(0) CheckMethod(m, constr, ".ctor", Accessibility.Public, isSub:=True, paramCount:=3) Assert.Equal(type.TypeParameters(0), constr.Parameters(0).Type) Assert.Equal("aa", constr.Parameters(0).Name) Assert.Equal(type.TypeParameters(1), constr.Parameters(1).Type) Assert.Equal("BB", constr.Parameters(1).Name) Assert.Equal(type.TypeParameters(2), constr.Parameters(2).Type) Assert.Equal("CCC", constr.Parameters(2).Name) End Sub) End Sub <Fact> Public Sub CheckEmittedSymbol_ToString() Dim compilationDef = <compilation name="CheckEmittedSymbol_ToString"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Dim toStr = type.GetMember(Of MethodSymbol)("ToString") CheckMethod(m, toStr, "ToString", Accessibility.Public, retType:=GetNamedTypeSymbol(m, "System.String"), isOverrides:=True, isOverloads:=True) Assert.Equal(GetNamedTypeSymbol(m, "System.Object").GetMember("ToString"), toStr.OverriddenMethod) End Sub) End Sub <Fact> Public Sub CheckNoExtraMethodsAreEmittedIfThereIsNoKeyFields() Dim compilationDef = <compilation name="CheckNoExtraMethodsAreEmittedIfThereIsNoKeyFields"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Assert.Equal(0, type.Interfaces.Length) Assert.Equal(0, type.GetMembers("GetHashCode").Length) Assert.Equal(0, type.GetMembers("Equals").Length) End Sub) End Sub <Fact> Public Sub CheckEmittedSymbol_SystemObject_Equals() Dim compilationDef = <compilation name="CheckEmittedSymbol_SystemObject_Equals"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { Key .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Dim method = DirectCast(type.GetMembers("Equals"). Where(Function(s) Return DirectCast(s, MethodSymbol).ExplicitInterfaceImplementations.Length = 0 End Function).Single(), MethodSymbol) CheckMethod(m, method, "Equals", Accessibility.Public, retType:=GetNamedTypeSymbol(m, "System.Boolean"), isOverrides:=True, isOverloads:=True, paramCount:=1) Assert.Equal(GetNamedTypeSymbol(m, "System.Object"), method.Parameters(0).Type) Assert.Equal(GetNamedTypeSymbol(m, "System.Object"). GetMembers("Equals").Where(Function(s) Not s.IsShared).Single(), method.OverriddenMethod) End Sub) End Sub <Fact> Public Sub CheckEmittedSymbol_GetHashCode() Dim compilationDef = <compilation name="CheckEmittedSymbol_GetHashCode"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { Key .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Dim method = type.GetMember(Of MethodSymbol)("GetHashCode") CheckMethod(m, method, "GetHashCode", Accessibility.Public, retType:=GetNamedTypeSymbol(m, "System.Int32"), isOverrides:=True, isOverloads:=True) Assert.Equal(GetNamedTypeSymbol(m, "System.Object").GetMember("GetHashCode"), method.OverriddenMethod) End Sub) End Sub <Fact> Public Sub CheckEmittedSymbol_IEquatableImplementation() Dim compilationDef = <compilation name="CheckEmittedSymbol_GetHashCode"> <file name="b.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { Key .aa = 1, .BB = "", .CCC = new SSS() } End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, references:={SystemCoreRef}, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Assert.Equal(1, type.Interfaces.Length) Dim [interface] = type.Interfaces(0) Assert.Equal(GetNamedTypeSymbol(m, "System.IEquatable").Construct(type), [interface]) Dim method = DirectCast(type.GetMembers("Equals"). Where(Function(s) Return DirectCast(s, MethodSymbol).ExplicitInterfaceImplementations.Length = 1 End Function).Single(), MethodSymbol) CheckMethod(m, method, "Equals", Accessibility.Public, retType:=GetNamedTypeSymbol(m, "System.Boolean"), paramCount:=1, isOverloads:=True) Assert.Equal(type, method.Parameters(0).Type) Assert.Equal([interface].GetMember("Equals"), method.ExplicitInterfaceImplementations(0)) End Sub) End Sub <Fact> Public Sub NotEmittingAnonymousTypeCreatedSolelyViaSemanticAPI() Dim compilationDef = <compilation name="NotEmittingAnonymousTypeCreatedSolelyViaSemanticAPI"> <file name="a.vb"> Module ModuleB Structure SSS End Structure Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1, .BB = "", .CCC = new SSS() } 'POSITION End Sub End Module </file> </compilation> Dim position = compilationDef.<file>.Value.IndexOf("'POSITION", StringComparison.Ordinal) CompileAndVerify(compilationDef, references:={SystemCoreRef}, sourceSymbolValidator:=Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node0 = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.AnonymousObjectCreationExpression).AsNode(), ExpressionSyntax) Dim info0 = model.GetSemanticInfoSummary(node0) Assert.NotNull(info0.Type) Assert.IsType(GetType(AnonymousTypeManager.AnonymousTypePublicSymbol), info0.Type) Assert.False(DirectCast(info0.Type, INamedTypeSymbol).IsSerializable) Dim expr1 = SyntaxFactory.ParseExpression(<text>New With { .aa = 1, .BB = "", .CCC = new SSS() }</text>.Value) Dim info1 = model.GetSpeculativeTypeInfo(position, expr1, SpeculativeBindingOption.BindAsExpression) Assert.NotNull(info1.Type) Assert.Equal(info0.Type.OriginalDefinition, info1.Type.OriginalDefinition) Dim expr2 = SyntaxFactory.ParseExpression(<text>New With { .aa = 1, Key .BB = "", .CCC = new SSS() }</text>.Value) Dim info2 = model.GetSpeculativeTypeInfo(position, expr2, SpeculativeBindingOption.BindAsExpression) Assert.NotNull(info2.Type) Assert.NotEqual(info0.Type.OriginalDefinition, info2.Type.OriginalDefinition) End Sub, symbolValidator:=Sub(m As ModuleSymbol) Dim type = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_0`3") Assert.NotNull(type) Assert.Equal(GetNamedTypeSymbol(m, "System.Object"), type.BaseType) Assert.True(type.IsGenericType) Assert.Equal(3, type.TypeParameters.Length) ' Only one type should be emitted!! Dim type2 = m.ContainingAssembly.GetTypeByMetadataName("VB$AnonymousType_1`3") Assert.Null(type2) End Sub) End Sub <Fact> <WorkItem(641639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/641639")> Public Sub Bug641639() Dim moduleDef = <compilation name="TestModule"> <file name="a.vb"> Module ModuleB Sub Test1(x As Integer) Dim v1 As Object = New With { .aa = 1 } Dim v2 As Object = Function(y as Integer) y + 1 End Sub End Module </file> </compilation> Dim testModule = CreateCompilationWithMscorlib40AndVBRuntime(moduleDef, TestOptions.ReleaseModule) Dim compilationDef = <compilation> <file name="a.vb"> Module ModuleA End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(moduleDef, {testModule.EmitToImageReference()}, TestOptions.ReleaseDll) Assert.Equal(1, compilation.Assembly.Modules(1).GlobalNamespace.GetTypeMembers("VB$AnonymousDelegate_0<TestModule>", 2).Length) Assert.Equal(1, compilation.Assembly.Modules(1).GlobalNamespace.GetTypeMembers("VB$AnonymousType_0<TestModule>", 1).Length) End Sub #Region "Utils" Private Shared Sub CheckPropertyAccessorsAndField(m As ModuleSymbol, type As NamedTypeSymbol, propName As String, propType As TypeSymbol, isKey As Boolean) Dim prop = type.GetMembers().OfType(Of PropertySymbol)().Single() Assert.Equal(propType, prop.Type) Assert.Equal(propName, prop.Name) Assert.Equal(propName, prop.MetadataName) Assert.Equal(Accessibility.Public, prop.DeclaredAccessibility) Assert.False(prop.IsDefault) Assert.False(prop.IsMustOverride) Assert.False(prop.IsNotOverridable) Assert.False(prop.IsOverridable) Assert.False(prop.IsOverrides) Assert.False(prop.IsOverloads) Assert.Equal(isKey, prop.IsReadOnly) Assert.False(prop.IsShared) Assert.False(prop.IsWriteOnly) Assert.Equal(0, prop.Parameters.Length) Assert.False(prop.ShadowsExplicitly) Dim getter = prop.GetMethod CheckMethod(m, getter, "get_" & prop.Name, Accessibility.Public, retType:=getter.ReturnType) If Not isKey Then Dim setter = prop.SetMethod CheckMethod(m, setter, "set_" & prop.Name, Accessibility.Public, paramCount:=1, isSub:=True) Assert.Equal(propType, setter.Parameters(0).Type) Else Assert.Null(prop.SetMethod) End If Dim field = type.GetMembers().OfType(Of FieldSymbol)().Single() Assert.Equal(propType, field.Type) Assert.Equal("$" & propName, field.Name) Assert.Equal("$" & propName, field.MetadataName) Assert.Equal(Accessibility.Private, field.DeclaredAccessibility) Dim parameter = type.Constructors.Single().Parameters(0) Assert.Equal(propType, parameter.Type) Assert.Equal(propName, parameter.Name) Assert.Equal(propName, parameter.MetadataName) End Sub Private Shared Sub CheckMethod(m As ModuleSymbol, method As MethodSymbol, name As String, accessibility As Accessibility, Optional paramCount As Integer = 0, Optional retType As TypeSymbol = Nothing, Optional isSub As Boolean = False, Optional isOverloads As Boolean = False, Optional isOverrides As Boolean = False, Optional isOverridable As Boolean = False, Optional isNotOverridable As Boolean = False) Assert.NotNull(method) Assert.Equal(name, method.Name) Assert.Equal(name, method.MetadataName) Assert.Equal(paramCount, method.ParameterCount) If isSub Then Assert.Null(retType) Assert.Equal(GetNamedTypeSymbol(m, "System.Void"), method.ReturnType) Assert.True(method.IsSub) End If If retType IsNot Nothing Then Assert.False(isSub) Assert.Equal(retType, method.ReturnType) Assert.False(method.IsSub) End If Assert.Equal(accessibility, method.DeclaredAccessibility) Assert.Equal(isOverloads, method.IsOverloads) Assert.Equal(isOverrides, method.IsOverrides) Assert.Equal(isOverridable, method.IsOverridable) Assert.Equal(isNotOverridable, method.IsNotOverridable) Assert.False(method.IsShared) Assert.False(method.IsMustOverride) Assert.False(method.IsGenericMethod) Assert.False(method.ShadowsExplicitly) End Sub Private Shared Function GetNamedTypeSymbol(m As ModuleSymbol, namedTypeName As String) As NamedTypeSymbol Dim nameParts = namedTypeName.Split("."c) Dim peAssembly = DirectCast(m.ContainingAssembly, PEAssemblySymbol) Dim nsSymbol As NamespaceSymbol = Nothing For Each ns In nameParts.Take(nameParts.Length - 1) nsSymbol = DirectCast(If(nsSymbol Is Nothing, m.ContainingAssembly.CorLibrary.GlobalNamespace.GetMember(ns), nsSymbol.GetMember(ns)), NamespaceSymbol) Next Return DirectCast(nsSymbol.GetTypeMember(nameParts(nameParts.Length - 1)), NamedTypeSymbol) End Function #End Region <WorkItem(1319, "https://github.com/dotnet/roslyn/issues/1319")> <ConditionalFact(GetType(DesktopOnly), Reason:=ConditionalSkipReason.NetModulesNeedDesktop)> Public Sub MultipleNetmodulesWithAnonymousTypes() Dim compilationDef1 = <compilation> <file name="a.vb"> Class A Friend o1 As Object = new with { .hello = 1, .world = 2 } Friend d1 As Object = Function() 1 public shared Function M1() As String return "Hello, " End Function End Class </file> </compilation> Dim compilationDef2 = <compilation> <file name="a.vb"> Class B Inherits A Friend o2 As Object = new with { .hello = 1, .world = 2 } Friend d2 As Object = Function() 1 public shared Function M2() As String return "world!" End Function End Class </file> </compilation> Dim compilationDef3 = <compilation> <file name="a.vb"> Class Module1 Friend o3 As Object = new with { .hello = 1, .world = 2 } Friend d3 As Object = Function() 1 public shared Sub Main() System.Console.Write(A.M1()) System.Console.WriteLine(B.M2()) End Sub End Class </file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(compilationDef1, options:=TestOptions.ReleaseModule.WithModuleName("A")) comp1.VerifyDiagnostics() Dim ref1 = comp1.EmitToImageReference() Dim comp2 = CreateCompilationWithMscorlib40AndReferences(compilationDef2, {ref1}, options:=TestOptions.ReleaseModule.WithModuleName("B")) comp2.VerifyDiagnostics() Dim ref2 = comp2.EmitToImageReference() Dim comp3 = CreateCompilationWithMscorlib40AndReferences(compilationDef3, {ref1, ref2}, options:=TestOptions.ReleaseExe.WithModuleName("C")) comp3.VerifyDiagnostics() Dim mA = comp3.Assembly.Modules(1) Assert.Equal("VB$AnonymousType_0<A>`2", mA.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousType")).Single().MetadataName) Assert.Equal("VB$AnonymousDelegate_0<A>`1", mA.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousDelegate")).Single().MetadataName) Dim mB = comp3.Assembly.Modules(2) Assert.Equal("VB$AnonymousType_0<B>`2", mB.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousType")).Single().MetadataName) Assert.Equal("VB$AnonymousDelegate_0<B>`1", mB.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousDelegate")).Single().MetadataName) CompileAndVerify(comp3, expectedOutput:="Hello, world!", symbolValidator:= Sub(m) Dim mC = DirectCast(m, PEModuleSymbol) Assert.Equal("VB$AnonymousType_0`2", mC.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousType")).Single().MetadataName) Assert.Equal("VB$AnonymousDelegate_0`1", mC.GlobalNamespace.GetTypeMembers().Where(Function(t) t.Name.StartsWith("VB$AnonymousDelegate")).Single().MetadataName) End Sub) End Sub End Class End Namespace
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Implementation/Commanding/LegacyCommandHandlerServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.Commanding { [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] [Export(typeof(ICommandHandlerServiceFactory))] internal sealed class LegacyCommandHandlerServiceFactory : ICommandHandlerServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LegacyCommandHandlerServiceFactory() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.Commanding { [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] [Export(typeof(ICommandHandlerServiceFactory))] internal sealed class LegacyCommandHandlerServiceFactory : ICommandHandlerServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LegacyCommandHandlerServiceFactory() { } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/Recommendations/Statements/LoopKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements Public Class LoopKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotInMethodBodyTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotInLambdaTest() VerifyRecommendationsMissing(<MethodBody> Dim x = Sub() | End Sub</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotAfterStatementTest() VerifyRecommendationsMissing(<MethodBody> Dim x |</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopAfterDoStatementTest() VerifyRecommendationsContain(<MethodBody> Do |</MethodBody>, "Loop", "Loop Until", "Loop While") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopAfterDoUntilStatementTest() VerifyRecommendationsContain(<MethodBody> Do Until True |</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopUntilNotAfterDoUntilStatementTest() VerifyRecommendationsMissing(<MethodBody> Do Until True |</MethodBody>, "Loop Until", "Loop While") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotInDoLoopUntilBlockTest() VerifyRecommendationsMissing(<MethodBody> Do | Loop Until True</MethodBody>, "Loop") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements Public Class LoopKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotInMethodBodyTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotInLambdaTest() VerifyRecommendationsMissing(<MethodBody> Dim x = Sub() | End Sub</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotAfterStatementTest() VerifyRecommendationsMissing(<MethodBody> Dim x |</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopAfterDoStatementTest() VerifyRecommendationsContain(<MethodBody> Do |</MethodBody>, "Loop", "Loop Until", "Loop While") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopAfterDoUntilStatementTest() VerifyRecommendationsContain(<MethodBody> Do Until True |</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopUntilNotAfterDoUntilStatementTest() VerifyRecommendationsMissing(<MethodBody> Do Until True |</MethodBody>, "Loop Until", "Loop While") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotInDoLoopUntilBlockTest() VerifyRecommendationsMissing(<MethodBody> Do | Loop Until True</MethodBody>, "Loop") End Sub End Class End Namespace
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Represents an analyzer assembly reference that contains diagnostic analyzers. /// </summary> /// <remarks> /// Represents a logical location of the analyzer reference, not the content of the reference. /// The content might change in time. A snapshot is taken when the compiler queries the reference for its analyzers. /// </remarks> public abstract class AnalyzerReference { protected AnalyzerReference() { } /// <summary> /// Full path describing the location of the analyzer reference, or null if the reference has no location. /// </summary> public abstract string? FullPath { get; } /// <summary> /// Path or name used in error messages to identity the reference. /// </summary> /// <remarks> /// Should not be null. /// </remarks> public virtual string Display { get { return string.Empty; } } /// <summary> /// A unique identifier for this analyzer reference. /// </summary> /// <remarks> /// Should not be null. /// Note that this and <see cref="FullPath"/> serve different purposes. An analyzer reference may not /// have a path, but it always has an ID. Further, two analyzer references with different paths may /// represent two copies of the same analyzer, in which case the IDs should also be the same. /// </remarks> public abstract object Id { get; } /// <summary> /// Gets all the diagnostic analyzers defined in this assembly reference, irrespective of the language supported by the analyzer. /// Use this method only if you need all the analyzers defined in the assembly, without a language context. /// In most instances, either the analyzer reference is associated with a project or is being queried for analyzers in a particular language context. /// If so, use <see cref="GetAnalyzers(string)"/> method. /// </summary> public abstract ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages(); /// <summary> /// Gets all the diagnostic analyzers defined in this assembly reference for the given <paramref name="language"/>. /// </summary> /// <param name="language">Language name.</param> public abstract ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language); /// <summary> /// Gets all the source generators defined in this assembly reference. /// </summary> public virtual ImmutableArray<ISourceGenerator> GetGeneratorsForAllLanguages() => ImmutableArray<ISourceGenerator>.Empty; [Obsolete("Use GetGenerators(string language) or GetGeneratorsForAllLanguages()")] public virtual ImmutableArray<ISourceGenerator> GetGenerators() => ImmutableArray<ISourceGenerator>.Empty; /// <summary> /// Gets all the generators defined in this assembly reference for the given <paramref name="language"/>. /// </summary> /// <param name="language">Language name.</param> public virtual ImmutableArray<ISourceGenerator> GetGenerators(string language) => ImmutableArray<ISourceGenerator>.Empty; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Represents an analyzer assembly reference that contains diagnostic analyzers. /// </summary> /// <remarks> /// Represents a logical location of the analyzer reference, not the content of the reference. /// The content might change in time. A snapshot is taken when the compiler queries the reference for its analyzers. /// </remarks> public abstract class AnalyzerReference { protected AnalyzerReference() { } /// <summary> /// Full path describing the location of the analyzer reference, or null if the reference has no location. /// </summary> public abstract string? FullPath { get; } /// <summary> /// Path or name used in error messages to identity the reference. /// </summary> /// <remarks> /// Should not be null. /// </remarks> public virtual string Display { get { return string.Empty; } } /// <summary> /// A unique identifier for this analyzer reference. /// </summary> /// <remarks> /// Should not be null. /// Note that this and <see cref="FullPath"/> serve different purposes. An analyzer reference may not /// have a path, but it always has an ID. Further, two analyzer references with different paths may /// represent two copies of the same analyzer, in which case the IDs should also be the same. /// </remarks> public abstract object Id { get; } /// <summary> /// Gets all the diagnostic analyzers defined in this assembly reference, irrespective of the language supported by the analyzer. /// Use this method only if you need all the analyzers defined in the assembly, without a language context. /// In most instances, either the analyzer reference is associated with a project or is being queried for analyzers in a particular language context. /// If so, use <see cref="GetAnalyzers(string)"/> method. /// </summary> public abstract ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages(); /// <summary> /// Gets all the diagnostic analyzers defined in this assembly reference for the given <paramref name="language"/>. /// </summary> /// <param name="language">Language name.</param> public abstract ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language); /// <summary> /// Gets all the source generators defined in this assembly reference. /// </summary> public virtual ImmutableArray<ISourceGenerator> GetGeneratorsForAllLanguages() => ImmutableArray<ISourceGenerator>.Empty; [Obsolete("Use GetGenerators(string language) or GetGeneratorsForAllLanguages()")] public virtual ImmutableArray<ISourceGenerator> GetGenerators() => ImmutableArray<ISourceGenerator>.Empty; /// <summary> /// Gets all the generators defined in this assembly reference for the given <paramref name="language"/>. /// </summary> /// <param name="language">Language name.</param> public virtual ImmutableArray<ISourceGenerator> GetGenerators(string language) => ImmutableArray<ISourceGenerator>.Empty; } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Test/SolutionExplorer/AnalyzersFolderItemTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.SolutionExplorer <[UseExportProvider]> Public Class AnalyzersFolderItemTests <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub Name() Dim workspaceXml = <Workspace> <Project Language="C#" CommonReferences="true"> <Analyzer Name="Goo" FullPath="C:\Users\Bill\Documents\Analyzers\Goo.dll"/> </Project> </Workspace> Using workspace = TestWorkspace.Create(workspaceXml) Dim project = workspace.Projects.Single() Dim analyzerFolder = New AnalyzersFolderItem(workspace, project.Id, Nothing, Nothing) Assert.Equal(expected:=SolutionExplorerShim.Analyzers, actual:=analyzerFolder.Text) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub BrowseObject1() Dim workspaceXml = <Workspace> <Project Language="C#" CommonReferences="true"> <Analyzer Name="Goo" FullPath="C:\Users\Bill\Documents\Analyzers\Goo.dll"/> </Project> </Workspace> Using workspace = TestWorkspace.Create(workspaceXml) Dim project = workspace.Projects.Single() Dim analyzerFolder = New AnalyzersFolderItem(workspace, project.Id, Nothing, Nothing) Dim browseObject = DirectCast(analyzerFolder.GetBrowseObject(), AnalyzersFolderItem.BrowseObject) Assert.Equal(expected:=SolutionExplorerShim.Analyzers, actual:=browseObject.GetComponentName()) Assert.Equal(expected:=SolutionExplorerShim.Folder_Properties, actual:=browseObject.GetClassName()) End Using End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.SolutionExplorer <[UseExportProvider]> Public Class AnalyzersFolderItemTests <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub Name() Dim workspaceXml = <Workspace> <Project Language="C#" CommonReferences="true"> <Analyzer Name="Goo" FullPath="C:\Users\Bill\Documents\Analyzers\Goo.dll"/> </Project> </Workspace> Using workspace = TestWorkspace.Create(workspaceXml) Dim project = workspace.Projects.Single() Dim analyzerFolder = New AnalyzersFolderItem(workspace, project.Id, Nothing, Nothing) Assert.Equal(expected:=SolutionExplorerShim.Analyzers, actual:=analyzerFolder.Text) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub BrowseObject1() Dim workspaceXml = <Workspace> <Project Language="C#" CommonReferences="true"> <Analyzer Name="Goo" FullPath="C:\Users\Bill\Documents\Analyzers\Goo.dll"/> </Project> </Workspace> Using workspace = TestWorkspace.Create(workspaceXml) Dim project = workspace.Projects.Single() Dim analyzerFolder = New AnalyzersFolderItem(workspace, project.Id, Nothing, Nothing) Dim browseObject = DirectCast(analyzerFolder.GetBrowseObject(), AnalyzersFolderItem.BrowseObject) Assert.Equal(expected:=SolutionExplorerShim.Analyzers, actual:=browseObject.GetComponentName()) Assert.Equal(expected:=SolutionExplorerShim.Folder_Properties, actual:=browseObject.GetClassName()) End Using End Sub End Class End Namespace
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Semantic/FlowAnalysis/FlowDiagnosticTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class FlowDiagnosticTests : FlowTestBase { [Fact] public void TestBug12350() { // We suppress the "local variable is only written" warning if the // variable is assigned a non-constant value. string program = @" class Program { static int X() { return 1; } static void M() { int i1 = 123; // 0219 int i2 = X(); // no warning int? i3 = 123; // 0219 int? i4 = null; // 0219 int? i5 = X(); // no warning int i6 = default(int); // 0219 int? i7 = default(int?); // 0219 int? i8 = new int?(); // 0219 int i9 = new int(); // 0219 } }"; CreateCompilation(program).VerifyDiagnostics( // (7,13): warning CS0219: The variable 'i1' is assigned but its value is never used // int i1 = 123; // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i1").WithArguments("i1"), // (9,14): warning CS0219: The variable 'i3' is assigned but its value is never used // int? i3 = 123; // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i3").WithArguments("i3"), // (10,14): warning CS0219: The variable 'i4' is assigned but its value is never used // int? i4 = null; // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i4").WithArguments("i4"), // (12,13): warning CS0219: The variable 'i6' is assigned but its value is never used // int i6 = default(int); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i6").WithArguments("i6"), // (13,14): warning CS0219: The variable 'i7' is assigned but its value is never used // int? i7 = default(int?); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i7").WithArguments("i7"), // (14,14): warning CS0219: The variable 'i8' is assigned but its value is never used // int? i8 = new int?(); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i8").WithArguments("i8"), // (15,13): warning CS0219: The variable 'i9' is assigned but its value is never used // int i9 = new int(); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i9").WithArguments("i9")); } [Fact] public void Test1() { string program = @" namespace ConsoleApplication1 { class Program { public static void F(int z) { int x; if (z == 2) { int y = x; x = y; // use of unassigned local variable 'x' } else { int y = x; x = y; // diagnostic suppressed here } } } }"; CreateCompilation(program).VerifyDiagnostics( // (11,25): error CS0165: Use of unassigned local variable 'x' // int y = x; x = y; // use of unassigned local variable 'x' Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x") ); } [Fact] public void Test2() { //x is "assigned when true" after "false" //Therefore x is "assigned" before "z == 1" (5.3.3.24) //Therefore x is "assigned" after "z == 1" (5.3.3.20) //Therefore x is "assigned when true" after "(false && z == 1)" (5.3.3.24) //Since the condition of the ?: expression is the constant true, the state of x after the ?: expression is the same as the state of x after the consequence (5.3.3.28) //Since the state of x after the consequence is "assigned when true", the state of x after the ?: expression is "assigned when true" (5.3.3.28) //Since the state of x after the if's condition is "assigned when true", x is assigned in the then block (5.3.3.5) //Therefore, there should be no error. string program = @" namespace ConsoleApplication1 { class Program { void F(int z) { int x; if (true ? (false && z == 1) : true) x = x + 1; // Dev10 complains x not assigned. } } }"; var comp = CreateCompilation(program); var errs = this.FlowDiagnostics(comp); Assert.Equal(0, errs.Count()); } [Fact] public void Test3() { string program = @" class Program { int F(int z) { } }"; var comp = CreateCompilation(program); var errs = this.FlowDiagnostics(comp); Assert.Equal(1, errs.Count()); } [Fact] public void Test4() { // v is definitely assigned at the beginning of any unreachable statement. string program = @" class Program { void F() { if (false) { int x; // warning: unreachable code x = x + 1; // no error: x assigned when unreachable } } }"; var comp = CreateCompilation(program); int[] count = new int[4]; foreach (var e in this.FlowDiagnostics(comp)) count[(int)e.Severity]++; Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(1, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); } [Fact] public void Test5() { // v is definitely assigned at the beginning of any unreachable statement. string program = @" class A { static void F() { goto L2; goto L1; // unreachable code detected int x; L1: ; // Roslyn: extrs warning CS0162 -unreachable code x = x + 1; // no definite assignment problem in unreachable code L2: ; } } "; var comp = CreateCompilation(program); int[] count = new int[4]; foreach (var e in this.FlowDiagnostics(comp)) count[(int)e.Severity]++; Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(2, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); } [WorkItem(537918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537918")] [Fact] public void AssertForInvalidBreak() { // v is definitely assigned at the beginning of any unreachable statement. string program = @" public class Test { public static int Main() { int ret = 1; break; // Assert here return (ret); } } "; var comp = CreateCompilation(program); comp.GetMethodBodyDiagnostics().Verify( // (7,9): error CS0139: No enclosing loop out of which to break or continue // break; // Assert here Diagnostic(ErrorCode.ERR_NoBreakOrCont, "break;")); } [WorkItem(538064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538064")] [Fact] public void IfFalse() { string program = @" using System; class Program { static void Main() { if (false) { } } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538067")] [Fact] public void WhileConstEqualsConst() { string program = @" using System; class Program { bool goo() { const bool b = true; while (b == b) { return b; } } static void Main() { } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538175")] [Fact] public void BreakWithoutTarget() { string program = @"public class Test { public static void Main() { if (true) break; } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [Fact] public void OutCausesAssignment() { string program = @"class Program { void F(out int x) { G(out x); } void G(out int x) { x = 1; } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [Fact] public void OutNotAssigned01() { string program = @"class Program { bool b; void F(out int x) { if (b) return; } }"; var comp = CreateCompilation(program); Assert.Equal(2, this.FlowDiagnostics(comp).Count()); } [WorkItem(539374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539374")] [Fact] public void OutAssignedAfterCall01() { string program = @"class Program { void F(out int x, int y) { x = y; } void G() { int x; F(out x, x); } }"; var comp = CreateCompilation(program); Assert.Equal(1, this.FlowDiagnostics(comp).Count()); } [WorkItem(538067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538067")] [Fact] public void WhileConstEqualsConst2() { string program = @" using System; class Program { bool goo() { const bool b = true; while (b == b) { return b; } return b; // Should detect this line as unreachable code. } static void Main() { } }"; var comp = CreateCompilation(program); int[] count = new int[4]; foreach (var e in this.FlowDiagnostics(comp)) count[(int)e.Severity]++; Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(1, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); } [WorkItem(538072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538072")] [Fact] public void UnusedLocal() { string program = @" using System; class Program { int x; int y; int z; static void Main() { int a; const bool b = true; } void goo() { y = 2; Console.WriteLine(z); } }"; var comp = CreateCompilation(program); int[] count = new int[4]; Dictionary<int, int> warnings = new Dictionary<int, int>(); foreach (var e in this.FlowDiagnostics(comp)) { count[(int)e.Severity]++; if (!warnings.ContainsKey(e.Code)) warnings[e.Code] = 0; warnings[e.Code] += 1; } Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); // See bug 3562 - field level flow analysis warnings CS0169, CS0414 and CS0649 are out of scope for M2. // TODO: Fix this test once CS0169, CS0414 and CS0649 are implemented. // Assert.Equal(5, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(2, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(1, warnings[168]); Assert.Equal(1, warnings[219]); // See bug 3562 - field level flow analysis warnings CS0169, CS0414 and CS0649 are out of scope for M2. // TODO: Fix this test once CS0169, CS0414 and CS0649 are implemented. // Assert.Equal(1, warnings[169]); // Assert.Equal(1, warnings[414]); // Assert.Equal(1, warnings[649]); } [WorkItem(538384, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538384")] [Fact] public void UnusedLocalConstants() { string program = @" using System; class Program { static void Main() { const string CONST1 = ""hello""; // Should not report CS0219 Console.WriteLine(CONST1 != ""hello""); int i = 1; const long CONST2 = 1; const uint CONST3 = 1; // Should not report CS0219 while (CONST2 < CONST3 - i) { if (CONST3 < CONST3 - i) continue; } } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538385")] [Fact] public void UnusedLocalReferenceTypedVariables() { string program = @" using System; class Program { static void Main() { object o = 1; // Should not report CS0219 Test c = new Test(); // Should not report CS0219 c = new Program(); string s = string.Empty; // Should not report CS0219 s = null; } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538386")] [Fact] public void UnusedLocalValueTypedVariables() { string program = @" using System; class Program { static void Main() { } public void Repro2(params int[] x) { int i = x[0]; // Should not report CS0219 byte b1 = 1; byte b11 = b1; // Should not report CS0219 } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [Fact] public void RefParameter01() { string program = @" class Program { public static void Main(string[] args) { int i; F(ref i); // use of unassigned local variable 'i' } static void F(ref int i) { } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void OutParameter01() { string program = @" class Program { public static void Main(string[] args) { int i; F(out i); int j = i; } static void F(out int i) { i = 1; } }"; var comp = CreateCompilation(program); Assert.Empty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void Goto01() { string program = @" using System; class Program { public void M(bool b) { if (b) goto label; int i; i = 3; i = i + 1; label: int j = i; // i not definitely assigned } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void LambdaParameters() { string program = @" using System; class Program { delegate void Func(ref int i, int r); static void Main(string[] args) { Func fnc = (ref int arg, int arg2) => { arg = arg; }; } }"; var comp = CreateCompilation(program); Assert.Empty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void LambdaMightNotBeInvoked() { string program = @" class Program { delegate void Func(); static void Main(string[] args) { int i; Func query = () => { i = 12; }; int j = i; } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void LambdaMustAssignOutParameters() { string program = @" class Program { delegate void Func(out int x); static void Main(string[] args) { Func query = (out int x) => { }; } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact, WorkItem(528052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528052")] public void InnerVariablesAreNotDefinitelyAssignedInBeginningOfLambdaBody() { string program = @" using System; class Program { static void Main() { return; Action f = () => { int y = y; }; } }"; CreateCompilation(program).VerifyDiagnostics( // (9,9): warning CS0162: Unreachable code detected // Action f = () => { int y = y; }; Diagnostic(ErrorCode.WRN_UnreachableCode, "Action"), // (9,36): error CS0165: Use of unassigned local variable 'y' // Action f = () => { int y = y; }; Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y") ); } [WorkItem(540139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540139")] [Fact] public void DelegateCreationReceiverIsRead() { string program = @" using System; class Program { static void Main() { Action a; Func<string> b = new Func<string>(a.ToString); } } "; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [WorkItem(540405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540405")] [Fact] public void ErrorInFieldInitializerLambda() { string program = @" using System; class Program { static Func<string> x = () => { string s; return s; }; static void Main() { } } "; CreateCompilation(program).VerifyDiagnostics( // (6,54): error CS0165: Use of unassigned local variable 's' // static Func<string> x = () => { string s; return s; }; Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s") ); } [WorkItem(541389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541389")] [Fact] public void IterationWithEmptyBody() { string program = @" public class A { public static void Main(string[] args) { for (int i = 0; i < 10; i++) ; foreach (var v in args); int len = args.Length; while (len-- > 0); } }"; CreateCompilation(program).VerifyDiagnostics(); } [WorkItem(541389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541389")] [Fact] public void SelectionWithEmptyBody() { string program = @" public class A { public static void Main(string[] args) { int len = args.Length; if (len++ < 9) ; else ; } }"; CreateCompilation(program).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";"), Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";")); } [WorkItem(542146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542146")] [Fact] public void FieldlikeEvent() { string program = @"public delegate void D(); public struct S { public event D Ev; public S(D d) { Ev = null; Ev += d; } }"; CreateCompilation(program).VerifyDiagnostics( // (4,20): warning CS0414: The field 'S.Ev' is assigned but its value is never used // public event D Ev; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "Ev").WithArguments("S.Ev")); } [WorkItem(542187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542187")] [Fact] public void GotoFromTry() { string program = @"class Test { static void F(int x) { } static void Main() { int a; try { a = 1; goto L1; } finally { } L1: F(a); } }"; CreateCompilation(program).VerifyDiagnostics(); } [WorkItem(542154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542154")] [Fact] public void UnreachableThrow() { string program = @"public class C { static void Main() { return; throw Goo(); } static System.Exception Goo() { System.Console.WriteLine(""Hello""); return null; } } "; CreateCompilation(program).VerifyDiagnostics(); } [WorkItem(542585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542585")] [Fact] public void Bug9870() { string program = @" struct S<T> { T x; static void Goo() { x.x = 1; } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'S<T>.x' // x.x = 1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x").WithArguments("S<T>.x") ); } [WorkItem(542597, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542597")] [Fact] public void LambdaEntryPointIsReachable() { string program = @"class Program { static void Main(string[] args) { int i; return; System.Action a = () => { int j = i + j; }; } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // unreachable statement // (7,23): warning CS0162: Unreachable code detected // System.Action a = () => Diagnostic(ErrorCode.WRN_UnreachableCode, "System"), // (9,25): error CS0165: Use of unassigned local variable 'j' // int j = i + j; Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j") ); } [WorkItem(542597, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542597")] [Fact] public void LambdaInUnimplementedPartial() { string program = @"using System; partial class C { static partial void Goo(Action a); static void Main() { Goo(() => { int x, y = x; }); } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (9,32): error CS0165: Use of unassigned local variable 'x' // Goo(() => { int x, y = x; }); Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x") ); } [WorkItem(541887, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541887")] [Fact] public void CascadedDiagnostics01() { string program = @" class Program { static void Main(string[] args) { var s = goo<,int>(123); } public static int goo<T>(int i) { return 1; } }"; var comp = CreateCompilation(program); var parseErrors = comp.SyntaxTrees[0].GetDiagnostics(); var errors = comp.GetDiagnostics(); Assert.Equal(parseErrors.Count(), errors.Count()); } [Fact] public void UnassignedInInitializer() { string program = @"class C { System.Action a = () => { int i; int j = i; }; }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (3,46): error CS0165: Use of unassigned local variable 'i' // System.Action a = () => { int i; int j = i; }; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i") ); } [WorkItem(543343, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543343")] [Fact] public void ConstInSwitch() { string program = @"class Program { static void Main(string[] args) { switch (args.Length) { case 0: const int N = 3; break; case 1: int M = N; break; } } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (11,21): warning CS0219: The variable 'M' is assigned but its value is never used // int M = N; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "M").WithArguments("M") ); } #region "Struct" [Fact] public void CycleWithInitialization() { string program = @" public struct A { A a = new A(); // CS8036 public static void Main() { A a = new A(); } } "; CreateCompilation(program).VerifyDiagnostics( // (4,7): error CS0573: 'A': cannot have instance property or field initializers in structs // A a = new A(); // CS8036 Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "a").WithArguments("A").WithLocation(4, 7), // (4,7): error CS0523: Struct member 'A.a' of type 'A' causes a cycle in the struct layout // A a = new A(); // CS8036 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "a").WithArguments("A.a", "A").WithLocation(4, 7), // (7,11): warning CS0219: The variable 'a' is assigned but its value is never used // A a = new A(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(7, 11), // (4,7): warning CS0169: The field 'A.a' is never used // A a = new A(); // CS8036 Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("A.a").WithLocation(4, 7) ); } [WorkItem(542356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542356")] [Fact] public void StaticMemberExplosion() { string program = @" struct A<T> { static A<A<T>> x; } struct B<T> { static A<B<T>> x; } struct C<T> { static D<T> x; } struct D<T> { static C<D<T>> x; } "; CreateCompilation(program) .VerifyDiagnostics( // (14,17): error CS0523: Struct member 'C<T>.x' of type 'D<T>' causes a cycle in the struct layout // static D<T> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("C<T>.x", "D<T>").WithLocation(14, 17), // (18,20): error CS0523: Struct member 'D<T>.x' of type 'C<D<T>>' causes a cycle in the struct layout // static C<D<T>> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("D<T>.x", "C<D<T>>").WithLocation(18, 20), // (4,20): error CS0523: Struct member 'A<T>.x' of type 'A<A<T>>' causes a cycle in the struct layout // static A<A<T>> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("A<T>.x", "A<A<T>>").WithLocation(4, 20), // (9,20): warning CS0169: The field 'B<T>.x' is never used // static A<B<T>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("B<T>.x").WithLocation(9, 20), // (4,20): warning CS0169: The field 'A<T>.x' is never used // static A<A<T>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("A<T>.x").WithLocation(4, 20), // (18,20): warning CS0169: The field 'D<T>.x' is never used // static C<D<T>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("D<T>.x").WithLocation(18, 20), // (14,17): warning CS0169: The field 'C<T>.x' is never used // static D<T> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("C<T>.x").WithLocation(14, 17) ); } [Fact] public void StaticSequential() { string program = @" partial struct S { public static int x; } partial struct S { public static int y; }"; CreateCompilation(program) .VerifyDiagnostics( // (4,23): warning CS0649: Field 'S.x' is never assigned to, and will always have its default value 0 // public static int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("S.x", "0"), // (9,23): warning CS0649: Field 'S.y' is never assigned to, and will always have its default value 0 // public static int y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("S.y", "0") ); } [WorkItem(542567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542567")] [Fact] public void ImplicitFieldSequential() { string program = @"partial struct S1 { public int x; } partial struct S1 { public int y { get; set; } } partial struct S2 { public int x; } delegate void D(); partial struct S2 { public event D y; }"; CreateCompilation(program) .VerifyDiagnostics( // (1,16): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'S1'. To specify an ordering, all instance fields must be in the same declaration. // partial struct S1 Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "S1").WithArguments("S1"), // (11,16): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'S2'. To specify an ordering, all instance fields must be in the same declaration. // partial struct S2 Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "S2").WithArguments("S2"), // (3,16): warning CS0649: Field 'S1.x' is never assigned to, and will always have its default value 0 // public int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("S1.x", "0"), // (13,16): warning CS0649: Field 'S2.x' is never assigned to, and will always have its default value 0 // public int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("S2.x", "0"), // (19,20): warning CS0067: The event 'S2.y' is never used // public event D y; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "y").WithArguments("S2.y") ); } [Fact] public void StaticInitializer() { string program = @" public struct A { static System.Func<int> d = () => { int j; return j * 9000; }; public static void Main() { } } "; CreateCompilation(program) .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j") ); } [Fact] public void AllPiecesAssigned() { string program = @" struct S { public int x, y; } class Program { public static void Main(string[] args) { S s; s.x = args.Length; s.y = args.Length; S t = s; } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void OnePieceMissing() { string program = @" struct S { public int x, y; } class Program { public static void Main(string[] args) { S s; s.x = args.Length; S t = s; } } "; CreateCompilation(program) .VerifyDiagnostics( // (12,15): error CS0165: Use of unassigned local variable 's' // S t = s; Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s"), // (4,19): warning CS0649: Field 'S.y' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("S.y", "0") ); } [Fact] public void OnePieceOnOnePath() { string program = @" struct S { public int x, y; } class Program { public void F(S s) { S s2; if (s.x == 3) s2 = s; else s2.x = s.x; int x = s2.x; } } "; CreateCompilation(program) .VerifyDiagnostics( // (4,19): warning CS0649: Field 'S.y' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("S.y", "0") ); } [Fact] public void DefaultConstructor() { string program = @" struct S { public int x, y; } class Program { public static void Main(string[] args) { S s = new S(); s.x = s.y = s.x; } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void FieldAssignedInConstructor() { string program = @" struct S { int x, y; S(int x, int y) { this.x = x; this.y = y; } }"; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void FieldUnassignedInConstructor() { string program = @" struct S { int x, y; S(int x) { this.x = x; } }"; CreateCompilation(program) .VerifyDiagnostics( // (5,5): error CS0171: Field 'S.y' must be fully assigned before control is returned to the caller // S(int x) { this.x = x; } Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("S.y"), // (4,12): warning CS0169: The field 'S.y' is never used // int x, y; Diagnostic(ErrorCode.WRN_UnreferencedField, "y").WithArguments("S.y") ); } [WorkItem(543429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543429")] [Fact] public void ConstructorCannotComplete() { string program = @"using System; public struct S { int value; public S(int value) { throw new NotImplementedException(); } }"; CreateCompilation(program).VerifyDiagnostics( // (4,9): warning CS0169: The field 'S.value' is never used // int value; Diagnostic(ErrorCode.WRN_UnreferencedField, "value").WithArguments("S.value") ); } [Fact] public void AutoPropInitialization1() { string program = @" struct Program { public int X { get; private set; } public Program(int x) { } public static void Main(string[] args) { } }"; CreateCompilation(program) .VerifyDiagnostics( // (5,12): error CS0843: Backing field for automatically implemented property 'Program.X' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer. Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.X")); } [Fact] public void AutoPropInitialization2() { var text = @"struct S { public int P { get; set; } = 1; internal static long Q { get; } = 10; public decimal R { get; } = 300; public S(int i) {} }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,16): error CS0573: 'S': cannot have instance property or field initializers in structs // public int P { get; set; } = 1; Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "P").WithArguments("S").WithLocation(3, 16), // (5,20): error CS0573: 'S': cannot have instance property or field initializers in structs // public decimal R { get; } = 300; Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "R").WithArguments("S").WithLocation(5, 20) ); } [Fact] public void AutoPropInitialization3() { var text = @"struct S { public int P { get; private set; } internal static long Q { get; } = 10; public decimal R { get; } = 300; public S(int p) { P = p; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,20): error CS0573: 'S': cannot have instance property or field initializers in structs // public decimal R { get; } = 300; Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "R").WithArguments("S").WithLocation(5, 20) ); } [Fact] public void AutoPropInitialization4() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; } S1 x2 { get; } public Program(int dummy) { x.i = 1; System.Console.WriteLine(x2.ii); } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (16,9): error CS1612: Cannot modify the return value of 'Program.x' because it is not a variable // x.i = 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x").WithArguments("Program.x").WithLocation(16, 9), // (16,9): error CS0170: Use of possibly unassigned field 'i' // x.i = 1; Diagnostic(ErrorCode.ERR_UseDefViolationField, "x.i").WithArguments("i").WithLocation(16, 9), // (17,34): error CS8079: Use of possibly unassigned auto-implemented property 'x2' // System.Console.WriteLine(x2.ii); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x2").WithArguments("x2").WithLocation(17, 34), // (14,12): error CS0843: Auto-implemented property 'Program.x' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x").WithLocation(14, 12), // (14,12): error CS0843: Auto-implemented property 'Program.x2' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x2").WithLocation(14, 12)); } [Fact] public void AutoPropInitialization5() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get; set;} public Program(int dummy) { x.i = 1; System.Console.WriteLine(x2.ii); } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (16,9): error CS1612: Cannot modify the return value of 'Program.x' because it is not a variable // x.i = 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x").WithArguments("Program.x").WithLocation(16, 9), // (16,9): error CS0170: Use of possibly unassigned field 'i' // x.i = 1; Diagnostic(ErrorCode.ERR_UseDefViolationField, "x.i").WithArguments("i").WithLocation(16, 9), // (17,34): error CS8079: Use of possibly unassigned auto-implemented property 'x2' // System.Console.WriteLine(x2.ii); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x2").WithArguments("x2").WithLocation(17, 34), // (14,12): error CS0843: Auto-implemented property 'Program.x' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x").WithLocation(14, 12), // (14,12): error CS0843: Auto-implemented property 'Program.x2' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x2").WithLocation(14, 12)); } [Fact] public void AutoPropInitialization6() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program(int dummy) { x = new S1(); x.i += 1; x2 = new S1(); x2.i += 1; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (17,9): error CS1612: Cannot modify the return value of 'Program.x' because it is not a variable // x.i += 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x").WithArguments("Program.x").WithLocation(17, 9), // (20,9): error CS1612: Cannot modify the return value of 'Program.x2' because it is not a variable // x2.i += 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x2").WithArguments("Program.x2").WithLocation(20, 9) ); } [Fact] public void AutoPropInitialization7() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program(int dummy) { this = default(Program); System.Action a = () => { this.x = new S1(); }; System.Action a2 = () => { this.x2 = new S1(); }; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (20,13): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // this.x = new S1(); Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(20, 13), // (25,13): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // this.x2 = new S1(); Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(25, 13), // (6,20): warning CS0649: Field 'Program.S1.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("Program.S1.i", "0").WithLocation(6, 20) ); } [Fact] public void AutoPropInitialization7c() { var text = @" class Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program() { System.Action a = () => { this.x = new S1(); }; System.Action a2 = () => { this.x2 = new S1(); }; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (23,13): error CS0200: Property or indexer 'Program.x2' cannot be assigned to -- it is read only // this.x2 = new S1(); Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this.x2").WithArguments("Program.x2").WithLocation(23, 13), // (6,20): warning CS0649: Field 'Program.S1.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("Program.S1.i", "0").WithLocation(6, 20) ); } [Fact] public void AutoPropInitialization8() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program(int arg) : this() { x2 = x; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,20): warning CS0649: Field 'Program.S1.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("Program.S1.i", "0").WithLocation(6, 20) ); } [Fact] public void AutoPropInitialization9() { var text = @" struct Program { struct S1 { } S1 x { get; set;} S1 x2 { get;} public Program(int arg) { x2 = x; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); // no errors since S1 is empty comp.VerifyDiagnostics( ); } [Fact] public void AutoPropInitialization10() { var text = @" struct Program { public struct S1 { public int x; } S1 x1 { get; set;} S1 x2 { get;} S1 x3; public Program(int arg) { Goo(out x1); Goo(ref x1); Goo(out x2); Goo(ref x2); Goo(out x3); Goo(ref x3); } public static void Goo(out S1 s) { s = default(S1); } public static void Goo1(ref S1 s) { s = default(S1); } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); // no errors since S1 is empty comp.VerifyDiagnostics( // (15,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(out x1); Diagnostic(ErrorCode.ERR_RefProperty, "x1").WithArguments("Program.x1").WithLocation(15, 17), // (16,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(ref x1); Diagnostic(ErrorCode.ERR_RefProperty, "x1").WithArguments("Program.x1").WithLocation(16, 17), // (17,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(out x2); Diagnostic(ErrorCode.ERR_RefProperty, "x2").WithArguments("Program.x2").WithLocation(17, 17), // (18,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(ref x2); Diagnostic(ErrorCode.ERR_RefProperty, "x2").WithArguments("Program.x2").WithLocation(18, 17), // (20,17): error CS1620: Argument 1 must be passed with the 'out' keyword // Goo(ref x3); Diagnostic(ErrorCode.ERR_BadArgRef, "x3").WithArguments("1", "out").WithLocation(20, 17), // (15,17): error CS8079: Use of automatically implemented property 'x1' whose backing field is possibly unassigned // Goo(out x1); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x1").WithArguments("x1").WithLocation(15, 17), // (16,9): error CS0188: The 'this' object cannot be used before all of its fields are assigned to // Goo(ref x1); Diagnostic(ErrorCode.ERR_UseDefViolationThis, "Goo").WithArguments("this").WithLocation(16, 9), // (17,17): error CS8079: Use of automatically implemented property 'x2' whose backing field is possibly unassigned // Goo(out x2); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x2").WithArguments("x2").WithLocation(17, 17), // (6,20): warning CS0649: Field 'Program.S1.x' is never assigned to, and will always have its default value 0 // public int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("Program.S1.x", "0").WithLocation(6, 20) ); } [Fact] public void EmptyStructAlwaysAssigned() { string program = @" struct S { static S M() { S s; return s; } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void DeeplyEmptyStructAlwaysAssigned() { string program = @" struct S { static S M() { S s; return s; } } struct T { S s1, s2, s3; static T M() { T t; return t; } }"; CreateCompilation(program) .VerifyDiagnostics( // (13,15): warning CS0169: The field 'T.s3' is never used // S s1, s2, s3; Diagnostic(ErrorCode.WRN_UnreferencedField, "s3").WithArguments("T.s3").WithLocation(13, 15), // (13,11): warning CS0169: The field 'T.s2' is never used // S s1, s2, s3; Diagnostic(ErrorCode.WRN_UnreferencedField, "s2").WithArguments("T.s2").WithLocation(13, 11), // (13,7): warning CS0169: The field 'T.s1' is never used // S s1, s2, s3; Diagnostic(ErrorCode.WRN_UnreferencedField, "s1").WithArguments("T.s1").WithLocation(13, 7) ); } [WorkItem(543466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543466")] [Fact] public void UnreferencedFieldWarningsMissingInEmit() { var comp = CreateCompilation(@" public class Class1 { int field1; }"); var bindingDiags = comp.GetDiagnostics().ToArray(); Assert.Equal(1, bindingDiags.Length); Assert.Equal(ErrorCode.WRN_UnreferencedField, (ErrorCode)bindingDiags[0].Code); var emitDiags = comp.Emit(new System.IO.MemoryStream()).Diagnostics.ToArray(); Assert.Equal(bindingDiags.Length, emitDiags.Length); Assert.Equal(bindingDiags[0], emitDiags[0]); } [Fact] public void DefiniteAssignGenericStruct() { string program = @" using System; struct C<T> { public int num; public int Goo1() { return this.num; } } class Test { static void Main(string[] args) { C<object> c; c.num = 1; bool verify = c.Goo1() == 1; Console.WriteLine(verify); } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [WorkItem(540896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540896")] [WorkItem(541268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541268")] [Fact] public void ChainToStructDefaultConstructor() { string program = @" using System; namespace Roslyn.Compilers.CSharp { class DecimalRewriter { private DecimalRewriter() { } private struct DecimalParts { public DecimalParts(decimal value) : this() { int[] bits = Decimal.GetBits(value); Low = bits[0]; } public int Low { get; private set; } } } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [WorkItem(541298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541298")] [WorkItem(541298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541298")] [Fact] public void SetStaticPropertyOnStruct() { string source = @" struct S { public static int p { get; internal set; } } class C { public static void Main() { S.p = 10; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPart() { string program = @" struct S { public int x; } class Program { public static void Main(string[] args) { S s = new S(); s.x = 12; } }"; CreateCompilation(program).VerifyDiagnostics(); } [Fact] public void ReferencingCycledStructures() { string program = @" public struct A { public static void Main() { S1 s1 = new S1(); S2 s2 = new S2(); s2.fld = new S3(); s2.fld.fld.fld.fld = new S2(); } } "; var c = CreateCompilation(program, new[] { TestReferences.SymbolsTests.CycledStructs }); c.VerifyDiagnostics( // (6,12): warning CS0219: The variable 's1' is assigned but its value is never used // S1 s1 = new S1(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s1").WithArguments("s1")); } [Fact] public void BigStruct() { string source = @" struct S<T> { T a, b, c, d, e, f, g, h; S(T t) { a = b = c = d = e = f = g = h = t; } static void M() { S<S<S<S<S<S<S<S<int>>>>>>>> x; x.a.a.a.a.a.a.a.a = 12; x.a.a.a.a.a.a.a.b = x.a.a.a.a.a.a.a.a; } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(542901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542901")] public void DataFlowForStructFieldAssignment() { string program = @"struct S { public float X; public float Y; public float Z; void M() { if (3 < 3.4) { S s; if (s.X < 3) { s = GetS(); s.Z = 10f; } else { } } else { } } private static S GetS() { return new S(); } } "; CreateCompilation(program).VerifyDiagnostics( // (12,17): error CS0170: Use of possibly unassigned field 'X' // if (s.X < 3) Diagnostic(ErrorCode.ERR_UseDefViolationField, "s.X").WithArguments("X"), // (3,18): warning CS0649: Field 'S.X' is never assigned to, and will always have its default value 0 // public float X; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "X").WithArguments("S.X", "0"), // (4,18): warning CS0649: Field 'S.Y' is never assigned to, and will always have its default value 0 // public float Y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Y").WithArguments("S.Y", "0") ); } [Fact] [WorkItem(2470, "https://github.com/dotnet/roslyn/issues/2470")] public void NoFieldNeverAssignedWarning() { string program = @" using System.Threading.Tasks; internal struct TaskEvent<T> { private TaskCompletionSource<T> _tcs; public Task<T> Task { get { if (_tcs == null) _tcs = new TaskCompletionSource<T>(); return _tcs.Task; } } public void Invoke(T result) { if (_tcs != null) { TaskCompletionSource<T> localTcs = _tcs; _tcs = null; localTcs.SetResult(result); } } } public class OperationExecutor { private TaskEvent<float?> _nextValueEvent; // Field is never assigned warning // Start some async operation public Task<bool> StartOperation() { return null; } // Get progress or data during async operation public Task<float?> WaitNextValue() { return _nextValueEvent.Task; } // Called externally internal void OnNextValue(float? value) { _nextValueEvent.Invoke(value); } } "; CreateCompilationWithMscorlib45(program).VerifyEmitDiagnostics(); } #endregion [Fact, WorkItem(545347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545347")] public void FieldInAbstractClass_UnusedField() { var text = @" abstract class AbstractType { public int Kind; }"; CreateCompilation(text).VerifyDiagnostics( // (4,16): warning CS0649: Field 'AbstractType.Kind' is never assigned to, and will always have its default value 0 // public int Kind; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Kind").WithArguments("AbstractType.Kind", "0").WithLocation(4, 16)); } [Fact, WorkItem(545347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545347")] public void FieldInAbstractClass_FieldUsedInChildType() { var text = @" abstract class AbstractType { public int Kind; } class ChildType : AbstractType { public ChildType() { this.Kind = 1; } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] [WorkItem(545642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545642")] public void InitializerAndConstructorWithOutParameter() { string program = @"class Program { private int field = Goo(); static int Goo() { return 12; } public Program(out int x) { x = 13; } }"; CreateCompilation(program).VerifyDiagnostics(); } [Fact] [WorkItem(545875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545875")] public void TestSuppressUnreferencedVarAssgOnIntPtr() { var source = @" using System; public class Test { public static void Main() { IntPtr i1 = (IntPtr)0; IntPtr i2 = (IntPtr)10L; UIntPtr ui1 = (UIntPtr)0; UIntPtr ui2 = (UIntPtr)10L; IntPtr z = IntPtr.Zero; int ip1 = (int)z; long lp1 = (long)z; UIntPtr uz = UIntPtr.Zero; int ip2 = (int)uz; long lp2 = (long)uz; } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(546183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546183")] public void TestUnassignedStructFieldsInPInvokePassByRefCase() { var source = @" using System; using System.Runtime.InteropServices; namespace ManagedDebuggingAssistants { internal class DebugMonitor { internal DebugMonitor() { SECURITY_ATTRIBUTES attributes = new SECURITY_ATTRIBUTES(); SECURITY_DESCRIPTOR descriptor = new SECURITY_DESCRIPTOR(); IntPtr pDescriptor = IntPtr.Zero; IntPtr pAttributes = IntPtr.Zero; attributes.nLength = Marshal.SizeOf(attributes); attributes.bInheritHandle = true; attributes.lpSecurityDescriptor = pDescriptor; if (!InitializeSecurityDescriptor(ref descriptor, 1 /*SECURITY_DESCRIPTOR_REVISION*/)) throw new ApplicationException(""InitializeSecurityDescriptor failed: "" + Marshal.GetLastWin32Error()); if (!SetSecurityDescriptorDacl(ref descriptor, true, IntPtr.Zero, false)) throw new ApplicationException(""SetSecurityDescriptorDacl failed: "" + Marshal.GetLastWin32Error()); Marshal.StructureToPtr(descriptor, pDescriptor, false); Marshal.StructureToPtr(attributes, pAttributes, false); } #region Interop definitions private struct SECURITY_DESCRIPTOR { internal byte Revision; internal byte Sbz1; internal short Control; internal IntPtr Owner; internal IntPtr Group; internal IntPtr Sacl; internal IntPtr Dacl; } private struct SECURITY_ATTRIBUTES { internal int nLength; internal IntPtr lpSecurityDescriptor; // disable csharp compiler warning #0414: field assigned unused value #pragma warning disable 0414 internal bool bInheritHandle; #pragma warning restore 0414 } [DllImport(""advapi32.dll"", SetLastError = true)] private static extern bool InitializeSecurityDescriptor([In] ref SECURITY_DESCRIPTOR pSecurityDescriptor, int dwRevision); [DllImport(""advapi32.dll"", SetLastError = true)] private static extern bool SetSecurityDescriptorDacl([In] ref SECURITY_DESCRIPTOR pSecurityDescriptor, bool bDaclPresent, IntPtr pDacl, bool bDaclDefaulted); #endregion } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(546673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546673")] [Fact] public void TestBreakInsideNonLocalScopeBinder() { var source = @" public class C { public static void Main() { while (true) { unchecked { break; } } switch(0) { case 0: unchecked { break; } } while (true) { unsafe { break; } } switch(0) { case 0: unsafe { break; } } bool flag = false; while (!flag) { flag = true; unchecked { continue; } } flag = false; while (!flag) { flag = true; unsafe { continue; } } } }"; CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: ""); } [WorkItem(611904, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611904")] [Fact] public void LabelAtTopLevelInsideLambda() { var source = @" class Program { delegate T SomeDelegate<T>(out bool f); static void Main(string[] args) { Test((out bool f) => { if (1.ToString() != null) goto l2; f = true; l1: if (1.ToString() != null) return 123; // <==== ERROR EXPECTED HERE f = true; if (1.ToString() != null) return 456; l2: goto l1; }); } static void Test<T>(SomeDelegate<T> f) { } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (17,17): error CS0177: The out parameter 'f' must be assigned to before control leaves the current method // return 123; // <==== ERROR EXPECTED HERE Diagnostic(ErrorCode.ERR_ParamUnassigned, "return 123;").WithArguments("f") ); } [WorkItem(633927, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633927")] [Fact] public void Xyzzy() { var source = @"class C { struct S { int x; S(dynamic y) { Goo(y, null); } } static void Goo(int y) { } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (8,13): error CS1501: No overload for method 'Goo' takes 2 arguments // Goo(y, null); Diagnostic(ErrorCode.ERR_BadArgCount, "Goo").WithArguments("Goo", "2"), // (6,9): error CS0171: Field 'C.S.x' must be fully assigned before control is returned to the caller // S(dynamic y) Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("C.S.x"), // (5,13): warning CS0169: The field 'C.S.x' is never used // int x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("C.S.x") ); } [WorkItem(667368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667368")] [Fact] public void RegressionTest667368() { var source = @"using System.Collections.Generic; namespace ConsoleApplication1 { internal class Class1 { Dictionary<string, int> _dict = new Dictionary<string, int>(); public Class1() { } public int? GetCode(dynamic value) { int val; if (value != null && _dict.TryGetValue(value, out val)) return val; return null; } } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (17,24): error CS0165: Use of unassigned local variable 'val' // return val; Diagnostic(ErrorCode.ERR_UseDefViolation, "val").WithArguments("val") ); } [WorkItem(690921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/690921")] [Fact] public void RegressionTest690921() { var source = @"using System.Collections.Generic; namespace ConsoleApplication1 { internal class Class1 { Dictionary<string, int> _dict = new Dictionary<string, int>(); public Class1() { } public static string GetOutBoxItemId(string itemName, string uniqueIdKey, string listUrl, Dictionary<string, dynamic> myList = null, bool useDefaultCredentials = false) { string uniqueId = null; dynamic myItemName; if (myList != null && myList.TryGetValue(""DisplayName"", out myItemName) && myItemName == itemName) { } return uniqueId; } public static void Main() { } } } "; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [WorkItem(715338, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715338")] [Fact] public void RegressionTest715338() { var source = @"using System; using System.Collections.Generic; static class Program { static void Add(this IList<int> source, string key, int value) { } static void View(Action<string, int> adder) { } static readonly IList<int> myInts = null; static void Main() { View(myInts.Add); } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [WorkItem(808567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/808567")] [Fact] public void RegressionTest808567() { var source = @"class Base { public Base(out int x, System.Func<int> u) { x = 0; } } class Derived2 : Base { Derived2(out int p1) : base(out p1, ()=>p1) { } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (11,28): error CS1628: Cannot use ref or out parameter 'p1' inside an anonymous method, lambda expression, or query expression // : base(out p1, ()=>p1) Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "p1").WithArguments("p1"), // (11,20): error CS0269: Use of unassigned out parameter 'p1' // : base(out p1, ()=>p1) Diagnostic(ErrorCode.ERR_UseDefViolationOut, "p1").WithArguments("p1") ); } [WorkItem(949324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/949324")] [Fact] public void RegressionTest949324() { var source = @"struct Derived { Derived(int x) { } Derived(long x) : this(p2) // error CS0188: The 'this' object cannot be used before all of its fields are assigned to { this = new Derived(); } private int x; }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (3,5): error CS0171: Field 'Derived.x' must be fully assigned before control is returned to the caller // Derived(int x) { } Diagnostic(ErrorCode.ERR_UnassignedThis, "Derived").WithArguments("Derived.x").WithLocation(3, 5), // (4,28): error CS0103: The name 'p2' does not exist in the current context // Derived(long x) : this(p2) // error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_NameNotInContext, "p2").WithArguments("p2").WithLocation(4, 28), // (8,17): warning CS0169: The field 'Derived.x' is never used // private int x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("Derived.x").WithLocation(8, 17) ); } [WorkItem(612, "https://github.com/dotnet/roslyn/issues/612")] [Fact] public void CascadedUnreachableCode() { var source = @"class Program { public static void Main() { string k; switch (1) { case 1: } string s = k; } }"; CSharpCompilation comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS8070: Control cannot fall out of switch from final case label ('case 1:') // case 1: Diagnostic(ErrorCode.ERR_SwitchFallOut, "case 1:").WithArguments("case 1:").WithLocation(8, 9), // (10,20): error CS0165: Use of unassigned local variable 'k' // string s = k; Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k").WithLocation(10, 20) ); } [WorkItem(9581, "https://github.com/dotnet/roslyn/issues/9581")] [Fact] public void UsingSelfAssignment() { var source = @"class Program { static void Main() { using (System.IDisposable x = x) { } } }"; CSharpCompilation comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,39): error CS0165: Use of unassigned local variable 'x' // using (System.IDisposable x = x) Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(5, 39) ); } [Fact] public void UsingAssignment() { var source = @"class Program { static void Main() { using (System.IDisposable x = null) { System.Console.WriteLine(x.ToString()); } using (System.IDisposable x = null, y = x) { System.Console.WriteLine(y.ToString()); } } }"; CSharpCompilation comp = CreateCompilation(source); comp.VerifyDiagnostics( ); } [Fact] public void RangeDefiniteAssignmentOrder() { CreateCompilationWithIndexAndRange(@" class C { void M() { int x; var r = (x=0)..(x+1); int y; r = (y+1)..(y=0); } }").VerifyDiagnostics( // (9,14): error CS0165: Use of unassigned local variable 'y' // r = (y+1)..(y=0); Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(9, 14)); } [Fact] public void FieldAssignedInLambdaOnly() { var source = @"using System; struct S { private object F; private object G; public S(object x, object y) { Action a = () => { F = x; }; G = y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,12): error CS0171: Field 'S.F' must be fully assigned before control is returned to the caller // public S(object x, object y) Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("S.F").WithLocation(6, 12), // (8,28): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { F = x; }; Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "F").WithLocation(8, 28)); } [Fact] public void FieldAssignedInLocalFunctionOnly() { var source = @"struct S { private object F; private object G; public S(object x, object y) { void f() { F = x; } G = y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,12): error CS0171: Field 'S.F' must be fully assigned before control is returned to the caller // public S(object x, object y) Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("S.F").WithLocation(5, 12), // (7,14): warning CS8321: The local function 'f' is declared but never used // void f() { F = x; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(7, 14), // (7,20): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void f() { F = x; } Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "F").WithLocation(7, 20)); } [Fact] [WorkItem(1243877, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1243877")] public void WorkItem1243877() { string program = @" static class C { static void Main() { Test(out var x, x); } static void Test(out Empty x, object y) => throw null; } struct Empty { } "; CreateCompilation(program).VerifyDiagnostics( // (6,25): error CS8196: Reference to an implicitly-typed out variable 'x' is not permitted in the same argument list. // Test(out var x, x); Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x").WithArguments("x").WithLocation(6, 25) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class FlowDiagnosticTests : FlowTestBase { [Fact] public void TestBug12350() { // We suppress the "local variable is only written" warning if the // variable is assigned a non-constant value. string program = @" class Program { static int X() { return 1; } static void M() { int i1 = 123; // 0219 int i2 = X(); // no warning int? i3 = 123; // 0219 int? i4 = null; // 0219 int? i5 = X(); // no warning int i6 = default(int); // 0219 int? i7 = default(int?); // 0219 int? i8 = new int?(); // 0219 int i9 = new int(); // 0219 } }"; CreateCompilation(program).VerifyDiagnostics( // (7,13): warning CS0219: The variable 'i1' is assigned but its value is never used // int i1 = 123; // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i1").WithArguments("i1"), // (9,14): warning CS0219: The variable 'i3' is assigned but its value is never used // int? i3 = 123; // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i3").WithArguments("i3"), // (10,14): warning CS0219: The variable 'i4' is assigned but its value is never used // int? i4 = null; // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i4").WithArguments("i4"), // (12,13): warning CS0219: The variable 'i6' is assigned but its value is never used // int i6 = default(int); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i6").WithArguments("i6"), // (13,14): warning CS0219: The variable 'i7' is assigned but its value is never used // int? i7 = default(int?); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i7").WithArguments("i7"), // (14,14): warning CS0219: The variable 'i8' is assigned but its value is never used // int? i8 = new int?(); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i8").WithArguments("i8"), // (15,13): warning CS0219: The variable 'i9' is assigned but its value is never used // int i9 = new int(); // 0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i9").WithArguments("i9")); } [Fact] public void Test1() { string program = @" namespace ConsoleApplication1 { class Program { public static void F(int z) { int x; if (z == 2) { int y = x; x = y; // use of unassigned local variable 'x' } else { int y = x; x = y; // diagnostic suppressed here } } } }"; CreateCompilation(program).VerifyDiagnostics( // (11,25): error CS0165: Use of unassigned local variable 'x' // int y = x; x = y; // use of unassigned local variable 'x' Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x") ); } [Fact] public void Test2() { //x is "assigned when true" after "false" //Therefore x is "assigned" before "z == 1" (5.3.3.24) //Therefore x is "assigned" after "z == 1" (5.3.3.20) //Therefore x is "assigned when true" after "(false && z == 1)" (5.3.3.24) //Since the condition of the ?: expression is the constant true, the state of x after the ?: expression is the same as the state of x after the consequence (5.3.3.28) //Since the state of x after the consequence is "assigned when true", the state of x after the ?: expression is "assigned when true" (5.3.3.28) //Since the state of x after the if's condition is "assigned when true", x is assigned in the then block (5.3.3.5) //Therefore, there should be no error. string program = @" namespace ConsoleApplication1 { class Program { void F(int z) { int x; if (true ? (false && z == 1) : true) x = x + 1; // Dev10 complains x not assigned. } } }"; var comp = CreateCompilation(program); var errs = this.FlowDiagnostics(comp); Assert.Equal(0, errs.Count()); } [Fact] public void Test3() { string program = @" class Program { int F(int z) { } }"; var comp = CreateCompilation(program); var errs = this.FlowDiagnostics(comp); Assert.Equal(1, errs.Count()); } [Fact] public void Test4() { // v is definitely assigned at the beginning of any unreachable statement. string program = @" class Program { void F() { if (false) { int x; // warning: unreachable code x = x + 1; // no error: x assigned when unreachable } } }"; var comp = CreateCompilation(program); int[] count = new int[4]; foreach (var e in this.FlowDiagnostics(comp)) count[(int)e.Severity]++; Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(1, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); } [Fact] public void Test5() { // v is definitely assigned at the beginning of any unreachable statement. string program = @" class A { static void F() { goto L2; goto L1; // unreachable code detected int x; L1: ; // Roslyn: extrs warning CS0162 -unreachable code x = x + 1; // no definite assignment problem in unreachable code L2: ; } } "; var comp = CreateCompilation(program); int[] count = new int[4]; foreach (var e in this.FlowDiagnostics(comp)) count[(int)e.Severity]++; Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(2, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); } [WorkItem(537918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537918")] [Fact] public void AssertForInvalidBreak() { // v is definitely assigned at the beginning of any unreachable statement. string program = @" public class Test { public static int Main() { int ret = 1; break; // Assert here return (ret); } } "; var comp = CreateCompilation(program); comp.GetMethodBodyDiagnostics().Verify( // (7,9): error CS0139: No enclosing loop out of which to break or continue // break; // Assert here Diagnostic(ErrorCode.ERR_NoBreakOrCont, "break;")); } [WorkItem(538064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538064")] [Fact] public void IfFalse() { string program = @" using System; class Program { static void Main() { if (false) { } } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538067")] [Fact] public void WhileConstEqualsConst() { string program = @" using System; class Program { bool goo() { const bool b = true; while (b == b) { return b; } } static void Main() { } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538175")] [Fact] public void BreakWithoutTarget() { string program = @"public class Test { public static void Main() { if (true) break; } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [Fact] public void OutCausesAssignment() { string program = @"class Program { void F(out int x) { G(out x); } void G(out int x) { x = 1; } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [Fact] public void OutNotAssigned01() { string program = @"class Program { bool b; void F(out int x) { if (b) return; } }"; var comp = CreateCompilation(program); Assert.Equal(2, this.FlowDiagnostics(comp).Count()); } [WorkItem(539374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539374")] [Fact] public void OutAssignedAfterCall01() { string program = @"class Program { void F(out int x, int y) { x = y; } void G() { int x; F(out x, x); } }"; var comp = CreateCompilation(program); Assert.Equal(1, this.FlowDiagnostics(comp).Count()); } [WorkItem(538067, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538067")] [Fact] public void WhileConstEqualsConst2() { string program = @" using System; class Program { bool goo() { const bool b = true; while (b == b) { return b; } return b; // Should detect this line as unreachable code. } static void Main() { } }"; var comp = CreateCompilation(program); int[] count = new int[4]; foreach (var e in this.FlowDiagnostics(comp)) count[(int)e.Severity]++; Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(1, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); } [WorkItem(538072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538072")] [Fact] public void UnusedLocal() { string program = @" using System; class Program { int x; int y; int z; static void Main() { int a; const bool b = true; } void goo() { y = 2; Console.WriteLine(z); } }"; var comp = CreateCompilation(program); int[] count = new int[4]; Dictionary<int, int> warnings = new Dictionary<int, int>(); foreach (var e in this.FlowDiagnostics(comp)) { count[(int)e.Severity]++; if (!warnings.ContainsKey(e.Code)) warnings[e.Code] = 0; warnings[e.Code] += 1; } Assert.Equal(0, count[(int)DiagnosticSeverity.Error]); Assert.Equal(0, count[(int)DiagnosticSeverity.Info]); // See bug 3562 - field level flow analysis warnings CS0169, CS0414 and CS0649 are out of scope for M2. // TODO: Fix this test once CS0169, CS0414 and CS0649 are implemented. // Assert.Equal(5, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(2, count[(int)DiagnosticSeverity.Warning]); Assert.Equal(1, warnings[168]); Assert.Equal(1, warnings[219]); // See bug 3562 - field level flow analysis warnings CS0169, CS0414 and CS0649 are out of scope for M2. // TODO: Fix this test once CS0169, CS0414 and CS0649 are implemented. // Assert.Equal(1, warnings[169]); // Assert.Equal(1, warnings[414]); // Assert.Equal(1, warnings[649]); } [WorkItem(538384, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538384")] [Fact] public void UnusedLocalConstants() { string program = @" using System; class Program { static void Main() { const string CONST1 = ""hello""; // Should not report CS0219 Console.WriteLine(CONST1 != ""hello""); int i = 1; const long CONST2 = 1; const uint CONST3 = 1; // Should not report CS0219 while (CONST2 < CONST3 - i) { if (CONST3 < CONST3 - i) continue; } } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538385")] [Fact] public void UnusedLocalReferenceTypedVariables() { string program = @" using System; class Program { static void Main() { object o = 1; // Should not report CS0219 Test c = new Test(); // Should not report CS0219 c = new Program(); string s = string.Empty; // Should not report CS0219 s = null; } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [WorkItem(538386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538386")] [Fact] public void UnusedLocalValueTypedVariables() { string program = @" using System; class Program { static void Main() { } public void Repro2(params int[] x) { int i = x[0]; // Should not report CS0219 byte b1 = 1; byte b11 = b1; // Should not report CS0219 } }"; var comp = CreateCompilation(program); Assert.Equal(0, this.FlowDiagnostics(comp).Count()); } [Fact] public void RefParameter01() { string program = @" class Program { public static void Main(string[] args) { int i; F(ref i); // use of unassigned local variable 'i' } static void F(ref int i) { } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void OutParameter01() { string program = @" class Program { public static void Main(string[] args) { int i; F(out i); int j = i; } static void F(out int i) { i = 1; } }"; var comp = CreateCompilation(program); Assert.Empty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void Goto01() { string program = @" using System; class Program { public void M(bool b) { if (b) goto label; int i; i = 3; i = i + 1; label: int j = i; // i not definitely assigned } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void LambdaParameters() { string program = @" using System; class Program { delegate void Func(ref int i, int r); static void Main(string[] args) { Func fnc = (ref int arg, int arg2) => { arg = arg; }; } }"; var comp = CreateCompilation(program); Assert.Empty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void LambdaMightNotBeInvoked() { string program = @" class Program { delegate void Func(); static void Main(string[] args) { int i; Func query = () => { i = 12; }; int j = i; } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact] public void LambdaMustAssignOutParameters() { string program = @" class Program { delegate void Func(out int x); static void Main(string[] args) { Func query = (out int x) => { }; } }"; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [Fact, WorkItem(528052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528052")] public void InnerVariablesAreNotDefinitelyAssignedInBeginningOfLambdaBody() { string program = @" using System; class Program { static void Main() { return; Action f = () => { int y = y; }; } }"; CreateCompilation(program).VerifyDiagnostics( // (9,9): warning CS0162: Unreachable code detected // Action f = () => { int y = y; }; Diagnostic(ErrorCode.WRN_UnreachableCode, "Action"), // (9,36): error CS0165: Use of unassigned local variable 'y' // Action f = () => { int y = y; }; Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y") ); } [WorkItem(540139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540139")] [Fact] public void DelegateCreationReceiverIsRead() { string program = @" using System; class Program { static void Main() { Action a; Func<string> b = new Func<string>(a.ToString); } } "; var comp = CreateCompilation(program); Assert.NotEmpty(this.FlowDiagnostics(comp).Where(e => e.Severity >= DiagnosticSeverity.Error)); } [WorkItem(540405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540405")] [Fact] public void ErrorInFieldInitializerLambda() { string program = @" using System; class Program { static Func<string> x = () => { string s; return s; }; static void Main() { } } "; CreateCompilation(program).VerifyDiagnostics( // (6,54): error CS0165: Use of unassigned local variable 's' // static Func<string> x = () => { string s; return s; }; Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s") ); } [WorkItem(541389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541389")] [Fact] public void IterationWithEmptyBody() { string program = @" public class A { public static void Main(string[] args) { for (int i = 0; i < 10; i++) ; foreach (var v in args); int len = args.Length; while (len-- > 0); } }"; CreateCompilation(program).VerifyDiagnostics(); } [WorkItem(541389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541389")] [Fact] public void SelectionWithEmptyBody() { string program = @" public class A { public static void Main(string[] args) { int len = args.Length; if (len++ < 9) ; else ; } }"; CreateCompilation(program).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";"), Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";")); } [WorkItem(542146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542146")] [Fact] public void FieldlikeEvent() { string program = @"public delegate void D(); public struct S { public event D Ev; public S(D d) { Ev = null; Ev += d; } }"; CreateCompilation(program).VerifyDiagnostics( // (4,20): warning CS0414: The field 'S.Ev' is assigned but its value is never used // public event D Ev; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "Ev").WithArguments("S.Ev")); } [WorkItem(542187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542187")] [Fact] public void GotoFromTry() { string program = @"class Test { static void F(int x) { } static void Main() { int a; try { a = 1; goto L1; } finally { } L1: F(a); } }"; CreateCompilation(program).VerifyDiagnostics(); } [WorkItem(542154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542154")] [Fact] public void UnreachableThrow() { string program = @"public class C { static void Main() { return; throw Goo(); } static System.Exception Goo() { System.Console.WriteLine(""Hello""); return null; } } "; CreateCompilation(program).VerifyDiagnostics(); } [WorkItem(542585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542585")] [Fact] public void Bug9870() { string program = @" struct S<T> { T x; static void Goo() { x.x = 1; } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'S<T>.x' // x.x = 1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x").WithArguments("S<T>.x") ); } [WorkItem(542597, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542597")] [Fact] public void LambdaEntryPointIsReachable() { string program = @"class Program { static void Main(string[] args) { int i; return; System.Action a = () => { int j = i + j; }; } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // unreachable statement // (7,23): warning CS0162: Unreachable code detected // System.Action a = () => Diagnostic(ErrorCode.WRN_UnreachableCode, "System"), // (9,25): error CS0165: Use of unassigned local variable 'j' // int j = i + j; Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j") ); } [WorkItem(542597, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542597")] [Fact] public void LambdaInUnimplementedPartial() { string program = @"using System; partial class C { static partial void Goo(Action a); static void Main() { Goo(() => { int x, y = x; }); } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (9,32): error CS0165: Use of unassigned local variable 'x' // Goo(() => { int x, y = x; }); Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x") ); } [WorkItem(541887, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541887")] [Fact] public void CascadedDiagnostics01() { string program = @" class Program { static void Main(string[] args) { var s = goo<,int>(123); } public static int goo<T>(int i) { return 1; } }"; var comp = CreateCompilation(program); var parseErrors = comp.SyntaxTrees[0].GetDiagnostics(); var errors = comp.GetDiagnostics(); Assert.Equal(parseErrors.Count(), errors.Count()); } [Fact] public void UnassignedInInitializer() { string program = @"class C { System.Action a = () => { int i; int j = i; }; }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (3,46): error CS0165: Use of unassigned local variable 'i' // System.Action a = () => { int i; int j = i; }; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i") ); } [WorkItem(543343, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543343")] [Fact] public void ConstInSwitch() { string program = @"class Program { static void Main(string[] args) { switch (args.Length) { case 0: const int N = 3; break; case 1: int M = N; break; } } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (11,21): warning CS0219: The variable 'M' is assigned but its value is never used // int M = N; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "M").WithArguments("M") ); } #region "Struct" [Fact] public void CycleWithInitialization() { string program = @" public struct A { A a = new A(); // CS8036 public static void Main() { A a = new A(); } } "; CreateCompilation(program).VerifyDiagnostics( // (4,7): error CS0573: 'A': cannot have instance property or field initializers in structs // A a = new A(); // CS8036 Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "a").WithArguments("A").WithLocation(4, 7), // (4,7): error CS0523: Struct member 'A.a' of type 'A' causes a cycle in the struct layout // A a = new A(); // CS8036 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "a").WithArguments("A.a", "A").WithLocation(4, 7), // (7,11): warning CS0219: The variable 'a' is assigned but its value is never used // A a = new A(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(7, 11), // (4,7): warning CS0169: The field 'A.a' is never used // A a = new A(); // CS8036 Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("A.a").WithLocation(4, 7) ); } [WorkItem(542356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542356")] [Fact] public void StaticMemberExplosion() { string program = @" struct A<T> { static A<A<T>> x; } struct B<T> { static A<B<T>> x; } struct C<T> { static D<T> x; } struct D<T> { static C<D<T>> x; } "; CreateCompilation(program) .VerifyDiagnostics( // (14,17): error CS0523: Struct member 'C<T>.x' of type 'D<T>' causes a cycle in the struct layout // static D<T> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("C<T>.x", "D<T>").WithLocation(14, 17), // (18,20): error CS0523: Struct member 'D<T>.x' of type 'C<D<T>>' causes a cycle in the struct layout // static C<D<T>> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("D<T>.x", "C<D<T>>").WithLocation(18, 20), // (4,20): error CS0523: Struct member 'A<T>.x' of type 'A<A<T>>' causes a cycle in the struct layout // static A<A<T>> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("A<T>.x", "A<A<T>>").WithLocation(4, 20), // (9,20): warning CS0169: The field 'B<T>.x' is never used // static A<B<T>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("B<T>.x").WithLocation(9, 20), // (4,20): warning CS0169: The field 'A<T>.x' is never used // static A<A<T>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("A<T>.x").WithLocation(4, 20), // (18,20): warning CS0169: The field 'D<T>.x' is never used // static C<D<T>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("D<T>.x").WithLocation(18, 20), // (14,17): warning CS0169: The field 'C<T>.x' is never used // static D<T> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("C<T>.x").WithLocation(14, 17) ); } [Fact] public void StaticSequential() { string program = @" partial struct S { public static int x; } partial struct S { public static int y; }"; CreateCompilation(program) .VerifyDiagnostics( // (4,23): warning CS0649: Field 'S.x' is never assigned to, and will always have its default value 0 // public static int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("S.x", "0"), // (9,23): warning CS0649: Field 'S.y' is never assigned to, and will always have its default value 0 // public static int y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("S.y", "0") ); } [WorkItem(542567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542567")] [Fact] public void ImplicitFieldSequential() { string program = @"partial struct S1 { public int x; } partial struct S1 { public int y { get; set; } } partial struct S2 { public int x; } delegate void D(); partial struct S2 { public event D y; }"; CreateCompilation(program) .VerifyDiagnostics( // (1,16): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'S1'. To specify an ordering, all instance fields must be in the same declaration. // partial struct S1 Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "S1").WithArguments("S1"), // (11,16): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'S2'. To specify an ordering, all instance fields must be in the same declaration. // partial struct S2 Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "S2").WithArguments("S2"), // (3,16): warning CS0649: Field 'S1.x' is never assigned to, and will always have its default value 0 // public int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("S1.x", "0"), // (13,16): warning CS0649: Field 'S2.x' is never assigned to, and will always have its default value 0 // public int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("S2.x", "0"), // (19,20): warning CS0067: The event 'S2.y' is never used // public event D y; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "y").WithArguments("S2.y") ); } [Fact] public void StaticInitializer() { string program = @" public struct A { static System.Func<int> d = () => { int j; return j * 9000; }; public static void Main() { } } "; CreateCompilation(program) .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j") ); } [Fact] public void AllPiecesAssigned() { string program = @" struct S { public int x, y; } class Program { public static void Main(string[] args) { S s; s.x = args.Length; s.y = args.Length; S t = s; } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void OnePieceMissing() { string program = @" struct S { public int x, y; } class Program { public static void Main(string[] args) { S s; s.x = args.Length; S t = s; } } "; CreateCompilation(program) .VerifyDiagnostics( // (12,15): error CS0165: Use of unassigned local variable 's' // S t = s; Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s"), // (4,19): warning CS0649: Field 'S.y' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("S.y", "0") ); } [Fact] public void OnePieceOnOnePath() { string program = @" struct S { public int x, y; } class Program { public void F(S s) { S s2; if (s.x == 3) s2 = s; else s2.x = s.x; int x = s2.x; } } "; CreateCompilation(program) .VerifyDiagnostics( // (4,19): warning CS0649: Field 'S.y' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("S.y", "0") ); } [Fact] public void DefaultConstructor() { string program = @" struct S { public int x, y; } class Program { public static void Main(string[] args) { S s = new S(); s.x = s.y = s.x; } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void FieldAssignedInConstructor() { string program = @" struct S { int x, y; S(int x, int y) { this.x = x; this.y = y; } }"; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void FieldUnassignedInConstructor() { string program = @" struct S { int x, y; S(int x) { this.x = x; } }"; CreateCompilation(program) .VerifyDiagnostics( // (5,5): error CS0171: Field 'S.y' must be fully assigned before control is returned to the caller // S(int x) { this.x = x; } Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("S.y"), // (4,12): warning CS0169: The field 'S.y' is never used // int x, y; Diagnostic(ErrorCode.WRN_UnreferencedField, "y").WithArguments("S.y") ); } [WorkItem(543429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543429")] [Fact] public void ConstructorCannotComplete() { string program = @"using System; public struct S { int value; public S(int value) { throw new NotImplementedException(); } }"; CreateCompilation(program).VerifyDiagnostics( // (4,9): warning CS0169: The field 'S.value' is never used // int value; Diagnostic(ErrorCode.WRN_UnreferencedField, "value").WithArguments("S.value") ); } [Fact] public void AutoPropInitialization1() { string program = @" struct Program { public int X { get; private set; } public Program(int x) { } public static void Main(string[] args) { } }"; CreateCompilation(program) .VerifyDiagnostics( // (5,12): error CS0843: Backing field for automatically implemented property 'Program.X' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer. Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.X")); } [Fact] public void AutoPropInitialization2() { var text = @"struct S { public int P { get; set; } = 1; internal static long Q { get; } = 10; public decimal R { get; } = 300; public S(int i) {} }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,16): error CS0573: 'S': cannot have instance property or field initializers in structs // public int P { get; set; } = 1; Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "P").WithArguments("S").WithLocation(3, 16), // (5,20): error CS0573: 'S': cannot have instance property or field initializers in structs // public decimal R { get; } = 300; Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "R").WithArguments("S").WithLocation(5, 20) ); } [Fact] public void AutoPropInitialization3() { var text = @"struct S { public int P { get; private set; } internal static long Q { get; } = 10; public decimal R { get; } = 300; public S(int p) { P = p; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,20): error CS0573: 'S': cannot have instance property or field initializers in structs // public decimal R { get; } = 300; Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "R").WithArguments("S").WithLocation(5, 20) ); } [Fact] public void AutoPropInitialization4() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; } S1 x2 { get; } public Program(int dummy) { x.i = 1; System.Console.WriteLine(x2.ii); } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (16,9): error CS1612: Cannot modify the return value of 'Program.x' because it is not a variable // x.i = 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x").WithArguments("Program.x").WithLocation(16, 9), // (16,9): error CS0170: Use of possibly unassigned field 'i' // x.i = 1; Diagnostic(ErrorCode.ERR_UseDefViolationField, "x.i").WithArguments("i").WithLocation(16, 9), // (17,34): error CS8079: Use of possibly unassigned auto-implemented property 'x2' // System.Console.WriteLine(x2.ii); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x2").WithArguments("x2").WithLocation(17, 34), // (14,12): error CS0843: Auto-implemented property 'Program.x' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x").WithLocation(14, 12), // (14,12): error CS0843: Auto-implemented property 'Program.x2' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x2").WithLocation(14, 12)); } [Fact] public void AutoPropInitialization5() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get; set;} public Program(int dummy) { x.i = 1; System.Console.WriteLine(x2.ii); } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (16,9): error CS1612: Cannot modify the return value of 'Program.x' because it is not a variable // x.i = 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x").WithArguments("Program.x").WithLocation(16, 9), // (16,9): error CS0170: Use of possibly unassigned field 'i' // x.i = 1; Diagnostic(ErrorCode.ERR_UseDefViolationField, "x.i").WithArguments("i").WithLocation(16, 9), // (17,34): error CS8079: Use of possibly unassigned auto-implemented property 'x2' // System.Console.WriteLine(x2.ii); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x2").WithArguments("x2").WithLocation(17, 34), // (14,12): error CS0843: Auto-implemented property 'Program.x' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x").WithLocation(14, 12), // (14,12): error CS0843: Auto-implemented property 'Program.x2' must be fully assigned before control is returned to the caller. // public Program(int dummy) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "Program").WithArguments("Program.x2").WithLocation(14, 12)); } [Fact] public void AutoPropInitialization6() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program(int dummy) { x = new S1(); x.i += 1; x2 = new S1(); x2.i += 1; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (17,9): error CS1612: Cannot modify the return value of 'Program.x' because it is not a variable // x.i += 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x").WithArguments("Program.x").WithLocation(17, 9), // (20,9): error CS1612: Cannot modify the return value of 'Program.x2' because it is not a variable // x2.i += 1; Diagnostic(ErrorCode.ERR_ReturnNotLValue, "x2").WithArguments("Program.x2").WithLocation(20, 9) ); } [Fact] public void AutoPropInitialization7() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program(int dummy) { this = default(Program); System.Action a = () => { this.x = new S1(); }; System.Action a2 = () => { this.x2 = new S1(); }; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (20,13): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // this.x = new S1(); Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(20, 13), // (25,13): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // this.x2 = new S1(); Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(25, 13), // (6,20): warning CS0649: Field 'Program.S1.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("Program.S1.i", "0").WithLocation(6, 20) ); } [Fact] public void AutoPropInitialization7c() { var text = @" class Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program() { System.Action a = () => { this.x = new S1(); }; System.Action a2 = () => { this.x2 = new S1(); }; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (23,13): error CS0200: Property or indexer 'Program.x2' cannot be assigned to -- it is read only // this.x2 = new S1(); Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this.x2").WithArguments("Program.x2").WithLocation(23, 13), // (6,20): warning CS0649: Field 'Program.S1.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("Program.S1.i", "0").WithLocation(6, 20) ); } [Fact] public void AutoPropInitialization8() { var text = @" struct Program { struct S1 { public int i; public int ii { get; } } S1 x { get; set;} S1 x2 { get;} public Program(int arg) : this() { x2 = x; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,20): warning CS0649: Field 'Program.S1.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("Program.S1.i", "0").WithLocation(6, 20) ); } [Fact] public void AutoPropInitialization9() { var text = @" struct Program { struct S1 { } S1 x { get; set;} S1 x2 { get;} public Program(int arg) { x2 = x; } public void Goo() { } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); // no errors since S1 is empty comp.VerifyDiagnostics( ); } [Fact] public void AutoPropInitialization10() { var text = @" struct Program { public struct S1 { public int x; } S1 x1 { get; set;} S1 x2 { get;} S1 x3; public Program(int arg) { Goo(out x1); Goo(ref x1); Goo(out x2); Goo(ref x2); Goo(out x3); Goo(ref x3); } public static void Goo(out S1 s) { s = default(S1); } public static void Goo1(ref S1 s) { s = default(S1); } static void Main(string[] args) { } }"; var comp = CreateCompilation(text); // no errors since S1 is empty comp.VerifyDiagnostics( // (15,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(out x1); Diagnostic(ErrorCode.ERR_RefProperty, "x1").WithArguments("Program.x1").WithLocation(15, 17), // (16,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(ref x1); Diagnostic(ErrorCode.ERR_RefProperty, "x1").WithArguments("Program.x1").WithLocation(16, 17), // (17,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(out x2); Diagnostic(ErrorCode.ERR_RefProperty, "x2").WithArguments("Program.x2").WithLocation(17, 17), // (18,17): error CS0206: A property or indexer may not be passed as an out or ref parameter // Goo(ref x2); Diagnostic(ErrorCode.ERR_RefProperty, "x2").WithArguments("Program.x2").WithLocation(18, 17), // (20,17): error CS1620: Argument 1 must be passed with the 'out' keyword // Goo(ref x3); Diagnostic(ErrorCode.ERR_BadArgRef, "x3").WithArguments("1", "out").WithLocation(20, 17), // (15,17): error CS8079: Use of automatically implemented property 'x1' whose backing field is possibly unassigned // Goo(out x1); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x1").WithArguments("x1").WithLocation(15, 17), // (16,9): error CS0188: The 'this' object cannot be used before all of its fields are assigned to // Goo(ref x1); Diagnostic(ErrorCode.ERR_UseDefViolationThis, "Goo").WithArguments("this").WithLocation(16, 9), // (17,17): error CS8079: Use of automatically implemented property 'x2' whose backing field is possibly unassigned // Goo(out x2); Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "x2").WithArguments("x2").WithLocation(17, 17), // (6,20): warning CS0649: Field 'Program.S1.x' is never assigned to, and will always have its default value 0 // public int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("Program.S1.x", "0").WithLocation(6, 20) ); } [Fact] public void EmptyStructAlwaysAssigned() { string program = @" struct S { static S M() { S s; return s; } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [Fact] public void DeeplyEmptyStructAlwaysAssigned() { string program = @" struct S { static S M() { S s; return s; } } struct T { S s1, s2, s3; static T M() { T t; return t; } }"; CreateCompilation(program) .VerifyDiagnostics( // (13,15): warning CS0169: The field 'T.s3' is never used // S s1, s2, s3; Diagnostic(ErrorCode.WRN_UnreferencedField, "s3").WithArguments("T.s3").WithLocation(13, 15), // (13,11): warning CS0169: The field 'T.s2' is never used // S s1, s2, s3; Diagnostic(ErrorCode.WRN_UnreferencedField, "s2").WithArguments("T.s2").WithLocation(13, 11), // (13,7): warning CS0169: The field 'T.s1' is never used // S s1, s2, s3; Diagnostic(ErrorCode.WRN_UnreferencedField, "s1").WithArguments("T.s1").WithLocation(13, 7) ); } [WorkItem(543466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543466")] [Fact] public void UnreferencedFieldWarningsMissingInEmit() { var comp = CreateCompilation(@" public class Class1 { int field1; }"); var bindingDiags = comp.GetDiagnostics().ToArray(); Assert.Equal(1, bindingDiags.Length); Assert.Equal(ErrorCode.WRN_UnreferencedField, (ErrorCode)bindingDiags[0].Code); var emitDiags = comp.Emit(new System.IO.MemoryStream()).Diagnostics.ToArray(); Assert.Equal(bindingDiags.Length, emitDiags.Length); Assert.Equal(bindingDiags[0], emitDiags[0]); } [Fact] public void DefiniteAssignGenericStruct() { string program = @" using System; struct C<T> { public int num; public int Goo1() { return this.num; } } class Test { static void Main(string[] args) { C<object> c; c.num = 1; bool verify = c.Goo1() == 1; Console.WriteLine(verify); } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [WorkItem(540896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540896")] [WorkItem(541268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541268")] [Fact] public void ChainToStructDefaultConstructor() { string program = @" using System; namespace Roslyn.Compilers.CSharp { class DecimalRewriter { private DecimalRewriter() { } private struct DecimalParts { public DecimalParts(decimal value) : this() { int[] bits = Decimal.GetBits(value); Low = bits[0]; } public int Low { get; private set; } } } } "; CreateCompilation(program) .VerifyDiagnostics( ); } [WorkItem(541298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541298")] [WorkItem(541298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541298")] [Fact] public void SetStaticPropertyOnStruct() { string source = @" struct S { public static int p { get; internal set; } } class C { public static void Main() { S.p = 10; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void UsingPart() { string program = @" struct S { public int x; } class Program { public static void Main(string[] args) { S s = new S(); s.x = 12; } }"; CreateCompilation(program).VerifyDiagnostics(); } [Fact] public void ReferencingCycledStructures() { string program = @" public struct A { public static void Main() { S1 s1 = new S1(); S2 s2 = new S2(); s2.fld = new S3(); s2.fld.fld.fld.fld = new S2(); } } "; var c = CreateCompilation(program, new[] { TestReferences.SymbolsTests.CycledStructs }); c.VerifyDiagnostics( // (6,12): warning CS0219: The variable 's1' is assigned but its value is never used // S1 s1 = new S1(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s1").WithArguments("s1")); } [Fact] public void BigStruct() { string source = @" struct S<T> { T a, b, c, d, e, f, g, h; S(T t) { a = b = c = d = e = f = g = h = t; } static void M() { S<S<S<S<S<S<S<S<int>>>>>>>> x; x.a.a.a.a.a.a.a.a = 12; x.a.a.a.a.a.a.a.b = x.a.a.a.a.a.a.a.a; } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(542901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542901")] public void DataFlowForStructFieldAssignment() { string program = @"struct S { public float X; public float Y; public float Z; void M() { if (3 < 3.4) { S s; if (s.X < 3) { s = GetS(); s.Z = 10f; } else { } } else { } } private static S GetS() { return new S(); } } "; CreateCompilation(program).VerifyDiagnostics( // (12,17): error CS0170: Use of possibly unassigned field 'X' // if (s.X < 3) Diagnostic(ErrorCode.ERR_UseDefViolationField, "s.X").WithArguments("X"), // (3,18): warning CS0649: Field 'S.X' is never assigned to, and will always have its default value 0 // public float X; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "X").WithArguments("S.X", "0"), // (4,18): warning CS0649: Field 'S.Y' is never assigned to, and will always have its default value 0 // public float Y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Y").WithArguments("S.Y", "0") ); } [Fact] [WorkItem(2470, "https://github.com/dotnet/roslyn/issues/2470")] public void NoFieldNeverAssignedWarning() { string program = @" using System.Threading.Tasks; internal struct TaskEvent<T> { private TaskCompletionSource<T> _tcs; public Task<T> Task { get { if (_tcs == null) _tcs = new TaskCompletionSource<T>(); return _tcs.Task; } } public void Invoke(T result) { if (_tcs != null) { TaskCompletionSource<T> localTcs = _tcs; _tcs = null; localTcs.SetResult(result); } } } public class OperationExecutor { private TaskEvent<float?> _nextValueEvent; // Field is never assigned warning // Start some async operation public Task<bool> StartOperation() { return null; } // Get progress or data during async operation public Task<float?> WaitNextValue() { return _nextValueEvent.Task; } // Called externally internal void OnNextValue(float? value) { _nextValueEvent.Invoke(value); } } "; CreateCompilationWithMscorlib45(program).VerifyEmitDiagnostics(); } #endregion [Fact, WorkItem(545347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545347")] public void FieldInAbstractClass_UnusedField() { var text = @" abstract class AbstractType { public int Kind; }"; CreateCompilation(text).VerifyDiagnostics( // (4,16): warning CS0649: Field 'AbstractType.Kind' is never assigned to, and will always have its default value 0 // public int Kind; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Kind").WithArguments("AbstractType.Kind", "0").WithLocation(4, 16)); } [Fact, WorkItem(545347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545347")] public void FieldInAbstractClass_FieldUsedInChildType() { var text = @" abstract class AbstractType { public int Kind; } class ChildType : AbstractType { public ChildType() { this.Kind = 1; } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] [WorkItem(545642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545642")] public void InitializerAndConstructorWithOutParameter() { string program = @"class Program { private int field = Goo(); static int Goo() { return 12; } public Program(out int x) { x = 13; } }"; CreateCompilation(program).VerifyDiagnostics(); } [Fact] [WorkItem(545875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545875")] public void TestSuppressUnreferencedVarAssgOnIntPtr() { var source = @" using System; public class Test { public static void Main() { IntPtr i1 = (IntPtr)0; IntPtr i2 = (IntPtr)10L; UIntPtr ui1 = (UIntPtr)0; UIntPtr ui2 = (UIntPtr)10L; IntPtr z = IntPtr.Zero; int ip1 = (int)z; long lp1 = (long)z; UIntPtr uz = UIntPtr.Zero; int ip2 = (int)uz; long lp2 = (long)uz; } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(546183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546183")] public void TestUnassignedStructFieldsInPInvokePassByRefCase() { var source = @" using System; using System.Runtime.InteropServices; namespace ManagedDebuggingAssistants { internal class DebugMonitor { internal DebugMonitor() { SECURITY_ATTRIBUTES attributes = new SECURITY_ATTRIBUTES(); SECURITY_DESCRIPTOR descriptor = new SECURITY_DESCRIPTOR(); IntPtr pDescriptor = IntPtr.Zero; IntPtr pAttributes = IntPtr.Zero; attributes.nLength = Marshal.SizeOf(attributes); attributes.bInheritHandle = true; attributes.lpSecurityDescriptor = pDescriptor; if (!InitializeSecurityDescriptor(ref descriptor, 1 /*SECURITY_DESCRIPTOR_REVISION*/)) throw new ApplicationException(""InitializeSecurityDescriptor failed: "" + Marshal.GetLastWin32Error()); if (!SetSecurityDescriptorDacl(ref descriptor, true, IntPtr.Zero, false)) throw new ApplicationException(""SetSecurityDescriptorDacl failed: "" + Marshal.GetLastWin32Error()); Marshal.StructureToPtr(descriptor, pDescriptor, false); Marshal.StructureToPtr(attributes, pAttributes, false); } #region Interop definitions private struct SECURITY_DESCRIPTOR { internal byte Revision; internal byte Sbz1; internal short Control; internal IntPtr Owner; internal IntPtr Group; internal IntPtr Sacl; internal IntPtr Dacl; } private struct SECURITY_ATTRIBUTES { internal int nLength; internal IntPtr lpSecurityDescriptor; // disable csharp compiler warning #0414: field assigned unused value #pragma warning disable 0414 internal bool bInheritHandle; #pragma warning restore 0414 } [DllImport(""advapi32.dll"", SetLastError = true)] private static extern bool InitializeSecurityDescriptor([In] ref SECURITY_DESCRIPTOR pSecurityDescriptor, int dwRevision); [DllImport(""advapi32.dll"", SetLastError = true)] private static extern bool SetSecurityDescriptorDacl([In] ref SECURITY_DESCRIPTOR pSecurityDescriptor, bool bDaclPresent, IntPtr pDacl, bool bDaclDefaulted); #endregion } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(546673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546673")] [Fact] public void TestBreakInsideNonLocalScopeBinder() { var source = @" public class C { public static void Main() { while (true) { unchecked { break; } } switch(0) { case 0: unchecked { break; } } while (true) { unsafe { break; } } switch(0) { case 0: unsafe { break; } } bool flag = false; while (!flag) { flag = true; unchecked { continue; } } flag = false; while (!flag) { flag = true; unsafe { continue; } } } }"; CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: ""); } [WorkItem(611904, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611904")] [Fact] public void LabelAtTopLevelInsideLambda() { var source = @" class Program { delegate T SomeDelegate<T>(out bool f); static void Main(string[] args) { Test((out bool f) => { if (1.ToString() != null) goto l2; f = true; l1: if (1.ToString() != null) return 123; // <==== ERROR EXPECTED HERE f = true; if (1.ToString() != null) return 456; l2: goto l1; }); } static void Test<T>(SomeDelegate<T> f) { } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (17,17): error CS0177: The out parameter 'f' must be assigned to before control leaves the current method // return 123; // <==== ERROR EXPECTED HERE Diagnostic(ErrorCode.ERR_ParamUnassigned, "return 123;").WithArguments("f") ); } [WorkItem(633927, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633927")] [Fact] public void Xyzzy() { var source = @"class C { struct S { int x; S(dynamic y) { Goo(y, null); } } static void Goo(int y) { } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (8,13): error CS1501: No overload for method 'Goo' takes 2 arguments // Goo(y, null); Diagnostic(ErrorCode.ERR_BadArgCount, "Goo").WithArguments("Goo", "2"), // (6,9): error CS0171: Field 'C.S.x' must be fully assigned before control is returned to the caller // S(dynamic y) Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("C.S.x"), // (5,13): warning CS0169: The field 'C.S.x' is never used // int x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("C.S.x") ); } [WorkItem(667368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667368")] [Fact] public void RegressionTest667368() { var source = @"using System.Collections.Generic; namespace ConsoleApplication1 { internal class Class1 { Dictionary<string, int> _dict = new Dictionary<string, int>(); public Class1() { } public int? GetCode(dynamic value) { int val; if (value != null && _dict.TryGetValue(value, out val)) return val; return null; } } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (17,24): error CS0165: Use of unassigned local variable 'val' // return val; Diagnostic(ErrorCode.ERR_UseDefViolation, "val").WithArguments("val") ); } [WorkItem(690921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/690921")] [Fact] public void RegressionTest690921() { var source = @"using System.Collections.Generic; namespace ConsoleApplication1 { internal class Class1 { Dictionary<string, int> _dict = new Dictionary<string, int>(); public Class1() { } public static string GetOutBoxItemId(string itemName, string uniqueIdKey, string listUrl, Dictionary<string, dynamic> myList = null, bool useDefaultCredentials = false) { string uniqueId = null; dynamic myItemName; if (myList != null && myList.TryGetValue(""DisplayName"", out myItemName) && myItemName == itemName) { } return uniqueId; } public static void Main() { } } } "; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [WorkItem(715338, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715338")] [Fact] public void RegressionTest715338() { var source = @"using System; using System.Collections.Generic; static class Program { static void Add(this IList<int> source, string key, int value) { } static void View(Action<string, int> adder) { } static readonly IList<int> myInts = null; static void Main() { View(myInts.Add); } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [WorkItem(808567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/808567")] [Fact] public void RegressionTest808567() { var source = @"class Base { public Base(out int x, System.Func<int> u) { x = 0; } } class Derived2 : Base { Derived2(out int p1) : base(out p1, ()=>p1) { } }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (11,28): error CS1628: Cannot use ref or out parameter 'p1' inside an anonymous method, lambda expression, or query expression // : base(out p1, ()=>p1) Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "p1").WithArguments("p1"), // (11,20): error CS0269: Use of unassigned out parameter 'p1' // : base(out p1, ()=>p1) Diagnostic(ErrorCode.ERR_UseDefViolationOut, "p1").WithArguments("p1") ); } [WorkItem(949324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/949324")] [Fact] public void RegressionTest949324() { var source = @"struct Derived { Derived(int x) { } Derived(long x) : this(p2) // error CS0188: The 'this' object cannot be used before all of its fields are assigned to { this = new Derived(); } private int x; }"; CSharpCompilation comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (3,5): error CS0171: Field 'Derived.x' must be fully assigned before control is returned to the caller // Derived(int x) { } Diagnostic(ErrorCode.ERR_UnassignedThis, "Derived").WithArguments("Derived.x").WithLocation(3, 5), // (4,28): error CS0103: The name 'p2' does not exist in the current context // Derived(long x) : this(p2) // error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_NameNotInContext, "p2").WithArguments("p2").WithLocation(4, 28), // (8,17): warning CS0169: The field 'Derived.x' is never used // private int x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("Derived.x").WithLocation(8, 17) ); } [WorkItem(612, "https://github.com/dotnet/roslyn/issues/612")] [Fact] public void CascadedUnreachableCode() { var source = @"class Program { public static void Main() { string k; switch (1) { case 1: } string s = k; } }"; CSharpCompilation comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): error CS8070: Control cannot fall out of switch from final case label ('case 1:') // case 1: Diagnostic(ErrorCode.ERR_SwitchFallOut, "case 1:").WithArguments("case 1:").WithLocation(8, 9), // (10,20): error CS0165: Use of unassigned local variable 'k' // string s = k; Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k").WithLocation(10, 20) ); } [WorkItem(9581, "https://github.com/dotnet/roslyn/issues/9581")] [Fact] public void UsingSelfAssignment() { var source = @"class Program { static void Main() { using (System.IDisposable x = x) { } } }"; CSharpCompilation comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,39): error CS0165: Use of unassigned local variable 'x' // using (System.IDisposable x = x) Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(5, 39) ); } [Fact] public void UsingAssignment() { var source = @"class Program { static void Main() { using (System.IDisposable x = null) { System.Console.WriteLine(x.ToString()); } using (System.IDisposable x = null, y = x) { System.Console.WriteLine(y.ToString()); } } }"; CSharpCompilation comp = CreateCompilation(source); comp.VerifyDiagnostics( ); } [Fact] public void RangeDefiniteAssignmentOrder() { CreateCompilationWithIndexAndRange(@" class C { void M() { int x; var r = (x=0)..(x+1); int y; r = (y+1)..(y=0); } }").VerifyDiagnostics( // (9,14): error CS0165: Use of unassigned local variable 'y' // r = (y+1)..(y=0); Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(9, 14)); } [Fact] public void FieldAssignedInLambdaOnly() { var source = @"using System; struct S { private object F; private object G; public S(object x, object y) { Action a = () => { F = x; }; G = y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,12): error CS0171: Field 'S.F' must be fully assigned before control is returned to the caller // public S(object x, object y) Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("S.F").WithLocation(6, 12), // (8,28): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // Action a = () => { F = x; }; Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "F").WithLocation(8, 28)); } [Fact] public void FieldAssignedInLocalFunctionOnly() { var source = @"struct S { private object F; private object G; public S(object x, object y) { void f() { F = x; } G = y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,12): error CS0171: Field 'S.F' must be fully assigned before control is returned to the caller // public S(object x, object y) Diagnostic(ErrorCode.ERR_UnassignedThis, "S").WithArguments("S.F").WithLocation(5, 12), // (7,14): warning CS8321: The local function 'f' is declared but never used // void f() { F = x; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(7, 14), // (7,20): error CS1673: Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead. // void f() { F = x; } Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "F").WithLocation(7, 20)); } [Fact] [WorkItem(1243877, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1243877")] public void WorkItem1243877() { string program = @" static class C { static void Main() { Test(out var x, x); } static void Test(out Empty x, object y) => throw null; } struct Empty { } "; CreateCompilation(program).VerifyDiagnostics( // (6,25): error CS8196: Reference to an implicitly-typed out variable 'x' is not permitted in the same argument list. // Test(out var x, x); Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x").WithArguments("x").WithLocation(6, 25) ); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Binder/Binder_Attributes.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { #region Bind All Attributes // Method to bind attributes types early for all attributes to enable early decoding of some well-known attributes used within the binder. // Note: attributesToBind contains merged attributes from all the different syntax locations (e.g. for named types, partial methods, etc.). // Note: Additionally, the attributes with non-matching target specifier for the given owner symbol have been filtered out, i.e. Binder.MatchAttributeTarget method returned true. // For example, if were binding attributes on delegate type symbol for below code snippet: // [A1] // [return: A2] // public delegate void Goo(); // attributesToBind will only contain first attribute syntax. internal static void BindAttributeTypes(ImmutableArray<Binder> binders, ImmutableArray<AttributeSyntax> attributesToBind, Symbol ownerSymbol, NamedTypeSymbol[] boundAttributeTypes, BindingDiagnosticBag diagnostics) { Debug.Assert(binders.Any()); Debug.Assert(attributesToBind.Any()); Debug.Assert((object)ownerSymbol != null); Debug.Assert(binders.Length == attributesToBind.Length); RoslynDebug.Assert(boundAttributeTypes != null); for (int i = 0; i < attributesToBind.Length; i++) { // Some types may have been bound by an earlier stage. if (boundAttributeTypes[i] is null) { var binder = binders[i]; // BindType for AttributeSyntax's name is handled specially during lookup, see Binder.LookupAttributeType. // When looking up a name in attribute type context, we generate a diagnostic + error type if it is not an attribute type, i.e. named type deriving from System.Attribute. // Hence we can assume here that BindType returns a NamedTypeSymbol. boundAttributeTypes[i] = (NamedTypeSymbol)binder.BindType(attributesToBind[i].Name, diagnostics).Type; } } } // Method to bind all attributes (attribute arguments and constructor) internal static void GetAttributes( ImmutableArray<Binder> binders, ImmutableArray<AttributeSyntax> attributesToBind, ImmutableArray<NamedTypeSymbol> boundAttributeTypes, CSharpAttributeData?[] attributesBuilder, BindingDiagnosticBag diagnostics) { Debug.Assert(binders.Any()); Debug.Assert(attributesToBind.Any()); Debug.Assert(boundAttributeTypes.Any()); Debug.Assert(binders.Length == attributesToBind.Length); Debug.Assert(boundAttributeTypes.Length == attributesToBind.Length); RoslynDebug.Assert(attributesBuilder != null); for (int i = 0; i < attributesToBind.Length; i++) { AttributeSyntax attributeSyntax = attributesToBind[i]; NamedTypeSymbol boundAttributeType = boundAttributeTypes[i]; Binder binder = binders[i]; var attribute = (SourceAttributeData?)attributesBuilder[i]; if (attribute == null) { attributesBuilder[i] = binder.GetAttribute(attributeSyntax, boundAttributeType, diagnostics); } else { // attributesBuilder might contain some early bound well-known attributes, which had no errors. // We don't rebind the early bound attributes, but need to compute isConditionallyOmitted. // Note that AttributeData.IsConditionallyOmitted is required only during emit, but must be computed here as // its value depends on the values of conditional symbols, which in turn depends on the source file where the attribute is applied. Debug.Assert(!attribute.HasErrors); Debug.Assert(attribute.AttributeClass is object); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics); bool isConditionallyOmitted = binder.IsAttributeConditionallyOmitted(attribute.AttributeClass, attributeSyntax.SyntaxTree, ref useSiteInfo); diagnostics.Add(attributeSyntax, useSiteInfo); attributesBuilder[i] = attribute.WithOmittedCondition(isConditionallyOmitted); } } } #endregion #region Bind Single Attribute internal CSharpAttributeData GetAttribute(AttributeSyntax node, NamedTypeSymbol boundAttributeType, BindingDiagnosticBag diagnostics) { var boundAttribute = new ExecutableCodeBinder(node, this.ContainingMemberOrLambda, this).BindAttribute(node, boundAttributeType, diagnostics); return GetAttribute(boundAttribute, diagnostics); } internal BoundAttribute BindAttribute(AttributeSyntax node, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics) { return this.GetRequiredBinder(node).BindAttributeCore(node, attributeType, diagnostics); } private Binder SkipSemanticModelBinder() { Binder result = this; while (result.IsSemanticModelBinder) { result = result.Next!; } return result; } private BoundAttribute BindAttributeCore(AttributeSyntax node, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics) { Debug.Assert(this.SkipSemanticModelBinder() == this.GetRequiredBinder(node).SkipSemanticModelBinder()); // If attribute name bound to an error type with a single named type // candidate symbol, we want to bind the attribute constructor // and arguments with that named type to generate better semantic info. // CONSIDER: Do we need separate code paths for IDE and // CONSIDER: batch compilation scenarios? Above mentioned scenario // CONSIDER: is not useful for batch compilation. NamedTypeSymbol attributeTypeForBinding = attributeType; LookupResultKind resultKind = LookupResultKind.Viable; if (attributeTypeForBinding.IsErrorType()) { var errorType = (ErrorTypeSymbol)attributeTypeForBinding; resultKind = errorType.ResultKind; if (errorType.CandidateSymbols.Length == 1 && errorType.CandidateSymbols[0] is NamedTypeSymbol) { attributeTypeForBinding = (NamedTypeSymbol)errorType.CandidateSymbols[0]; } } // Bind constructor and named attribute arguments using the attribute binder var argumentListOpt = node.ArgumentList; Binder attributeArgumentBinder = this.WithAdditionalFlags(BinderFlags.AttributeArgument); AnalyzedAttributeArguments analyzedArguments = attributeArgumentBinder.BindAttributeArguments(argumentListOpt, attributeTypeForBinding, diagnostics); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); ImmutableArray<int> argsToParamsOpt = default; bool expanded = false; MethodSymbol? attributeConstructor = null; // Bind attributeType's constructor based on the bound constructor arguments ImmutableArray<BoundExpression> boundConstructorArguments; if (!attributeTypeForBinding.IsErrorType()) { attributeConstructor = BindAttributeConstructor(node, attributeTypeForBinding, analyzedArguments.ConstructorArguments, diagnostics, ref resultKind, suppressErrors: attributeType.IsErrorType(), ref argsToParamsOpt, ref expanded, ref useSiteInfo, out boundConstructorArguments); } else { boundConstructorArguments = analyzedArguments.ConstructorArguments.Arguments.SelectAsArray( static (arg, attributeArgumentBinder) => attributeArgumentBinder.BindToTypeForErrorRecovery(arg), attributeArgumentBinder); } Debug.Assert(boundConstructorArguments.All(a => !a.NeedsToBeConverted())); diagnostics.Add(node, useSiteInfo); if (attributeConstructor is object) { ReportDiagnosticsIfObsolete(diagnostics, attributeConstructor, node, hasBaseReceiver: false); if (attributeConstructor.Parameters.Any(p => p.RefKind == RefKind.In)) { Error(diagnostics, ErrorCode.ERR_AttributeCtorInParameter, node, attributeConstructor.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)); } } ImmutableArray<string?> boundConstructorArgumentNamesOpt = analyzedArguments.ConstructorArguments.GetNames(); ImmutableArray<BoundAssignmentOperator> boundNamedArguments = analyzedArguments.NamedArguments?.ToImmutableAndFree() ?? ImmutableArray<BoundAssignmentOperator>.Empty; Debug.Assert(boundNamedArguments.All(arg => !arg.Right.NeedsToBeConverted())); analyzedArguments.ConstructorArguments.Free(); return new BoundAttribute(node, attributeConstructor, boundConstructorArguments, boundConstructorArgumentNamesOpt, argsToParamsOpt, expanded, boundNamedArguments, resultKind, attributeType, hasErrors: resultKind != LookupResultKind.Viable); } private CSharpAttributeData GetAttribute(BoundAttribute boundAttribute, BindingDiagnosticBag diagnostics) { var attributeType = (NamedTypeSymbol)boundAttribute.Type; var attributeConstructor = boundAttribute.Constructor; RoslynDebug.Assert((object)attributeType != null); Debug.Assert(boundAttribute.Syntax.Kind() == SyntaxKind.Attribute); if (diagnostics.DiagnosticBag is object) { NullableWalker.AnalyzeIfNeeded(this, boundAttribute, boundAttribute.Syntax, diagnostics.DiagnosticBag); } bool hasErrors = boundAttribute.HasAnyErrors; if (attributeType.IsErrorType() || attributeType.IsAbstract || attributeConstructor is null) { // prevent cascading diagnostics Debug.Assert(hasErrors); return new SourceAttributeData(boundAttribute.Syntax.GetReference(), attributeType, attributeConstructor, hasErrors); } // Validate attribute constructor parameters have valid attribute parameter type ValidateTypeForAttributeParameters(attributeConstructor.Parameters, ((AttributeSyntax)boundAttribute.Syntax).Name, diagnostics, ref hasErrors); // Validate the attribute arguments and generate TypedConstant for argument's BoundExpression. var visitor = new AttributeExpressionVisitor(this); var arguments = boundAttribute.ConstructorArguments; var constructorArgsArray = visitor.VisitArguments(arguments, diagnostics, ref hasErrors); var namedArguments = visitor.VisitNamedArguments(boundAttribute.NamedArguments, diagnostics, ref hasErrors); Debug.Assert(!constructorArgsArray.IsDefault, "Property of VisitArguments"); ImmutableArray<int> constructorArgumentsSourceIndices; ImmutableArray<TypedConstant> constructorArguments; if (hasErrors || attributeConstructor.ParameterCount == 0) { constructorArgumentsSourceIndices = default(ImmutableArray<int>); constructorArguments = constructorArgsArray; } else { constructorArguments = GetRewrittenAttributeConstructorArguments(out constructorArgumentsSourceIndices, attributeConstructor, constructorArgsArray, boundAttribute.ConstructorArgumentNamesOpt, (AttributeSyntax)boundAttribute.Syntax, diagnostics, ref hasErrors); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isConditionallyOmitted = IsAttributeConditionallyOmitted(attributeType, boundAttribute.SyntaxTree, ref useSiteInfo); diagnostics.Add(boundAttribute.Syntax, useSiteInfo); return new SourceAttributeData(boundAttribute.Syntax.GetReference(), attributeType, attributeConstructor, constructorArguments, constructorArgumentsSourceIndices, namedArguments, hasErrors, isConditionallyOmitted); } private void ValidateTypeForAttributeParameters(ImmutableArray<ParameterSymbol> parameters, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics, ref bool hasErrors) { foreach (var parameter in parameters) { var paramType = parameter.TypeWithAnnotations; Debug.Assert(paramType.HasType); if (!paramType.Type.IsValidAttributeParameterType(Compilation)) { Error(diagnostics, ErrorCode.ERR_BadAttributeParamType, syntax, parameter.Name, paramType.Type); hasErrors = true; } } } protected bool IsAttributeConditionallyOmitted(NamedTypeSymbol attributeType, SyntaxTree? syntaxTree, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // When early binding attributes, we don't want to determine if the attribute type is conditional and if so, must be emitted or not. // Invoking IsConditional property on attributeType can lead to a cycle, hence we delay this computation until after early binding. if (IsEarlyAttributeBinder) { return false; } Debug.Assert((object)attributeType != null); Debug.Assert(!attributeType.IsErrorType()); if (attributeType.IsConditional) { ImmutableArray<string> conditionalSymbols = attributeType.GetAppliedConditionalSymbols(); Debug.Assert(conditionalSymbols != null); if (syntaxTree.IsAnyPreprocessorSymbolDefined(conditionalSymbols)) { return false; } var baseType = attributeType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); if ((object)baseType != null && baseType.IsConditional) { return IsAttributeConditionallyOmitted(baseType, syntaxTree, ref useSiteInfo); } return true; } else { return false; } } /// <summary> /// The caller is responsible for freeing <see cref="AnalyzedAttributeArguments.ConstructorArguments"/> and <see cref="AnalyzedAttributeArguments.NamedArguments"/>. /// </summary> private AnalyzedAttributeArguments BindAttributeArguments( AttributeArgumentListSyntax? attributeArgumentList, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics) { var boundConstructorArguments = AnalyzedArguments.GetInstance(); ArrayBuilder<BoundAssignmentOperator>? boundNamedArgumentsBuilder = null; if (attributeArgumentList != null) { HashSet<string>? boundNamedArgumentsSet = null; // Only report the first "non-trailing named args required C# 7.2" error, // so as to avoid "cascading" errors. bool hadLangVersionError = false; var shouldHaveName = false; foreach (var argument in attributeArgumentList.Arguments) { if (argument.NameEquals == null) { if (shouldHaveName) { diagnostics.Add(ErrorCode.ERR_NamedArgumentExpected, argument.Expression.GetLocation()); } // Constructor argument this.BindArgumentAndName( boundConstructorArguments, diagnostics, ref hadLangVersionError, argument, BindArgumentExpression(diagnostics, argument.Expression, RefKind.None, allowArglist: false), argument.NameColon, refKind: RefKind.None); } else { shouldHaveName = true; // Named argument // TODO: use fully qualified identifier name for boundNamedArgumentsSet string argumentName = argument.NameEquals.Name.Identifier.ValueText!; if (boundNamedArgumentsBuilder == null) { boundNamedArgumentsBuilder = ArrayBuilder<BoundAssignmentOperator>.GetInstance(); boundNamedArgumentsSet = new HashSet<string>(); } else if (boundNamedArgumentsSet!.Contains(argumentName)) { // Duplicate named argument Error(diagnostics, ErrorCode.ERR_DuplicateNamedAttributeArgument, argument, argumentName); } BoundAssignmentOperator boundNamedArgument = BindNamedAttributeArgument(argument, attributeType, diagnostics); boundNamedArgumentsBuilder.Add(boundNamedArgument); boundNamedArgumentsSet.Add(argumentName); } } } return new AnalyzedAttributeArguments(boundConstructorArguments, boundNamedArgumentsBuilder); } private BoundAssignmentOperator BindNamedAttributeArgument(AttributeArgumentSyntax namedArgument, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics) { bool wasError; LookupResultKind resultKind; Symbol namedArgumentNameSymbol = BindNamedAttributeArgumentName(namedArgument, attributeType, diagnostics, out wasError, out resultKind); ReportDiagnosticsIfObsolete(diagnostics, namedArgumentNameSymbol, namedArgument, hasBaseReceiver: false); if (namedArgumentNameSymbol.Kind == SymbolKind.Property) { var propertySymbol = (PropertySymbol)namedArgumentNameSymbol; var setMethod = propertySymbol.GetOwnOrInheritedSetMethod(); if (setMethod != null) { ReportDiagnosticsIfObsolete(diagnostics, setMethod, namedArgument, hasBaseReceiver: false); if (setMethod.IsInitOnly && setMethod.DeclaringCompilation != this.Compilation) { // an error would have already been reported on declaring an init-only setter CheckFeatureAvailability(namedArgument, MessageID.IDS_FeatureInitOnlySetters, diagnostics); } } } Debug.Assert(resultKind == LookupResultKind.Viable || wasError); TypeSymbol namedArgumentType; if (wasError) { namedArgumentType = CreateErrorType(); // don't generate cascaded errors. } else { namedArgumentType = BindNamedAttributeArgumentType(namedArgument, namedArgumentNameSymbol, attributeType, diagnostics); } // BindRValue just binds the expression without doing any validation (if its a valid expression for attribute argument). // Validation is done later by AttributeExpressionVisitor BoundExpression namedArgumentValue = this.BindValue(namedArgument.Expression, diagnostics, BindValueKind.RValue); namedArgumentValue = GenerateConversionForAssignment(namedArgumentType, namedArgumentValue, diagnostics); // TODO: should we create an entry even if there are binding errors? var fieldSymbol = namedArgumentNameSymbol as FieldSymbol; RoslynDebug.Assert(namedArgument.NameEquals is object); IdentifierNameSyntax nameSyntax = namedArgument.NameEquals.Name; BoundExpression lvalue; if (fieldSymbol is object) { var containingAssembly = fieldSymbol.ContainingAssembly as SourceAssemblySymbol; // We do not want to generate any unassigned field or unreferenced field diagnostics. containingAssembly?.NoteFieldAccess(fieldSymbol, read: true, write: true); lvalue = new BoundFieldAccess(nameSyntax, null, fieldSymbol, ConstantValue.NotAvailable, resultKind, fieldSymbol.Type); } else { var propertySymbol = namedArgumentNameSymbol as PropertySymbol; if (propertySymbol is object) { lvalue = new BoundPropertyAccess(nameSyntax, null, propertySymbol, resultKind, namedArgumentType); } else { lvalue = BadExpression(nameSyntax, resultKind); } } return new BoundAssignmentOperator(namedArgument, lvalue, namedArgumentValue, namedArgumentType); } private Symbol BindNamedAttributeArgumentName(AttributeArgumentSyntax namedArgument, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics, out bool wasError, out LookupResultKind resultKind) { RoslynDebug.Assert(namedArgument.NameEquals is object); var identifierName = namedArgument.NameEquals.Name; var name = identifierName.Identifier.ValueText; LookupResult result = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(result, attributeType, name, 0, ref useSiteInfo); diagnostics.Add(identifierName, useSiteInfo); Symbol resultSymbol = this.ResultSymbol(result, name, 0, identifierName, diagnostics, false, out wasError, qualifierOpt: null); resultKind = result.Kind; result.Free(); return resultSymbol; } private TypeSymbol BindNamedAttributeArgumentType(AttributeArgumentSyntax namedArgument, Symbol namedArgumentNameSymbol, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics) { if (namedArgumentNameSymbol.Kind == SymbolKind.ErrorType) { return (TypeSymbol)namedArgumentNameSymbol; } // SPEC: For each named-argument Arg in named-argument-list N: // SPEC: Let Name be the identifier of the named-argument Arg. // SPEC: Name must identify a non-static read-write public field or property on // SPEC: attribute class T. If T has no such field or property, then a compile-time error occurs. bool invalidNamedArgument = false; TypeSymbol? namedArgumentType = null; invalidNamedArgument |= (namedArgumentNameSymbol.DeclaredAccessibility != Accessibility.Public); invalidNamedArgument |= namedArgumentNameSymbol.IsStatic; if (!invalidNamedArgument) { switch (namedArgumentNameSymbol.Kind) { case SymbolKind.Field: var fieldSymbol = (FieldSymbol)namedArgumentNameSymbol; namedArgumentType = fieldSymbol.Type; invalidNamedArgument |= fieldSymbol.IsReadOnly; invalidNamedArgument |= fieldSymbol.IsConst; break; case SymbolKind.Property: var propertySymbol = ((PropertySymbol)namedArgumentNameSymbol).GetLeastOverriddenProperty(this.ContainingType); namedArgumentType = propertySymbol.Type; invalidNamedArgument |= propertySymbol.IsReadOnly; var getMethod = propertySymbol.GetMethod; var setMethod = propertySymbol.SetMethod; invalidNamedArgument = invalidNamedArgument || (object)getMethod == null || (object)setMethod == null; if (!invalidNamedArgument) { invalidNamedArgument = getMethod!.DeclaredAccessibility != Accessibility.Public || setMethod!.DeclaredAccessibility != Accessibility.Public; } break; default: invalidNamedArgument = true; break; } } if (invalidNamedArgument) { RoslynDebug.Assert(namedArgument.NameEquals is object); return new ExtendedErrorTypeSymbol(attributeType, namedArgumentNameSymbol, LookupResultKind.NotAVariable, diagnostics.Add(ErrorCode.ERR_BadNamedAttributeArgument, namedArgument.NameEquals.Name.Location, namedArgumentNameSymbol.Name)); } RoslynDebug.Assert(namedArgumentType is object); if (!namedArgumentType.IsValidAttributeParameterType(Compilation)) { RoslynDebug.Assert(namedArgument.NameEquals is object); return new ExtendedErrorTypeSymbol(attributeType, namedArgumentNameSymbol, LookupResultKind.NotAVariable, diagnostics.Add(ErrorCode.ERR_BadNamedAttributeArgumentType, namedArgument.NameEquals.Name.Location, namedArgumentNameSymbol.Name)); } return namedArgumentType; } protected MethodSymbol BindAttributeConstructor( AttributeSyntax node, NamedTypeSymbol attributeType, AnalyzedArguments boundConstructorArguments, BindingDiagnosticBag diagnostics, ref LookupResultKind resultKind, bool suppressErrors, ref ImmutableArray<int> argsToParamsOpt, ref bool expanded, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out ImmutableArray<BoundExpression> constructorArguments) { MemberResolutionResult<MethodSymbol> memberResolutionResult; ImmutableArray<MethodSymbol> candidateConstructors; if (!TryPerformConstructorOverloadResolution( attributeType, boundConstructorArguments, attributeType.Name, node.Location, suppressErrors, //don't cascade in these cases diagnostics, out memberResolutionResult, out candidateConstructors, allowProtectedConstructorsOfBaseType: true)) { resultKind = resultKind.WorseResultKind( memberResolutionResult.IsValid && !IsConstructorAccessible(memberResolutionResult.Member, ref useSiteInfo) ? LookupResultKind.Inaccessible : LookupResultKind.OverloadResolutionFailure); constructorArguments = BuildArgumentsForErrorRecovery(boundConstructorArguments, candidateConstructors); } else { constructorArguments = boundConstructorArguments.Arguments.ToImmutable(); } argsToParamsOpt = memberResolutionResult.Result.ArgsToParamsOpt; expanded = memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; return memberResolutionResult.Member; } /// <summary> /// Gets the rewritten attribute constructor arguments, i.e. the arguments /// are in the order of parameters, which may differ from the source /// if named constructor arguments are used. /// /// For example: /// void Goo(int x, int y, int z, int w = 3); /// /// Goo(0, z: 2, y: 1); /// /// Arguments returned: 0, 1, 2, 3 /// </summary> /// <returns>Rewritten attribute constructor arguments</returns> /// <remarks> /// CONSIDER: Can we share some code will call rewriting in the local rewriter? /// </remarks> private ImmutableArray<TypedConstant> GetRewrittenAttributeConstructorArguments( out ImmutableArray<int> constructorArgumentsSourceIndices, MethodSymbol attributeConstructor, ImmutableArray<TypedConstant> constructorArgsArray, ImmutableArray<string?> constructorArgumentNamesOpt, AttributeSyntax syntax, BindingDiagnosticBag diagnostics, ref bool hasErrors) { RoslynDebug.Assert((object)attributeConstructor != null); Debug.Assert(!constructorArgsArray.IsDefault); Debug.Assert(!hasErrors); int argumentsCount = constructorArgsArray.Length; // argsConsumedCount keeps track of the number of constructor arguments // consumed from this.ConstructorArguments array int argsConsumedCount = 0; bool hasNamedCtorArguments = !constructorArgumentNamesOpt.IsDefault; Debug.Assert(!hasNamedCtorArguments || constructorArgumentNamesOpt.Length == argumentsCount); // index of the first named constructor argument int firstNamedArgIndex = -1; ImmutableArray<ParameterSymbol> parameters = attributeConstructor.Parameters; int parameterCount = parameters.Length; var reorderedArguments = new TypedConstant[parameterCount]; int[]? sourceIndices = null; for (int i = 0; i < parameterCount; i++) { Debug.Assert(argsConsumedCount <= argumentsCount); ParameterSymbol parameter = parameters[i]; TypedConstant reorderedArgument; if (parameter.IsParams && parameter.Type.IsSZArray() && i + 1 == parameterCount) { reorderedArgument = GetParamArrayArgument(parameter, constructorArgsArray, constructorArgumentNamesOpt, argumentsCount, argsConsumedCount, this.Conversions, out bool foundNamed); if (!foundNamed) { sourceIndices = sourceIndices ?? CreateSourceIndicesArray(i, parameterCount); } } else if (argsConsumedCount < argumentsCount) { if (!hasNamedCtorArguments || constructorArgumentNamesOpt[argsConsumedCount] == null) { // positional constructor argument reorderedArgument = constructorArgsArray[argsConsumedCount]; if (sourceIndices != null) { sourceIndices[i] = argsConsumedCount; } argsConsumedCount++; } else { // named constructor argument // Store the index of the first named constructor argument if (firstNamedArgIndex == -1) { firstNamedArgIndex = argsConsumedCount; } // Current parameter must either have a matching named argument or a default value // For the former case, argsConsumedCount must be incremented to note that we have // consumed a named argument. For the latter case, argsConsumedCount stays same. int matchingArgumentIndex; reorderedArgument = GetMatchingNamedOrOptionalConstructorArgument(out matchingArgumentIndex, constructorArgsArray, constructorArgumentNamesOpt, parameter, firstNamedArgIndex, argumentsCount, ref argsConsumedCount, syntax, diagnostics); sourceIndices = sourceIndices ?? CreateSourceIndicesArray(i, parameterCount); sourceIndices[i] = matchingArgumentIndex; } } else { reorderedArgument = GetDefaultValueArgument(parameter, syntax, diagnostics); sourceIndices = sourceIndices ?? CreateSourceIndicesArray(i, parameterCount); } if (!hasErrors) { if (reorderedArgument.Kind == TypedConstantKind.Error) { hasErrors = true; } else if (reorderedArgument.Kind == TypedConstantKind.Array && parameter.Type.TypeKind == TypeKind.Array && !((TypeSymbol)reorderedArgument.TypeInternal!).Equals(parameter.Type, TypeCompareKind.AllIgnoreOptions)) { // NOTE: As in dev11, we don't allow array covariance conversions (presumably, we don't have a way to // represent the conversion in metadata). diagnostics.Add(ErrorCode.ERR_BadAttributeArgument, syntax.Location); hasErrors = true; } } reorderedArguments[i] = reorderedArgument; } constructorArgumentsSourceIndices = sourceIndices != null ? sourceIndices.AsImmutableOrNull() : default(ImmutableArray<int>); return reorderedArguments.AsImmutableOrNull(); } private static int[] CreateSourceIndicesArray(int paramIndex, int parameterCount) { Debug.Assert(paramIndex >= 0); Debug.Assert(paramIndex < parameterCount); var sourceIndices = new int[parameterCount]; for (int i = 0; i < paramIndex; i++) { sourceIndices[i] = i; } for (int i = paramIndex; i < parameterCount; i++) { sourceIndices[i] = -1; } return sourceIndices; } private TypedConstant GetMatchingNamedOrOptionalConstructorArgument( out int matchingArgumentIndex, ImmutableArray<TypedConstant> constructorArgsArray, ImmutableArray<string?> constructorArgumentNamesOpt, ParameterSymbol parameter, int startIndex, int argumentsCount, ref int argsConsumedCount, AttributeSyntax syntax, BindingDiagnosticBag diagnostics) { int index = GetMatchingNamedConstructorArgumentIndex(parameter.Name, constructorArgumentNamesOpt, startIndex, argumentsCount); if (index < argumentsCount) { // found a matching named argument Debug.Assert(index >= startIndex); // increment argsConsumedCount argsConsumedCount++; matchingArgumentIndex = index; return constructorArgsArray[index]; } else { matchingArgumentIndex = -1; return GetDefaultValueArgument(parameter, syntax, diagnostics); } } private static int GetMatchingNamedConstructorArgumentIndex(string parameterName, ImmutableArray<string?> argumentNamesOpt, int startIndex, int argumentsCount) { RoslynDebug.Assert(parameterName != null); Debug.Assert(startIndex >= 0 && startIndex < argumentsCount); if (parameterName.IsEmpty() || !argumentNamesOpt.Any()) { return argumentsCount; } // get the matching named (constructor) argument int argIndex = startIndex; while (argIndex < argumentsCount) { var name = argumentNamesOpt[argIndex]; if (string.Equals(name, parameterName, StringComparison.Ordinal)) { break; } argIndex++; } return argIndex; } private TypedConstant GetDefaultValueArgument(ParameterSymbol parameter, AttributeSyntax syntax, BindingDiagnosticBag diagnostics) { var parameterType = parameter.Type; ConstantValue? defaultConstantValue = parameter.IsOptional ? parameter.ExplicitDefaultConstantValue : ConstantValue.NotAvailable; TypedConstantKind kind; object? defaultValue = null; if (!IsEarlyAttributeBinder && parameter.IsCallerLineNumber) { int line = syntax.SyntaxTree.GetDisplayLineNumber(syntax.Name.Span); kind = TypedConstantKind.Primitive; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = Conversions.GetCallerLineNumberConversion(parameterType, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); if (conversion.IsNumeric || conversion.IsConstantExpression) { // DoUncheckedConversion() keeps "single" floats as doubles internally to maintain higher // precision, so make sure they get cast to floats here. defaultValue = (parameterType.SpecialType == SpecialType.System_Single) ? (float)line : Binder.DoUncheckedConversion(parameterType.SpecialType, ConstantValue.Create(line)); } else { // Boxing or identity conversion: parameterType = Compilation.GetSpecialType(SpecialType.System_Int32); defaultValue = line; } } else if (!IsEarlyAttributeBinder && parameter.IsCallerFilePath) { parameterType = Compilation.GetSpecialType(SpecialType.System_String); kind = TypedConstantKind.Primitive; defaultValue = syntax.SyntaxTree.GetDisplayPath(syntax.Name.Span, Compilation.Options.SourceReferenceResolver); } else if (!IsEarlyAttributeBinder && parameter.IsCallerMemberName && (object)((ContextualAttributeBinder)this).AttributedMember != null) { parameterType = Compilation.GetSpecialType(SpecialType.System_String); kind = TypedConstantKind.Primitive; defaultValue = ((ContextualAttributeBinder)this).AttributedMember.GetMemberCallerName(); } else if (defaultConstantValue == ConstantValue.NotAvailable) { // There is no constant value given for the parameter in source/metadata. // For example, the attribute constructor with signature: M([Optional] int x), has no default value from syntax or attributes. // Default value for these cases is "default(parameterType)". // Optional parameter of System.Object type is treated specially though. // Native compiler treats "M([Optional] object x)" equivalent to "M(object x)" for attributes if parameter type is System.Object. // We generate a better diagnostic for this case by treating "x" in the above case as optional, but generating CS7067 instead. if (parameterType.SpecialType == SpecialType.System_Object) { // CS7067: Attribute constructor parameter '{0}' is optional, but no default parameter value was specified. diagnostics.Add(ErrorCode.ERR_BadAttributeParamDefaultArgument, syntax.Name.Location, parameter.Name); kind = TypedConstantKind.Error; } else { kind = TypedConstant.GetTypedConstantKind(parameterType, this.Compilation); Debug.Assert(kind != TypedConstantKind.Error); defaultConstantValue = parameterType.GetDefaultValue(); if (defaultConstantValue != null) { defaultValue = defaultConstantValue.Value; } } } else if (defaultConstantValue.IsBad) { // Constant value through syntax had errors, don't generate cascading diagnostics. kind = TypedConstantKind.Error; } else if (parameterType.SpecialType == SpecialType.System_Object && !defaultConstantValue.IsNull) { // error CS1763: '{0}' is of type '{1}'. A default parameter value of a reference type other than string can only be initialized with null diagnostics.Add(ErrorCode.ERR_NotNullRefDefaultParameter, syntax.Location, parameter.Name, parameterType); kind = TypedConstantKind.Error; } else { kind = TypedConstant.GetTypedConstantKind(parameterType, this.Compilation); Debug.Assert(kind != TypedConstantKind.Error); defaultValue = defaultConstantValue.Value; } if (kind == TypedConstantKind.Array) { Debug.Assert(defaultValue == null); return new TypedConstant(parameterType, default(ImmutableArray<TypedConstant>)); } else { return new TypedConstant(parameterType, kind, defaultValue); } } private static TypedConstant GetParamArrayArgument(ParameterSymbol parameter, ImmutableArray<TypedConstant> constructorArgsArray, ImmutableArray<string?> constructorArgumentNamesOpt, int argumentsCount, int argsConsumedCount, Conversions conversions, out bool foundNamed) { Debug.Assert(argsConsumedCount <= argumentsCount); // If there's a named argument, we'll use that if (!constructorArgumentNamesOpt.IsDefault) { int argIndex = constructorArgumentNamesOpt.IndexOf(parameter.Name); if (argIndex >= 0) { foundNamed = true; if (TryGetNormalParamValue(parameter, constructorArgsArray, argIndex, conversions, out var namedValue)) { return namedValue; } // A named argument for a params parameter is necessarily the only one for that parameter return new TypedConstant(parameter.Type, ImmutableArray.Create(constructorArgsArray[argIndex])); } } int paramArrayArgCount = argumentsCount - argsConsumedCount; foundNamed = false; // If there are zero arguments left if (paramArrayArgCount == 0) { return new TypedConstant(parameter.Type, ImmutableArray<TypedConstant>.Empty); } // If there's exactly one argument left, we'll try to use it in normal form if (paramArrayArgCount == 1 && TryGetNormalParamValue(parameter, constructorArgsArray, argsConsumedCount, conversions, out var lastValue)) { return lastValue; } Debug.Assert(!constructorArgsArray.IsDefault); Debug.Assert(argsConsumedCount <= constructorArgsArray.Length); // Take the trailing arguments as an array for expanded form var values = new TypedConstant[paramArrayArgCount]; for (int i = 0; i < paramArrayArgCount; i++) { values[i] = constructorArgsArray[argsConsumedCount++]; } return new TypedConstant(parameter.Type, values.AsImmutableOrNull()); } private static bool TryGetNormalParamValue(ParameterSymbol parameter, ImmutableArray<TypedConstant> constructorArgsArray, int argIndex, Conversions conversions, out TypedConstant result) { TypedConstant argument = constructorArgsArray[argIndex]; if (argument.Kind != TypedConstantKind.Array) { result = default; return false; } Debug.Assert(argument.TypeInternal is object); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; // ignoring, since already bound argument and parameter Conversion conversion = conversions.ClassifyBuiltInConversion((TypeSymbol)argument.TypeInternal, parameter.Type, ref discardedUseSiteInfo); // NOTE: Won't always succeed, even though we've performed overload resolution. // For example, passing int[] to params object[] actually treats the int[] as an element of the object[]. if (conversion.IsValid && (conversion.Kind == ConversionKind.ImplicitReference || conversion.Kind == ConversionKind.Identity)) { result = argument; return true; } result = default; return false; } #endregion #region AttributeExpressionVisitor /// <summary> /// Walk a custom attribute argument bound node and return a TypedConstant. Verify that the expression is a constant expression. /// </summary> private struct AttributeExpressionVisitor { private readonly Binder _binder; public AttributeExpressionVisitor(Binder binder) { _binder = binder; } public ImmutableArray<TypedConstant> VisitArguments(ImmutableArray<BoundExpression> arguments, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool parentHasErrors = false) { var validatedArguments = ImmutableArray<TypedConstant>.Empty; int numArguments = arguments.Length; if (numArguments > 0) { var builder = ArrayBuilder<TypedConstant>.GetInstance(numArguments); foreach (var argument in arguments) { // current argument has errors if parent had errors OR argument.HasErrors. bool curArgumentHasErrors = parentHasErrors || argument.HasAnyErrors; builder.Add(VisitExpression(argument, diagnostics, ref attrHasErrors, curArgumentHasErrors)); } validatedArguments = builder.ToImmutableAndFree(); } return validatedArguments; } public ImmutableArray<KeyValuePair<string, TypedConstant>> VisitNamedArguments(ImmutableArray<BoundAssignmentOperator> arguments, BindingDiagnosticBag diagnostics, ref bool attrHasErrors) { ArrayBuilder<KeyValuePair<string, TypedConstant>>? builder = null; foreach (var argument in arguments) { var kv = VisitNamedArgument(argument, diagnostics, ref attrHasErrors); if (kv.HasValue) { if (builder == null) { builder = ArrayBuilder<KeyValuePair<string, TypedConstant>>.GetInstance(); } builder.Add(kv.Value); } } if (builder == null) { return ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty; } return builder.ToImmutableAndFree(); } private KeyValuePair<String, TypedConstant>? VisitNamedArgument(BoundAssignmentOperator assignment, BindingDiagnosticBag diagnostics, ref bool attrHasErrors) { KeyValuePair<String, TypedConstant>? visitedArgument = null; switch (assignment.Left.Kind) { case BoundKind.FieldAccess: var fa = (BoundFieldAccess)assignment.Left; visitedArgument = new KeyValuePair<String, TypedConstant>(fa.FieldSymbol.Name, VisitExpression(assignment.Right, diagnostics, ref attrHasErrors, assignment.HasAnyErrors)); break; case BoundKind.PropertyAccess: var pa = (BoundPropertyAccess)assignment.Left; visitedArgument = new KeyValuePair<String, TypedConstant>(pa.PropertySymbol.Name, VisitExpression(assignment.Right, diagnostics, ref attrHasErrors, assignment.HasAnyErrors)); break; } return visitedArgument; } // SPEC: An expression E is an attribute-argument-expression if all of the following statements are true: // SPEC: 1) The type of E is an attribute parameter type (§17.1.3). // SPEC: 2) At compile-time, the value of Expression can be resolved to one of the following: // SPEC: a) A constant value. // SPEC: b) A System.Type object. // SPEC: c) A one-dimensional array of attribute-argument-expressions private TypedConstant VisitExpression(BoundExpression node, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) { // Validate Statement 1) of the spec comment above. RoslynDebug.Assert(node.Type is object); var typedConstantKind = node.Type.GetAttributeParameterTypedConstantKind(_binder.Compilation); return VisitExpression(node, typedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors || typedConstantKind == TypedConstantKind.Error); } private TypedConstant VisitExpression(BoundExpression node, TypedConstantKind typedConstantKind, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) { // Validate Statement 2) of the spec comment above. ConstantValue? constantValue = node.ConstantValue; if (constantValue != null) { if (constantValue.IsBad) { typedConstantKind = TypedConstantKind.Error; } ConstantValueUtils.CheckLangVersionForConstantValue(node, diagnostics); return CreateTypedConstant(node, typedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors, simpleValue: constantValue.Value); } switch (node.Kind) { case BoundKind.Conversion: return VisitConversion((BoundConversion)node, diagnostics, ref attrHasErrors, curArgumentHasErrors); case BoundKind.TypeOfOperator: return VisitTypeOfExpression((BoundTypeOfOperator)node, diagnostics, ref attrHasErrors, curArgumentHasErrors); case BoundKind.ArrayCreation: return VisitArrayCreation((BoundArrayCreation)node, diagnostics, ref attrHasErrors, curArgumentHasErrors); default: return CreateTypedConstant(node, TypedConstantKind.Error, diagnostics, ref attrHasErrors, curArgumentHasErrors); } } private TypedConstant VisitConversion(BoundConversion node, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) { Debug.Assert(node.ConstantValue == null); // We have a bound conversion with a non-constant value. // According to statement 2) of the spec comment, this is not a valid attribute argument. // However, native compiler allows conversions to object type if the conversion operand is a valid attribute argument. // See method AttributeHelper::VerifyAttrArg(EXPR *arg). // We will match native compiler's behavior here. // Devdiv Bug #8763: Additionally we allow conversions from array type to object[], provided a conversion exists and each array element is a valid attribute argument. var type = node.Type; var operand = node.Operand; var operandType = operand.Type; if ((object)type != null && operandType is object) { if (type.SpecialType == SpecialType.System_Object || operandType.IsArray() && type.IsArray() && ((ArrayTypeSymbol)type).ElementType.SpecialType == SpecialType.System_Object) { var typedConstantKind = operandType.GetAttributeParameterTypedConstantKind(_binder.Compilation); return VisitExpression(operand, typedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors); } } return CreateTypedConstant(node, TypedConstantKind.Error, diagnostics, ref attrHasErrors, curArgumentHasErrors); } private static TypedConstant VisitTypeOfExpression(BoundTypeOfOperator node, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) { var typeOfArgument = (TypeSymbol?)node.SourceType.Type; // typeof argument is allowed to be: // (a) an unbound type // (b) closed constructed type // typeof argument cannot be an open type if (typeOfArgument is object) // skip this if the argument was an alias symbol { var isValidArgument = true; switch (typeOfArgument.Kind) { case SymbolKind.TypeParameter: // type parameter represents an open type isValidArgument = false; break; default: isValidArgument = typeOfArgument.IsUnboundGenericType() || !typeOfArgument.ContainsTypeParameter(); break; } if (!isValidArgument && !curArgumentHasErrors) { // attribute argument type cannot be an open type Binder.Error(diagnostics, ErrorCode.ERR_AttrArgWithTypeVars, node.Syntax, typeOfArgument.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)); curArgumentHasErrors = true; attrHasErrors = true; } } return CreateTypedConstant(node, TypedConstantKind.Type, diagnostics, ref attrHasErrors, curArgumentHasErrors, simpleValue: node.SourceType.Type); } private TypedConstant VisitArrayCreation(BoundArrayCreation node, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) { ImmutableArray<BoundExpression> bounds = node.Bounds; int boundsCount = bounds.Length; if (boundsCount > 1) { return CreateTypedConstant(node, TypedConstantKind.Error, diagnostics, ref attrHasErrors, curArgumentHasErrors); } var type = (ArrayTypeSymbol)node.Type; var typedConstantKind = type.GetAttributeParameterTypedConstantKind(_binder.Compilation); ImmutableArray<TypedConstant> initializer; if (node.InitializerOpt == null) { if (boundsCount == 0) { initializer = ImmutableArray<TypedConstant>.Empty; } else { if (bounds[0].IsDefaultValue()) { initializer = ImmutableArray<TypedConstant>.Empty; } else { // error: non-constant array creation initializer = ImmutableArray.Create(CreateTypedConstant(node, TypedConstantKind.Error, diagnostics, ref attrHasErrors, curArgumentHasErrors)); } } } else { initializer = VisitArguments(node.InitializerOpt.Initializers, diagnostics, ref attrHasErrors, curArgumentHasErrors); } return CreateTypedConstant(node, typedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors, arrayValue: initializer); } private static TypedConstant CreateTypedConstant(BoundExpression node, TypedConstantKind typedConstantKind, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors, object? simpleValue = null, ImmutableArray<TypedConstant> arrayValue = default(ImmutableArray<TypedConstant>)) { var type = node.Type; RoslynDebug.Assert(type is object); if (typedConstantKind != TypedConstantKind.Error && type.ContainsTypeParameter()) { // Devdiv Bug #12636: Constant values of open types should not be allowed in attributes // SPEC ERROR: C# language specification does not explicitly disallow constant values of open types. For e.g. // public class C<T> // { // public enum E { V } // } // // [SomeAttr(C<T>.E.V)] // case (a): Constant value of open type. // [SomeAttr(C<int>.E.V)] // case (b): Constant value of constructed type. // Both expressions 'C<T>.E.V' and 'C<int>.E.V' satisfy the requirements for a valid attribute-argument-expression: // (a) Its type is a valid attribute parameter type as per section 17.1.3 of the specification. // (b) It has a compile time constant value. // However, native compiler disallows both the above cases. // We disallow case (a) as it cannot be serialized correctly, but allow case (b) to compile. typedConstantKind = TypedConstantKind.Error; } if (typedConstantKind == TypedConstantKind.Error) { if (!curArgumentHasErrors) { Binder.Error(diagnostics, ErrorCode.ERR_BadAttributeArgument, node.Syntax); attrHasErrors = true; } return new TypedConstant(type, TypedConstantKind.Error, null); } else if (typedConstantKind == TypedConstantKind.Array) { return new TypedConstant(type, arrayValue); } else { return new TypedConstant(type, typedConstantKind, simpleValue); } } } #endregion #region AnalyzedAttributeArguments private struct AnalyzedAttributeArguments { internal readonly AnalyzedArguments ConstructorArguments; internal readonly ArrayBuilder<BoundAssignmentOperator>? NamedArguments; internal AnalyzedAttributeArguments(AnalyzedArguments constructorArguments, ArrayBuilder<BoundAssignmentOperator>? namedArguments) { this.ConstructorArguments = constructorArguments; this.NamedArguments = namedArguments; } } #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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { #region Bind All Attributes // Method to bind attributes types early for all attributes to enable early decoding of some well-known attributes used within the binder. // Note: attributesToBind contains merged attributes from all the different syntax locations (e.g. for named types, partial methods, etc.). // Note: Additionally, the attributes with non-matching target specifier for the given owner symbol have been filtered out, i.e. Binder.MatchAttributeTarget method returned true. // For example, if were binding attributes on delegate type symbol for below code snippet: // [A1] // [return: A2] // public delegate void Goo(); // attributesToBind will only contain first attribute syntax. internal static void BindAttributeTypes(ImmutableArray<Binder> binders, ImmutableArray<AttributeSyntax> attributesToBind, Symbol ownerSymbol, NamedTypeSymbol[] boundAttributeTypes, BindingDiagnosticBag diagnostics) { Debug.Assert(binders.Any()); Debug.Assert(attributesToBind.Any()); Debug.Assert((object)ownerSymbol != null); Debug.Assert(binders.Length == attributesToBind.Length); RoslynDebug.Assert(boundAttributeTypes != null); for (int i = 0; i < attributesToBind.Length; i++) { // Some types may have been bound by an earlier stage. if (boundAttributeTypes[i] is null) { var binder = binders[i]; // BindType for AttributeSyntax's name is handled specially during lookup, see Binder.LookupAttributeType. // When looking up a name in attribute type context, we generate a diagnostic + error type if it is not an attribute type, i.e. named type deriving from System.Attribute. // Hence we can assume here that BindType returns a NamedTypeSymbol. boundAttributeTypes[i] = (NamedTypeSymbol)binder.BindType(attributesToBind[i].Name, diagnostics).Type; } } } // Method to bind all attributes (attribute arguments and constructor) internal static void GetAttributes( ImmutableArray<Binder> binders, ImmutableArray<AttributeSyntax> attributesToBind, ImmutableArray<NamedTypeSymbol> boundAttributeTypes, CSharpAttributeData?[] attributesBuilder, BindingDiagnosticBag diagnostics) { Debug.Assert(binders.Any()); Debug.Assert(attributesToBind.Any()); Debug.Assert(boundAttributeTypes.Any()); Debug.Assert(binders.Length == attributesToBind.Length); Debug.Assert(boundAttributeTypes.Length == attributesToBind.Length); RoslynDebug.Assert(attributesBuilder != null); for (int i = 0; i < attributesToBind.Length; i++) { AttributeSyntax attributeSyntax = attributesToBind[i]; NamedTypeSymbol boundAttributeType = boundAttributeTypes[i]; Binder binder = binders[i]; var attribute = (SourceAttributeData?)attributesBuilder[i]; if (attribute == null) { attributesBuilder[i] = binder.GetAttribute(attributeSyntax, boundAttributeType, diagnostics); } else { // attributesBuilder might contain some early bound well-known attributes, which had no errors. // We don't rebind the early bound attributes, but need to compute isConditionallyOmitted. // Note that AttributeData.IsConditionallyOmitted is required only during emit, but must be computed here as // its value depends on the values of conditional symbols, which in turn depends on the source file where the attribute is applied. Debug.Assert(!attribute.HasErrors); Debug.Assert(attribute.AttributeClass is object); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics); bool isConditionallyOmitted = binder.IsAttributeConditionallyOmitted(attribute.AttributeClass, attributeSyntax.SyntaxTree, ref useSiteInfo); diagnostics.Add(attributeSyntax, useSiteInfo); attributesBuilder[i] = attribute.WithOmittedCondition(isConditionallyOmitted); } } } #endregion #region Bind Single Attribute internal CSharpAttributeData GetAttribute(AttributeSyntax node, NamedTypeSymbol boundAttributeType, BindingDiagnosticBag diagnostics) { var boundAttribute = new ExecutableCodeBinder(node, this.ContainingMemberOrLambda, this).BindAttribute(node, boundAttributeType, diagnostics); return GetAttribute(boundAttribute, diagnostics); } internal BoundAttribute BindAttribute(AttributeSyntax node, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics) { return this.GetRequiredBinder(node).BindAttributeCore(node, attributeType, diagnostics); } private Binder SkipSemanticModelBinder() { Binder result = this; while (result.IsSemanticModelBinder) { result = result.Next!; } return result; } private BoundAttribute BindAttributeCore(AttributeSyntax node, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics) { Debug.Assert(this.SkipSemanticModelBinder() == this.GetRequiredBinder(node).SkipSemanticModelBinder()); // If attribute name bound to an error type with a single named type // candidate symbol, we want to bind the attribute constructor // and arguments with that named type to generate better semantic info. // CONSIDER: Do we need separate code paths for IDE and // CONSIDER: batch compilation scenarios? Above mentioned scenario // CONSIDER: is not useful for batch compilation. NamedTypeSymbol attributeTypeForBinding = attributeType; LookupResultKind resultKind = LookupResultKind.Viable; if (attributeTypeForBinding.IsErrorType()) { var errorType = (ErrorTypeSymbol)attributeTypeForBinding; resultKind = errorType.ResultKind; if (errorType.CandidateSymbols.Length == 1 && errorType.CandidateSymbols[0] is NamedTypeSymbol) { attributeTypeForBinding = (NamedTypeSymbol)errorType.CandidateSymbols[0]; } } // Bind constructor and named attribute arguments using the attribute binder var argumentListOpt = node.ArgumentList; Binder attributeArgumentBinder = this.WithAdditionalFlags(BinderFlags.AttributeArgument); AnalyzedAttributeArguments analyzedArguments = attributeArgumentBinder.BindAttributeArguments(argumentListOpt, attributeTypeForBinding, diagnostics); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); ImmutableArray<int> argsToParamsOpt = default; bool expanded = false; MethodSymbol? attributeConstructor = null; // Bind attributeType's constructor based on the bound constructor arguments ImmutableArray<BoundExpression> boundConstructorArguments; if (!attributeTypeForBinding.IsErrorType()) { attributeConstructor = BindAttributeConstructor(node, attributeTypeForBinding, analyzedArguments.ConstructorArguments, diagnostics, ref resultKind, suppressErrors: attributeType.IsErrorType(), ref argsToParamsOpt, ref expanded, ref useSiteInfo, out boundConstructorArguments); } else { boundConstructorArguments = analyzedArguments.ConstructorArguments.Arguments.SelectAsArray( static (arg, attributeArgumentBinder) => attributeArgumentBinder.BindToTypeForErrorRecovery(arg), attributeArgumentBinder); } Debug.Assert(boundConstructorArguments.All(a => !a.NeedsToBeConverted())); diagnostics.Add(node, useSiteInfo); if (attributeConstructor is object) { ReportDiagnosticsIfObsolete(diagnostics, attributeConstructor, node, hasBaseReceiver: false); if (attributeConstructor.Parameters.Any(p => p.RefKind == RefKind.In)) { Error(diagnostics, ErrorCode.ERR_AttributeCtorInParameter, node, attributeConstructor.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)); } } ImmutableArray<string?> boundConstructorArgumentNamesOpt = analyzedArguments.ConstructorArguments.GetNames(); ImmutableArray<BoundAssignmentOperator> boundNamedArguments = analyzedArguments.NamedArguments?.ToImmutableAndFree() ?? ImmutableArray<BoundAssignmentOperator>.Empty; Debug.Assert(boundNamedArguments.All(arg => !arg.Right.NeedsToBeConverted())); analyzedArguments.ConstructorArguments.Free(); return new BoundAttribute(node, attributeConstructor, boundConstructorArguments, boundConstructorArgumentNamesOpt, argsToParamsOpt, expanded, boundNamedArguments, resultKind, attributeType, hasErrors: resultKind != LookupResultKind.Viable); } private CSharpAttributeData GetAttribute(BoundAttribute boundAttribute, BindingDiagnosticBag diagnostics) { var attributeType = (NamedTypeSymbol)boundAttribute.Type; var attributeConstructor = boundAttribute.Constructor; RoslynDebug.Assert((object)attributeType != null); Debug.Assert(boundAttribute.Syntax.Kind() == SyntaxKind.Attribute); if (diagnostics.DiagnosticBag is object) { NullableWalker.AnalyzeIfNeeded(this, boundAttribute, boundAttribute.Syntax, diagnostics.DiagnosticBag); } bool hasErrors = boundAttribute.HasAnyErrors; if (attributeType.IsErrorType() || attributeType.IsAbstract || attributeConstructor is null) { // prevent cascading diagnostics Debug.Assert(hasErrors); return new SourceAttributeData(boundAttribute.Syntax.GetReference(), attributeType, attributeConstructor, hasErrors); } // Validate attribute constructor parameters have valid attribute parameter type ValidateTypeForAttributeParameters(attributeConstructor.Parameters, ((AttributeSyntax)boundAttribute.Syntax).Name, diagnostics, ref hasErrors); // Validate the attribute arguments and generate TypedConstant for argument's BoundExpression. var visitor = new AttributeExpressionVisitor(this); var arguments = boundAttribute.ConstructorArguments; var constructorArgsArray = visitor.VisitArguments(arguments, diagnostics, ref hasErrors); var namedArguments = visitor.VisitNamedArguments(boundAttribute.NamedArguments, diagnostics, ref hasErrors); Debug.Assert(!constructorArgsArray.IsDefault, "Property of VisitArguments"); ImmutableArray<int> constructorArgumentsSourceIndices; ImmutableArray<TypedConstant> constructorArguments; if (hasErrors || attributeConstructor.ParameterCount == 0) { constructorArgumentsSourceIndices = default(ImmutableArray<int>); constructorArguments = constructorArgsArray; } else { constructorArguments = GetRewrittenAttributeConstructorArguments(out constructorArgumentsSourceIndices, attributeConstructor, constructorArgsArray, boundAttribute.ConstructorArgumentNamesOpt, (AttributeSyntax)boundAttribute.Syntax, diagnostics, ref hasErrors); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isConditionallyOmitted = IsAttributeConditionallyOmitted(attributeType, boundAttribute.SyntaxTree, ref useSiteInfo); diagnostics.Add(boundAttribute.Syntax, useSiteInfo); return new SourceAttributeData(boundAttribute.Syntax.GetReference(), attributeType, attributeConstructor, constructorArguments, constructorArgumentsSourceIndices, namedArguments, hasErrors, isConditionallyOmitted); } private void ValidateTypeForAttributeParameters(ImmutableArray<ParameterSymbol> parameters, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics, ref bool hasErrors) { foreach (var parameter in parameters) { var paramType = parameter.TypeWithAnnotations; Debug.Assert(paramType.HasType); if (!paramType.Type.IsValidAttributeParameterType(Compilation)) { Error(diagnostics, ErrorCode.ERR_BadAttributeParamType, syntax, parameter.Name, paramType.Type); hasErrors = true; } } } protected bool IsAttributeConditionallyOmitted(NamedTypeSymbol attributeType, SyntaxTree? syntaxTree, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // When early binding attributes, we don't want to determine if the attribute type is conditional and if so, must be emitted or not. // Invoking IsConditional property on attributeType can lead to a cycle, hence we delay this computation until after early binding. if (IsEarlyAttributeBinder) { return false; } Debug.Assert((object)attributeType != null); Debug.Assert(!attributeType.IsErrorType()); if (attributeType.IsConditional) { ImmutableArray<string> conditionalSymbols = attributeType.GetAppliedConditionalSymbols(); Debug.Assert(conditionalSymbols != null); if (syntaxTree.IsAnyPreprocessorSymbolDefined(conditionalSymbols)) { return false; } var baseType = attributeType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); if ((object)baseType != null && baseType.IsConditional) { return IsAttributeConditionallyOmitted(baseType, syntaxTree, ref useSiteInfo); } return true; } else { return false; } } /// <summary> /// The caller is responsible for freeing <see cref="AnalyzedAttributeArguments.ConstructorArguments"/> and <see cref="AnalyzedAttributeArguments.NamedArguments"/>. /// </summary> private AnalyzedAttributeArguments BindAttributeArguments( AttributeArgumentListSyntax? attributeArgumentList, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics) { var boundConstructorArguments = AnalyzedArguments.GetInstance(); ArrayBuilder<BoundAssignmentOperator>? boundNamedArgumentsBuilder = null; if (attributeArgumentList != null) { HashSet<string>? boundNamedArgumentsSet = null; // Only report the first "non-trailing named args required C# 7.2" error, // so as to avoid "cascading" errors. bool hadLangVersionError = false; var shouldHaveName = false; foreach (var argument in attributeArgumentList.Arguments) { if (argument.NameEquals == null) { if (shouldHaveName) { diagnostics.Add(ErrorCode.ERR_NamedArgumentExpected, argument.Expression.GetLocation()); } // Constructor argument this.BindArgumentAndName( boundConstructorArguments, diagnostics, ref hadLangVersionError, argument, BindArgumentExpression(diagnostics, argument.Expression, RefKind.None, allowArglist: false), argument.NameColon, refKind: RefKind.None); } else { shouldHaveName = true; // Named argument // TODO: use fully qualified identifier name for boundNamedArgumentsSet string argumentName = argument.NameEquals.Name.Identifier.ValueText!; if (boundNamedArgumentsBuilder == null) { boundNamedArgumentsBuilder = ArrayBuilder<BoundAssignmentOperator>.GetInstance(); boundNamedArgumentsSet = new HashSet<string>(); } else if (boundNamedArgumentsSet!.Contains(argumentName)) { // Duplicate named argument Error(diagnostics, ErrorCode.ERR_DuplicateNamedAttributeArgument, argument, argumentName); } BoundAssignmentOperator boundNamedArgument = BindNamedAttributeArgument(argument, attributeType, diagnostics); boundNamedArgumentsBuilder.Add(boundNamedArgument); boundNamedArgumentsSet.Add(argumentName); } } } return new AnalyzedAttributeArguments(boundConstructorArguments, boundNamedArgumentsBuilder); } private BoundAssignmentOperator BindNamedAttributeArgument(AttributeArgumentSyntax namedArgument, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics) { bool wasError; LookupResultKind resultKind; Symbol namedArgumentNameSymbol = BindNamedAttributeArgumentName(namedArgument, attributeType, diagnostics, out wasError, out resultKind); ReportDiagnosticsIfObsolete(diagnostics, namedArgumentNameSymbol, namedArgument, hasBaseReceiver: false); if (namedArgumentNameSymbol.Kind == SymbolKind.Property) { var propertySymbol = (PropertySymbol)namedArgumentNameSymbol; var setMethod = propertySymbol.GetOwnOrInheritedSetMethod(); if (setMethod != null) { ReportDiagnosticsIfObsolete(diagnostics, setMethod, namedArgument, hasBaseReceiver: false); if (setMethod.IsInitOnly && setMethod.DeclaringCompilation != this.Compilation) { // an error would have already been reported on declaring an init-only setter CheckFeatureAvailability(namedArgument, MessageID.IDS_FeatureInitOnlySetters, diagnostics); } } } Debug.Assert(resultKind == LookupResultKind.Viable || wasError); TypeSymbol namedArgumentType; if (wasError) { namedArgumentType = CreateErrorType(); // don't generate cascaded errors. } else { namedArgumentType = BindNamedAttributeArgumentType(namedArgument, namedArgumentNameSymbol, attributeType, diagnostics); } // BindRValue just binds the expression without doing any validation (if its a valid expression for attribute argument). // Validation is done later by AttributeExpressionVisitor BoundExpression namedArgumentValue = this.BindValue(namedArgument.Expression, diagnostics, BindValueKind.RValue); namedArgumentValue = GenerateConversionForAssignment(namedArgumentType, namedArgumentValue, diagnostics); // TODO: should we create an entry even if there are binding errors? var fieldSymbol = namedArgumentNameSymbol as FieldSymbol; RoslynDebug.Assert(namedArgument.NameEquals is object); IdentifierNameSyntax nameSyntax = namedArgument.NameEquals.Name; BoundExpression lvalue; if (fieldSymbol is object) { var containingAssembly = fieldSymbol.ContainingAssembly as SourceAssemblySymbol; // We do not want to generate any unassigned field or unreferenced field diagnostics. containingAssembly?.NoteFieldAccess(fieldSymbol, read: true, write: true); lvalue = new BoundFieldAccess(nameSyntax, null, fieldSymbol, ConstantValue.NotAvailable, resultKind, fieldSymbol.Type); } else { var propertySymbol = namedArgumentNameSymbol as PropertySymbol; if (propertySymbol is object) { lvalue = new BoundPropertyAccess(nameSyntax, null, propertySymbol, resultKind, namedArgumentType); } else { lvalue = BadExpression(nameSyntax, resultKind); } } return new BoundAssignmentOperator(namedArgument, lvalue, namedArgumentValue, namedArgumentType); } private Symbol BindNamedAttributeArgumentName(AttributeArgumentSyntax namedArgument, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics, out bool wasError, out LookupResultKind resultKind) { RoslynDebug.Assert(namedArgument.NameEquals is object); var identifierName = namedArgument.NameEquals.Name; var name = identifierName.Identifier.ValueText; LookupResult result = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(result, attributeType, name, 0, ref useSiteInfo); diagnostics.Add(identifierName, useSiteInfo); Symbol resultSymbol = this.ResultSymbol(result, name, 0, identifierName, diagnostics, false, out wasError, qualifierOpt: null); resultKind = result.Kind; result.Free(); return resultSymbol; } private TypeSymbol BindNamedAttributeArgumentType(AttributeArgumentSyntax namedArgument, Symbol namedArgumentNameSymbol, NamedTypeSymbol attributeType, BindingDiagnosticBag diagnostics) { if (namedArgumentNameSymbol.Kind == SymbolKind.ErrorType) { return (TypeSymbol)namedArgumentNameSymbol; } // SPEC: For each named-argument Arg in named-argument-list N: // SPEC: Let Name be the identifier of the named-argument Arg. // SPEC: Name must identify a non-static read-write public field or property on // SPEC: attribute class T. If T has no such field or property, then a compile-time error occurs. bool invalidNamedArgument = false; TypeSymbol? namedArgumentType = null; invalidNamedArgument |= (namedArgumentNameSymbol.DeclaredAccessibility != Accessibility.Public); invalidNamedArgument |= namedArgumentNameSymbol.IsStatic; if (!invalidNamedArgument) { switch (namedArgumentNameSymbol.Kind) { case SymbolKind.Field: var fieldSymbol = (FieldSymbol)namedArgumentNameSymbol; namedArgumentType = fieldSymbol.Type; invalidNamedArgument |= fieldSymbol.IsReadOnly; invalidNamedArgument |= fieldSymbol.IsConst; break; case SymbolKind.Property: var propertySymbol = ((PropertySymbol)namedArgumentNameSymbol).GetLeastOverriddenProperty(this.ContainingType); namedArgumentType = propertySymbol.Type; invalidNamedArgument |= propertySymbol.IsReadOnly; var getMethod = propertySymbol.GetMethod; var setMethod = propertySymbol.SetMethod; invalidNamedArgument = invalidNamedArgument || (object)getMethod == null || (object)setMethod == null; if (!invalidNamedArgument) { invalidNamedArgument = getMethod!.DeclaredAccessibility != Accessibility.Public || setMethod!.DeclaredAccessibility != Accessibility.Public; } break; default: invalidNamedArgument = true; break; } } if (invalidNamedArgument) { RoslynDebug.Assert(namedArgument.NameEquals is object); return new ExtendedErrorTypeSymbol(attributeType, namedArgumentNameSymbol, LookupResultKind.NotAVariable, diagnostics.Add(ErrorCode.ERR_BadNamedAttributeArgument, namedArgument.NameEquals.Name.Location, namedArgumentNameSymbol.Name)); } RoslynDebug.Assert(namedArgumentType is object); if (!namedArgumentType.IsValidAttributeParameterType(Compilation)) { RoslynDebug.Assert(namedArgument.NameEquals is object); return new ExtendedErrorTypeSymbol(attributeType, namedArgumentNameSymbol, LookupResultKind.NotAVariable, diagnostics.Add(ErrorCode.ERR_BadNamedAttributeArgumentType, namedArgument.NameEquals.Name.Location, namedArgumentNameSymbol.Name)); } return namedArgumentType; } protected MethodSymbol BindAttributeConstructor( AttributeSyntax node, NamedTypeSymbol attributeType, AnalyzedArguments boundConstructorArguments, BindingDiagnosticBag diagnostics, ref LookupResultKind resultKind, bool suppressErrors, ref ImmutableArray<int> argsToParamsOpt, ref bool expanded, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out ImmutableArray<BoundExpression> constructorArguments) { MemberResolutionResult<MethodSymbol> memberResolutionResult; ImmutableArray<MethodSymbol> candidateConstructors; if (!TryPerformConstructorOverloadResolution( attributeType, boundConstructorArguments, attributeType.Name, node.Location, suppressErrors, //don't cascade in these cases diagnostics, out memberResolutionResult, out candidateConstructors, allowProtectedConstructorsOfBaseType: true)) { resultKind = resultKind.WorseResultKind( memberResolutionResult.IsValid && !IsConstructorAccessible(memberResolutionResult.Member, ref useSiteInfo) ? LookupResultKind.Inaccessible : LookupResultKind.OverloadResolutionFailure); constructorArguments = BuildArgumentsForErrorRecovery(boundConstructorArguments, candidateConstructors); } else { constructorArguments = boundConstructorArguments.Arguments.ToImmutable(); } argsToParamsOpt = memberResolutionResult.Result.ArgsToParamsOpt; expanded = memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; return memberResolutionResult.Member; } /// <summary> /// Gets the rewritten attribute constructor arguments, i.e. the arguments /// are in the order of parameters, which may differ from the source /// if named constructor arguments are used. /// /// For example: /// void Goo(int x, int y, int z, int w = 3); /// /// Goo(0, z: 2, y: 1); /// /// Arguments returned: 0, 1, 2, 3 /// </summary> /// <returns>Rewritten attribute constructor arguments</returns> /// <remarks> /// CONSIDER: Can we share some code will call rewriting in the local rewriter? /// </remarks> private ImmutableArray<TypedConstant> GetRewrittenAttributeConstructorArguments( out ImmutableArray<int> constructorArgumentsSourceIndices, MethodSymbol attributeConstructor, ImmutableArray<TypedConstant> constructorArgsArray, ImmutableArray<string?> constructorArgumentNamesOpt, AttributeSyntax syntax, BindingDiagnosticBag diagnostics, ref bool hasErrors) { RoslynDebug.Assert((object)attributeConstructor != null); Debug.Assert(!constructorArgsArray.IsDefault); Debug.Assert(!hasErrors); int argumentsCount = constructorArgsArray.Length; // argsConsumedCount keeps track of the number of constructor arguments // consumed from this.ConstructorArguments array int argsConsumedCount = 0; bool hasNamedCtorArguments = !constructorArgumentNamesOpt.IsDefault; Debug.Assert(!hasNamedCtorArguments || constructorArgumentNamesOpt.Length == argumentsCount); // index of the first named constructor argument int firstNamedArgIndex = -1; ImmutableArray<ParameterSymbol> parameters = attributeConstructor.Parameters; int parameterCount = parameters.Length; var reorderedArguments = new TypedConstant[parameterCount]; int[]? sourceIndices = null; for (int i = 0; i < parameterCount; i++) { Debug.Assert(argsConsumedCount <= argumentsCount); ParameterSymbol parameter = parameters[i]; TypedConstant reorderedArgument; if (parameter.IsParams && parameter.Type.IsSZArray() && i + 1 == parameterCount) { reorderedArgument = GetParamArrayArgument(parameter, constructorArgsArray, constructorArgumentNamesOpt, argumentsCount, argsConsumedCount, this.Conversions, out bool foundNamed); if (!foundNamed) { sourceIndices = sourceIndices ?? CreateSourceIndicesArray(i, parameterCount); } } else if (argsConsumedCount < argumentsCount) { if (!hasNamedCtorArguments || constructorArgumentNamesOpt[argsConsumedCount] == null) { // positional constructor argument reorderedArgument = constructorArgsArray[argsConsumedCount]; if (sourceIndices != null) { sourceIndices[i] = argsConsumedCount; } argsConsumedCount++; } else { // named constructor argument // Store the index of the first named constructor argument if (firstNamedArgIndex == -1) { firstNamedArgIndex = argsConsumedCount; } // Current parameter must either have a matching named argument or a default value // For the former case, argsConsumedCount must be incremented to note that we have // consumed a named argument. For the latter case, argsConsumedCount stays same. int matchingArgumentIndex; reorderedArgument = GetMatchingNamedOrOptionalConstructorArgument(out matchingArgumentIndex, constructorArgsArray, constructorArgumentNamesOpt, parameter, firstNamedArgIndex, argumentsCount, ref argsConsumedCount, syntax, diagnostics); sourceIndices = sourceIndices ?? CreateSourceIndicesArray(i, parameterCount); sourceIndices[i] = matchingArgumentIndex; } } else { reorderedArgument = GetDefaultValueArgument(parameter, syntax, diagnostics); sourceIndices = sourceIndices ?? CreateSourceIndicesArray(i, parameterCount); } if (!hasErrors) { if (reorderedArgument.Kind == TypedConstantKind.Error) { hasErrors = true; } else if (reorderedArgument.Kind == TypedConstantKind.Array && parameter.Type.TypeKind == TypeKind.Array && !((TypeSymbol)reorderedArgument.TypeInternal!).Equals(parameter.Type, TypeCompareKind.AllIgnoreOptions)) { // NOTE: As in dev11, we don't allow array covariance conversions (presumably, we don't have a way to // represent the conversion in metadata). diagnostics.Add(ErrorCode.ERR_BadAttributeArgument, syntax.Location); hasErrors = true; } } reorderedArguments[i] = reorderedArgument; } constructorArgumentsSourceIndices = sourceIndices != null ? sourceIndices.AsImmutableOrNull() : default(ImmutableArray<int>); return reorderedArguments.AsImmutableOrNull(); } private static int[] CreateSourceIndicesArray(int paramIndex, int parameterCount) { Debug.Assert(paramIndex >= 0); Debug.Assert(paramIndex < parameterCount); var sourceIndices = new int[parameterCount]; for (int i = 0; i < paramIndex; i++) { sourceIndices[i] = i; } for (int i = paramIndex; i < parameterCount; i++) { sourceIndices[i] = -1; } return sourceIndices; } private TypedConstant GetMatchingNamedOrOptionalConstructorArgument( out int matchingArgumentIndex, ImmutableArray<TypedConstant> constructorArgsArray, ImmutableArray<string?> constructorArgumentNamesOpt, ParameterSymbol parameter, int startIndex, int argumentsCount, ref int argsConsumedCount, AttributeSyntax syntax, BindingDiagnosticBag diagnostics) { int index = GetMatchingNamedConstructorArgumentIndex(parameter.Name, constructorArgumentNamesOpt, startIndex, argumentsCount); if (index < argumentsCount) { // found a matching named argument Debug.Assert(index >= startIndex); // increment argsConsumedCount argsConsumedCount++; matchingArgumentIndex = index; return constructorArgsArray[index]; } else { matchingArgumentIndex = -1; return GetDefaultValueArgument(parameter, syntax, diagnostics); } } private static int GetMatchingNamedConstructorArgumentIndex(string parameterName, ImmutableArray<string?> argumentNamesOpt, int startIndex, int argumentsCount) { RoslynDebug.Assert(parameterName != null); Debug.Assert(startIndex >= 0 && startIndex < argumentsCount); if (parameterName.IsEmpty() || !argumentNamesOpt.Any()) { return argumentsCount; } // get the matching named (constructor) argument int argIndex = startIndex; while (argIndex < argumentsCount) { var name = argumentNamesOpt[argIndex]; if (string.Equals(name, parameterName, StringComparison.Ordinal)) { break; } argIndex++; } return argIndex; } private TypedConstant GetDefaultValueArgument(ParameterSymbol parameter, AttributeSyntax syntax, BindingDiagnosticBag diagnostics) { var parameterType = parameter.Type; ConstantValue? defaultConstantValue = parameter.IsOptional ? parameter.ExplicitDefaultConstantValue : ConstantValue.NotAvailable; TypedConstantKind kind; object? defaultValue = null; if (!IsEarlyAttributeBinder && parameter.IsCallerLineNumber) { int line = syntax.SyntaxTree.GetDisplayLineNumber(syntax.Name.Span); kind = TypedConstantKind.Primitive; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = Conversions.GetCallerLineNumberConversion(parameterType, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); if (conversion.IsNumeric || conversion.IsConstantExpression) { // DoUncheckedConversion() keeps "single" floats as doubles internally to maintain higher // precision, so make sure they get cast to floats here. defaultValue = (parameterType.SpecialType == SpecialType.System_Single) ? (float)line : Binder.DoUncheckedConversion(parameterType.SpecialType, ConstantValue.Create(line)); } else { // Boxing or identity conversion: parameterType = Compilation.GetSpecialType(SpecialType.System_Int32); defaultValue = line; } } else if (!IsEarlyAttributeBinder && parameter.IsCallerFilePath) { parameterType = Compilation.GetSpecialType(SpecialType.System_String); kind = TypedConstantKind.Primitive; defaultValue = syntax.SyntaxTree.GetDisplayPath(syntax.Name.Span, Compilation.Options.SourceReferenceResolver); } else if (!IsEarlyAttributeBinder && parameter.IsCallerMemberName && (object)((ContextualAttributeBinder)this).AttributedMember != null) { parameterType = Compilation.GetSpecialType(SpecialType.System_String); kind = TypedConstantKind.Primitive; defaultValue = ((ContextualAttributeBinder)this).AttributedMember.GetMemberCallerName(); } else if (defaultConstantValue == ConstantValue.NotAvailable) { // There is no constant value given for the parameter in source/metadata. // For example, the attribute constructor with signature: M([Optional] int x), has no default value from syntax or attributes. // Default value for these cases is "default(parameterType)". // Optional parameter of System.Object type is treated specially though. // Native compiler treats "M([Optional] object x)" equivalent to "M(object x)" for attributes if parameter type is System.Object. // We generate a better diagnostic for this case by treating "x" in the above case as optional, but generating CS7067 instead. if (parameterType.SpecialType == SpecialType.System_Object) { // CS7067: Attribute constructor parameter '{0}' is optional, but no default parameter value was specified. diagnostics.Add(ErrorCode.ERR_BadAttributeParamDefaultArgument, syntax.Name.Location, parameter.Name); kind = TypedConstantKind.Error; } else { kind = TypedConstant.GetTypedConstantKind(parameterType, this.Compilation); Debug.Assert(kind != TypedConstantKind.Error); defaultConstantValue = parameterType.GetDefaultValue(); if (defaultConstantValue != null) { defaultValue = defaultConstantValue.Value; } } } else if (defaultConstantValue.IsBad) { // Constant value through syntax had errors, don't generate cascading diagnostics. kind = TypedConstantKind.Error; } else if (parameterType.SpecialType == SpecialType.System_Object && !defaultConstantValue.IsNull) { // error CS1763: '{0}' is of type '{1}'. A default parameter value of a reference type other than string can only be initialized with null diagnostics.Add(ErrorCode.ERR_NotNullRefDefaultParameter, syntax.Location, parameter.Name, parameterType); kind = TypedConstantKind.Error; } else { kind = TypedConstant.GetTypedConstantKind(parameterType, this.Compilation); Debug.Assert(kind != TypedConstantKind.Error); defaultValue = defaultConstantValue.Value; } if (kind == TypedConstantKind.Array) { Debug.Assert(defaultValue == null); return new TypedConstant(parameterType, default(ImmutableArray<TypedConstant>)); } else { return new TypedConstant(parameterType, kind, defaultValue); } } private static TypedConstant GetParamArrayArgument(ParameterSymbol parameter, ImmutableArray<TypedConstant> constructorArgsArray, ImmutableArray<string?> constructorArgumentNamesOpt, int argumentsCount, int argsConsumedCount, Conversions conversions, out bool foundNamed) { Debug.Assert(argsConsumedCount <= argumentsCount); // If there's a named argument, we'll use that if (!constructorArgumentNamesOpt.IsDefault) { int argIndex = constructorArgumentNamesOpt.IndexOf(parameter.Name); if (argIndex >= 0) { foundNamed = true; if (TryGetNormalParamValue(parameter, constructorArgsArray, argIndex, conversions, out var namedValue)) { return namedValue; } // A named argument for a params parameter is necessarily the only one for that parameter return new TypedConstant(parameter.Type, ImmutableArray.Create(constructorArgsArray[argIndex])); } } int paramArrayArgCount = argumentsCount - argsConsumedCount; foundNamed = false; // If there are zero arguments left if (paramArrayArgCount == 0) { return new TypedConstant(parameter.Type, ImmutableArray<TypedConstant>.Empty); } // If there's exactly one argument left, we'll try to use it in normal form if (paramArrayArgCount == 1 && TryGetNormalParamValue(parameter, constructorArgsArray, argsConsumedCount, conversions, out var lastValue)) { return lastValue; } Debug.Assert(!constructorArgsArray.IsDefault); Debug.Assert(argsConsumedCount <= constructorArgsArray.Length); // Take the trailing arguments as an array for expanded form var values = new TypedConstant[paramArrayArgCount]; for (int i = 0; i < paramArrayArgCount; i++) { values[i] = constructorArgsArray[argsConsumedCount++]; } return new TypedConstant(parameter.Type, values.AsImmutableOrNull()); } private static bool TryGetNormalParamValue(ParameterSymbol parameter, ImmutableArray<TypedConstant> constructorArgsArray, int argIndex, Conversions conversions, out TypedConstant result) { TypedConstant argument = constructorArgsArray[argIndex]; if (argument.Kind != TypedConstantKind.Array) { result = default; return false; } Debug.Assert(argument.TypeInternal is object); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; // ignoring, since already bound argument and parameter Conversion conversion = conversions.ClassifyBuiltInConversion((TypeSymbol)argument.TypeInternal, parameter.Type, ref discardedUseSiteInfo); // NOTE: Won't always succeed, even though we've performed overload resolution. // For example, passing int[] to params object[] actually treats the int[] as an element of the object[]. if (conversion.IsValid && (conversion.Kind == ConversionKind.ImplicitReference || conversion.Kind == ConversionKind.Identity)) { result = argument; return true; } result = default; return false; } #endregion #region AttributeExpressionVisitor /// <summary> /// Walk a custom attribute argument bound node and return a TypedConstant. Verify that the expression is a constant expression. /// </summary> private struct AttributeExpressionVisitor { private readonly Binder _binder; public AttributeExpressionVisitor(Binder binder) { _binder = binder; } public ImmutableArray<TypedConstant> VisitArguments(ImmutableArray<BoundExpression> arguments, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool parentHasErrors = false) { var validatedArguments = ImmutableArray<TypedConstant>.Empty; int numArguments = arguments.Length; if (numArguments > 0) { var builder = ArrayBuilder<TypedConstant>.GetInstance(numArguments); foreach (var argument in arguments) { // current argument has errors if parent had errors OR argument.HasErrors. bool curArgumentHasErrors = parentHasErrors || argument.HasAnyErrors; builder.Add(VisitExpression(argument, diagnostics, ref attrHasErrors, curArgumentHasErrors)); } validatedArguments = builder.ToImmutableAndFree(); } return validatedArguments; } public ImmutableArray<KeyValuePair<string, TypedConstant>> VisitNamedArguments(ImmutableArray<BoundAssignmentOperator> arguments, BindingDiagnosticBag diagnostics, ref bool attrHasErrors) { ArrayBuilder<KeyValuePair<string, TypedConstant>>? builder = null; foreach (var argument in arguments) { var kv = VisitNamedArgument(argument, diagnostics, ref attrHasErrors); if (kv.HasValue) { if (builder == null) { builder = ArrayBuilder<KeyValuePair<string, TypedConstant>>.GetInstance(); } builder.Add(kv.Value); } } if (builder == null) { return ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty; } return builder.ToImmutableAndFree(); } private KeyValuePair<String, TypedConstant>? VisitNamedArgument(BoundAssignmentOperator assignment, BindingDiagnosticBag diagnostics, ref bool attrHasErrors) { KeyValuePair<String, TypedConstant>? visitedArgument = null; switch (assignment.Left.Kind) { case BoundKind.FieldAccess: var fa = (BoundFieldAccess)assignment.Left; visitedArgument = new KeyValuePair<String, TypedConstant>(fa.FieldSymbol.Name, VisitExpression(assignment.Right, diagnostics, ref attrHasErrors, assignment.HasAnyErrors)); break; case BoundKind.PropertyAccess: var pa = (BoundPropertyAccess)assignment.Left; visitedArgument = new KeyValuePair<String, TypedConstant>(pa.PropertySymbol.Name, VisitExpression(assignment.Right, diagnostics, ref attrHasErrors, assignment.HasAnyErrors)); break; } return visitedArgument; } // SPEC: An expression E is an attribute-argument-expression if all of the following statements are true: // SPEC: 1) The type of E is an attribute parameter type (§17.1.3). // SPEC: 2) At compile-time, the value of Expression can be resolved to one of the following: // SPEC: a) A constant value. // SPEC: b) A System.Type object. // SPEC: c) A one-dimensional array of attribute-argument-expressions private TypedConstant VisitExpression(BoundExpression node, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) { // Validate Statement 1) of the spec comment above. RoslynDebug.Assert(node.Type is object); var typedConstantKind = node.Type.GetAttributeParameterTypedConstantKind(_binder.Compilation); return VisitExpression(node, typedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors || typedConstantKind == TypedConstantKind.Error); } private TypedConstant VisitExpression(BoundExpression node, TypedConstantKind typedConstantKind, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) { // Validate Statement 2) of the spec comment above. ConstantValue? constantValue = node.ConstantValue; if (constantValue != null) { if (constantValue.IsBad) { typedConstantKind = TypedConstantKind.Error; } ConstantValueUtils.CheckLangVersionForConstantValue(node, diagnostics); return CreateTypedConstant(node, typedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors, simpleValue: constantValue.Value); } switch (node.Kind) { case BoundKind.Conversion: return VisitConversion((BoundConversion)node, diagnostics, ref attrHasErrors, curArgumentHasErrors); case BoundKind.TypeOfOperator: return VisitTypeOfExpression((BoundTypeOfOperator)node, diagnostics, ref attrHasErrors, curArgumentHasErrors); case BoundKind.ArrayCreation: return VisitArrayCreation((BoundArrayCreation)node, diagnostics, ref attrHasErrors, curArgumentHasErrors); default: return CreateTypedConstant(node, TypedConstantKind.Error, diagnostics, ref attrHasErrors, curArgumentHasErrors); } } private TypedConstant VisitConversion(BoundConversion node, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) { Debug.Assert(node.ConstantValue == null); // We have a bound conversion with a non-constant value. // According to statement 2) of the spec comment, this is not a valid attribute argument. // However, native compiler allows conversions to object type if the conversion operand is a valid attribute argument. // See method AttributeHelper::VerifyAttrArg(EXPR *arg). // We will match native compiler's behavior here. // Devdiv Bug #8763: Additionally we allow conversions from array type to object[], provided a conversion exists and each array element is a valid attribute argument. var type = node.Type; var operand = node.Operand; var operandType = operand.Type; if ((object)type != null && operandType is object) { if (type.SpecialType == SpecialType.System_Object || operandType.IsArray() && type.IsArray() && ((ArrayTypeSymbol)type).ElementType.SpecialType == SpecialType.System_Object) { var typedConstantKind = operandType.GetAttributeParameterTypedConstantKind(_binder.Compilation); return VisitExpression(operand, typedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors); } } return CreateTypedConstant(node, TypedConstantKind.Error, diagnostics, ref attrHasErrors, curArgumentHasErrors); } private static TypedConstant VisitTypeOfExpression(BoundTypeOfOperator node, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) { var typeOfArgument = (TypeSymbol?)node.SourceType.Type; // typeof argument is allowed to be: // (a) an unbound type // (b) closed constructed type // typeof argument cannot be an open type if (typeOfArgument is object) // skip this if the argument was an alias symbol { var isValidArgument = true; switch (typeOfArgument.Kind) { case SymbolKind.TypeParameter: // type parameter represents an open type isValidArgument = false; break; default: isValidArgument = typeOfArgument.IsUnboundGenericType() || !typeOfArgument.ContainsTypeParameter(); break; } if (!isValidArgument && !curArgumentHasErrors) { // attribute argument type cannot be an open type Binder.Error(diagnostics, ErrorCode.ERR_AttrArgWithTypeVars, node.Syntax, typeOfArgument.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)); curArgumentHasErrors = true; attrHasErrors = true; } } return CreateTypedConstant(node, TypedConstantKind.Type, diagnostics, ref attrHasErrors, curArgumentHasErrors, simpleValue: node.SourceType.Type); } private TypedConstant VisitArrayCreation(BoundArrayCreation node, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) { ImmutableArray<BoundExpression> bounds = node.Bounds; int boundsCount = bounds.Length; if (boundsCount > 1) { return CreateTypedConstant(node, TypedConstantKind.Error, diagnostics, ref attrHasErrors, curArgumentHasErrors); } var type = (ArrayTypeSymbol)node.Type; var typedConstantKind = type.GetAttributeParameterTypedConstantKind(_binder.Compilation); ImmutableArray<TypedConstant> initializer; if (node.InitializerOpt == null) { if (boundsCount == 0) { initializer = ImmutableArray<TypedConstant>.Empty; } else { if (bounds[0].IsDefaultValue()) { initializer = ImmutableArray<TypedConstant>.Empty; } else { // error: non-constant array creation initializer = ImmutableArray.Create(CreateTypedConstant(node, TypedConstantKind.Error, diagnostics, ref attrHasErrors, curArgumentHasErrors)); } } } else { initializer = VisitArguments(node.InitializerOpt.Initializers, diagnostics, ref attrHasErrors, curArgumentHasErrors); } return CreateTypedConstant(node, typedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors, arrayValue: initializer); } private static TypedConstant CreateTypedConstant(BoundExpression node, TypedConstantKind typedConstantKind, BindingDiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors, object? simpleValue = null, ImmutableArray<TypedConstant> arrayValue = default(ImmutableArray<TypedConstant>)) { var type = node.Type; RoslynDebug.Assert(type is object); if (typedConstantKind != TypedConstantKind.Error && type.ContainsTypeParameter()) { // Devdiv Bug #12636: Constant values of open types should not be allowed in attributes // SPEC ERROR: C# language specification does not explicitly disallow constant values of open types. For e.g. // public class C<T> // { // public enum E { V } // } // // [SomeAttr(C<T>.E.V)] // case (a): Constant value of open type. // [SomeAttr(C<int>.E.V)] // case (b): Constant value of constructed type. // Both expressions 'C<T>.E.V' and 'C<int>.E.V' satisfy the requirements for a valid attribute-argument-expression: // (a) Its type is a valid attribute parameter type as per section 17.1.3 of the specification. // (b) It has a compile time constant value. // However, native compiler disallows both the above cases. // We disallow case (a) as it cannot be serialized correctly, but allow case (b) to compile. typedConstantKind = TypedConstantKind.Error; } if (typedConstantKind == TypedConstantKind.Error) { if (!curArgumentHasErrors) { Binder.Error(diagnostics, ErrorCode.ERR_BadAttributeArgument, node.Syntax); attrHasErrors = true; } return new TypedConstant(type, TypedConstantKind.Error, null); } else if (typedConstantKind == TypedConstantKind.Array) { return new TypedConstant(type, arrayValue); } else { return new TypedConstant(type, typedConstantKind, simpleValue); } } } #endregion #region AnalyzedAttributeArguments private struct AnalyzedAttributeArguments { internal readonly AnalyzedArguments ConstructorArguments; internal readonly ArrayBuilder<BoundAssignmentOperator>? NamedArguments; internal AnalyzedAttributeArguments(AnalyzedArguments constructorArguments, ArrayBuilder<BoundAssignmentOperator>? namedArguments) { this.ConstructorArguments = constructorArguments; this.NamedArguments = namedArguments; } } #endregion } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Options/Providers/ExportOptionProviderAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.Options.Providers { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal sealed class ExportOptionProviderAttribute : ExportAttribute { /// <summary> /// Optional source language for language specific option providers. See <see cref="LanguageNames"/>. /// This will be empty string for language agnostic option providers. /// </summary> public string Language { get; } /// <summary> /// Constructor for language agnostic option providers. /// Use <see cref="ExportOptionProviderAttribute(string)"/> overload for language specific option providers. /// </summary> public ExportOptionProviderAttribute() : base(typeof(IOptionProvider)) { this.Language = string.Empty; } /// <summary> /// Constructor for language specific option providers. /// Use <see cref="ExportOptionProviderAttribute()"/> overload for language agnostic option providers. /// </summary> public ExportOptionProviderAttribute(string language) : base(typeof(IOptionProvider)) { this.Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.Options.Providers { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal sealed class ExportOptionProviderAttribute : ExportAttribute { /// <summary> /// Optional source language for language specific option providers. See <see cref="LanguageNames"/>. /// This will be empty string for language agnostic option providers. /// </summary> public string Language { get; } /// <summary> /// Constructor for language agnostic option providers. /// Use <see cref="ExportOptionProviderAttribute(string)"/> overload for language specific option providers. /// </summary> public ExportOptionProviderAttribute() : base(typeof(IOptionProvider)) { this.Language = string.Empty; } /// <summary> /// Constructor for language specific option providers. /// Use <see cref="ExportOptionProviderAttribute()"/> overload for language agnostic option providers. /// </summary> public ExportOptionProviderAttribute(string language) : base(typeof(IOptionProvider)) { this.Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/xlf/CSharpCompilerExtensionsResources.it.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="it" original="../CSharpCompilerExtensionsResources.resx"> <body> <trans-unit id="Code_block_preferences"> <source>Code-block preferences</source> <target state="translated">Preferenze per blocchi di codice</target> <note /> </trans-unit> <trans-unit id="Expected_string_or_char_literal"> <source>Expected string or char literal</source> <target state="translated">È previsto un valore letterale di tipo stringa o char</target> <note /> </trans-unit> <trans-unit id="Expression_bodied_members"> <source>Expression-bodied members</source> <target state="translated">Membri con corpo di espressione</target> <note /> </trans-unit> <trans-unit id="Null_checking_preferences"> <source>Null-checking preferences</source> <target state="translated">Preference per controllo valori Null</target> <note /> </trans-unit> <trans-unit id="Pattern_matching_preferences"> <source>Pattern matching preferences</source> <target state="translated">Preferenze per criteri di ricerca</target> <note /> </trans-unit> <trans-unit id="_0_1_is_not_supported_in_this_version"> <source>'{0}.{1}' is not supported in this version</source> <target state="translated">'{0}.{1}' non è supportato in questa versione</target> <note>{0}: A type name {1}: A member name</note> </trans-unit> <trans-unit id="using_directive_preferences"> <source>'using' directive preferences</source> <target state="translated">Preferenze per direttive 'using'</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="var_preferences"> <source>var preferences</source> <target state="translated">Preferenze per var</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="it" original="../CSharpCompilerExtensionsResources.resx"> <body> <trans-unit id="Code_block_preferences"> <source>Code-block preferences</source> <target state="translated">Preferenze per blocchi di codice</target> <note /> </trans-unit> <trans-unit id="Expected_string_or_char_literal"> <source>Expected string or char literal</source> <target state="translated">È previsto un valore letterale di tipo stringa o char</target> <note /> </trans-unit> <trans-unit id="Expression_bodied_members"> <source>Expression-bodied members</source> <target state="translated">Membri con corpo di espressione</target> <note /> </trans-unit> <trans-unit id="Null_checking_preferences"> <source>Null-checking preferences</source> <target state="translated">Preference per controllo valori Null</target> <note /> </trans-unit> <trans-unit id="Pattern_matching_preferences"> <source>Pattern matching preferences</source> <target state="translated">Preferenze per criteri di ricerca</target> <note /> </trans-unit> <trans-unit id="_0_1_is_not_supported_in_this_version"> <source>'{0}.{1}' is not supported in this version</source> <target state="translated">'{0}.{1}' non è supportato in questa versione</target> <note>{0}: A type name {1}: A member name</note> </trans-unit> <trans-unit id="using_directive_preferences"> <source>'using' directive preferences</source> <target state="translated">Preferenze per direttive 'using'</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="var_preferences"> <source>var preferences</source> <target state="translated">Preferenze per var</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Emit; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting { /// <summary> /// Represents a parameter of a RetargetingMethodSymbol. Essentially this is a wrapper around /// another ParameterSymbol that is responsible for retargeting symbols from one assembly to another. /// It can retarget symbols for multiple assemblies at the same time. /// </summary> internal abstract class RetargetingParameterSymbol : WrappedParameterSymbol { private ImmutableArray<CustomModifier> _lazyRefCustomModifiers; /// <summary> /// Retargeted custom attributes /// </summary> private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes; protected RetargetingParameterSymbol(ParameterSymbol underlyingParameter) : base(underlyingParameter) { Debug.Assert(!(underlyingParameter is RetargetingParameterSymbol)); } protected abstract RetargetingModuleSymbol RetargetingModule { get; } public sealed override TypeWithAnnotations TypeWithAnnotations { get { return this.RetargetingModule.RetargetingTranslator.Retarget(_underlyingParameter.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); } } public sealed override ImmutableArray<CustomModifier> RefCustomModifiers { get { return RetargetingModule.RetargetingTranslator.RetargetModifiers(_underlyingParameter.RefCustomModifiers, ref _lazyRefCustomModifiers); } } public sealed override Symbol ContainingSymbol { get { return this.RetargetingModule.RetargetingTranslator.Retarget(_underlyingParameter.ContainingSymbol); } } public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.RetargetingModule.RetargetingTranslator.GetRetargetedAttributes(_underlyingParameter.GetAttributes(), ref _lazyCustomAttributes); } internal sealed override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { return this.RetargetingModule.RetargetingTranslator.RetargetAttributes(_underlyingParameter.GetCustomAttributesToEmit(moduleBuilder)); } public sealed override AssemblySymbol ContainingAssembly { get { return this.RetargetingModule.ContainingAssembly; } } internal sealed override ModuleSymbol ContainingModule { get { return this.RetargetingModule; } } internal sealed override bool HasMetadataConstantValue { get { return _underlyingParameter.HasMetadataConstantValue; } } internal sealed override bool IsMarshalledExplicitly { get { return _underlyingParameter.IsMarshalledExplicitly; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { return this.RetargetingModule.RetargetingTranslator.Retarget(_underlyingParameter.MarshallingInformation); } } internal override ImmutableArray<byte> MarshallingDescriptor { get { return _underlyingParameter.MarshallingDescriptor; } } internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness { get { return null; } } internal sealed override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => _underlyingParameter.InterpolatedStringHandlerArgumentIndexes; internal override bool HasInterpolatedStringHandlerArgumentError => _underlyingParameter.HasInterpolatedStringHandlerArgumentError; } internal sealed class RetargetingMethodParameterSymbol : RetargetingParameterSymbol { /// <summary> /// Owning RetargetingMethodSymbol. /// </summary> private readonly RetargetingMethodSymbol _retargetingMethod; public RetargetingMethodParameterSymbol(RetargetingMethodSymbol retargetingMethod, ParameterSymbol underlyingParameter) : base(underlyingParameter) { Debug.Assert((object)retargetingMethod != null); _retargetingMethod = retargetingMethod; } protected override RetargetingModuleSymbol RetargetingModule { get { return _retargetingMethod.RetargetingModule; } } } internal sealed class RetargetingPropertyParameterSymbol : RetargetingParameterSymbol { /// <summary> /// Owning RetargetingPropertySymbol. /// </summary> private readonly RetargetingPropertySymbol _retargetingProperty; public RetargetingPropertyParameterSymbol(RetargetingPropertySymbol retargetingProperty, ParameterSymbol underlyingParameter) : base(underlyingParameter) { Debug.Assert((object)retargetingProperty != null); _retargetingProperty = retargetingProperty; } protected override RetargetingModuleSymbol RetargetingModule { get { return _retargetingProperty.RetargetingModule; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Emit; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting { /// <summary> /// Represents a parameter of a RetargetingMethodSymbol. Essentially this is a wrapper around /// another ParameterSymbol that is responsible for retargeting symbols from one assembly to another. /// It can retarget symbols for multiple assemblies at the same time. /// </summary> internal abstract class RetargetingParameterSymbol : WrappedParameterSymbol { private ImmutableArray<CustomModifier> _lazyRefCustomModifiers; /// <summary> /// Retargeted custom attributes /// </summary> private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes; protected RetargetingParameterSymbol(ParameterSymbol underlyingParameter) : base(underlyingParameter) { Debug.Assert(!(underlyingParameter is RetargetingParameterSymbol)); } protected abstract RetargetingModuleSymbol RetargetingModule { get; } public sealed override TypeWithAnnotations TypeWithAnnotations { get { return this.RetargetingModule.RetargetingTranslator.Retarget(_underlyingParameter.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); } } public sealed override ImmutableArray<CustomModifier> RefCustomModifiers { get { return RetargetingModule.RetargetingTranslator.RetargetModifiers(_underlyingParameter.RefCustomModifiers, ref _lazyRefCustomModifiers); } } public sealed override Symbol ContainingSymbol { get { return this.RetargetingModule.RetargetingTranslator.Retarget(_underlyingParameter.ContainingSymbol); } } public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.RetargetingModule.RetargetingTranslator.GetRetargetedAttributes(_underlyingParameter.GetAttributes(), ref _lazyCustomAttributes); } internal sealed override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder) { return this.RetargetingModule.RetargetingTranslator.RetargetAttributes(_underlyingParameter.GetCustomAttributesToEmit(moduleBuilder)); } public sealed override AssemblySymbol ContainingAssembly { get { return this.RetargetingModule.ContainingAssembly; } } internal sealed override ModuleSymbol ContainingModule { get { return this.RetargetingModule; } } internal sealed override bool HasMetadataConstantValue { get { return _underlyingParameter.HasMetadataConstantValue; } } internal sealed override bool IsMarshalledExplicitly { get { return _underlyingParameter.IsMarshalledExplicitly; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { return this.RetargetingModule.RetargetingTranslator.Retarget(_underlyingParameter.MarshallingInformation); } } internal override ImmutableArray<byte> MarshallingDescriptor { get { return _underlyingParameter.MarshallingDescriptor; } } internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness { get { return null; } } internal sealed override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => _underlyingParameter.InterpolatedStringHandlerArgumentIndexes; internal override bool HasInterpolatedStringHandlerArgumentError => _underlyingParameter.HasInterpolatedStringHandlerArgumentError; } internal sealed class RetargetingMethodParameterSymbol : RetargetingParameterSymbol { /// <summary> /// Owning RetargetingMethodSymbol. /// </summary> private readonly RetargetingMethodSymbol _retargetingMethod; public RetargetingMethodParameterSymbol(RetargetingMethodSymbol retargetingMethod, ParameterSymbol underlyingParameter) : base(underlyingParameter) { Debug.Assert((object)retargetingMethod != null); _retargetingMethod = retargetingMethod; } protected override RetargetingModuleSymbol RetargetingModule { get { return _retargetingMethod.RetargetingModule; } } } internal sealed class RetargetingPropertyParameterSymbol : RetargetingParameterSymbol { /// <summary> /// Owning RetargetingPropertySymbol. /// </summary> private readonly RetargetingPropertySymbol _retargetingProperty; public RetargetingPropertyParameterSymbol(RetargetingPropertySymbol retargetingProperty, ParameterSymbol underlyingParameter) : base(underlyingParameter) { Debug.Assert((object)retargetingProperty != null); _retargetingProperty = retargetingProperty; } protected override RetargetingModuleSymbol RetargetingModule { get { return _retargetingProperty.RetargetingModule; } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/AbstractCodeType.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { public abstract class AbstractCodeType : AbstractCodeMember, EnvDTE.CodeType { internal AbstractCodeType( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } internal AbstractCodeType( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } private SyntaxNode GetNamespaceOrTypeNode() { return LookupNode().Ancestors() .Where(n => CodeModelService.IsNamespace(n) || CodeModelService.IsType(n)) .FirstOrDefault(); } private SyntaxNode GetNamespaceNode() { return LookupNode().Ancestors() .Where(n => CodeModelService.IsNamespace(n)) .FirstOrDefault(); } internal INamedTypeSymbol LookupTypeSymbol() => (INamedTypeSymbol)LookupSymbol(); protected override object GetExtenderNames() => CodeModelService.GetTypeExtenderNames(); protected override object GetExtender(string name) => CodeModelService.GetTypeExtender(name, this); public override object Parent { get { var containingNamespaceOrType = GetNamespaceOrTypeNode(); return containingNamespaceOrType != null ? (object)FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(containingNamespaceOrType) : this.FileCodeModel; } } public override EnvDTE.CodeElements Children { get { return UnionCollection.Create(this.State, this, (ICodeElements)this.Attributes, (ICodeElements)InheritsImplementsCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey), (ICodeElements)this.Members); } } public EnvDTE.CodeElements Bases { get { return BasesCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey, interfaces: false); } } public EnvDTE80.vsCMDataTypeKind DataTypeKind { get { return CodeModelService.GetDataTypeKind(LookupNode(), (INamedTypeSymbol)LookupSymbol()); } set { UpdateNode(FileCodeModel.UpdateDataTypeKind, value); } } public EnvDTE.CodeElements DerivedTypes { get { throw new NotImplementedException(); } } public EnvDTE.CodeElements ImplementedInterfaces { get { return BasesCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey, interfaces: true); } } public EnvDTE.CodeElements Members { get { return TypeCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey); } } public EnvDTE.CodeNamespace Namespace { get { var namespaceNode = GetNamespaceNode(); return namespaceNode != null ? FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeNamespace>(namespaceNode) : null; } } /// <returns>True if the current type inherits from or equals the type described by the /// given full name.</returns> /// <remarks>Equality is included in the check as per Dev10 Bug #725630</remarks> public bool get_IsDerivedFrom(string fullName) { var currentType = LookupTypeSymbol(); if (currentType == null) { return false; } var baseType = GetSemanticModel().Compilation.GetTypeByMetadataName(fullName); if (baseType == null) { return false; } return currentType.InheritsFromOrEquals(baseType); } public override bool IsCodeType { get { return true; } } public void RemoveMember(object element) { // Is this an EnvDTE.CodeElement that we created? If so, try to get the underlying code element object. var abstractCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (abstractCodeElement == null) { if (element is EnvDTE.CodeElement codeElement) { // Is at least an EnvDTE.CodeElement? If so, try to retrieve it from the Members collection by name. // Note: This might throw an ArgumentException if the name isn't found in the collection. abstractCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Members.Item(codeElement.Name)); } else if (element is string || element is int) { // Is this a string or int? If so, try to retrieve it from the Members collection. Again, this will // throw an ArgumentException if the name or index isn't found in the collection. abstractCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Members.Item(element)); } } if (abstractCodeElement == null) { throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element)); } abstractCodeElement.Delete(); } public EnvDTE.CodeElement AddBase(object @base, object position) { return FileCodeModel.EnsureEditor(() => { FileCodeModel.AddBase(LookupNode(), @base, position); var codeElements = this.Bases as ICodeElements; var hr = codeElements.Item(1, out var element); if (ErrorHandler.Succeeded(hr)) { return element; } return null; }); } public EnvDTE.CodeInterface AddImplementedInterface(object @base, object position) { return FileCodeModel.EnsureEditor(() => { var name = FileCodeModel.AddImplementedInterface(LookupNode(), @base, position); var codeElements = this.ImplementedInterfaces as ICodeElements; var hr = codeElements.Item(name, out var element); if (ErrorHandler.Succeeded(hr)) { return element as EnvDTE.CodeInterface; } return null; }); } public void RemoveBase(object element) { FileCodeModel.EnsureEditor(() => { FileCodeModel.RemoveBase(LookupNode(), element); }); } public void RemoveInterface(object element) { FileCodeModel.EnsureEditor(() => { FileCodeModel.RemoveImplementedInterface(LookupNode(), element); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { public abstract class AbstractCodeType : AbstractCodeMember, EnvDTE.CodeType { internal AbstractCodeType( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } internal AbstractCodeType( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } private SyntaxNode GetNamespaceOrTypeNode() { return LookupNode().Ancestors() .Where(n => CodeModelService.IsNamespace(n) || CodeModelService.IsType(n)) .FirstOrDefault(); } private SyntaxNode GetNamespaceNode() { return LookupNode().Ancestors() .Where(n => CodeModelService.IsNamespace(n)) .FirstOrDefault(); } internal INamedTypeSymbol LookupTypeSymbol() => (INamedTypeSymbol)LookupSymbol(); protected override object GetExtenderNames() => CodeModelService.GetTypeExtenderNames(); protected override object GetExtender(string name) => CodeModelService.GetTypeExtender(name, this); public override object Parent { get { var containingNamespaceOrType = GetNamespaceOrTypeNode(); return containingNamespaceOrType != null ? (object)FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(containingNamespaceOrType) : this.FileCodeModel; } } public override EnvDTE.CodeElements Children { get { return UnionCollection.Create(this.State, this, (ICodeElements)this.Attributes, (ICodeElements)InheritsImplementsCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey), (ICodeElements)this.Members); } } public EnvDTE.CodeElements Bases { get { return BasesCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey, interfaces: false); } } public EnvDTE80.vsCMDataTypeKind DataTypeKind { get { return CodeModelService.GetDataTypeKind(LookupNode(), (INamedTypeSymbol)LookupSymbol()); } set { UpdateNode(FileCodeModel.UpdateDataTypeKind, value); } } public EnvDTE.CodeElements DerivedTypes { get { throw new NotImplementedException(); } } public EnvDTE.CodeElements ImplementedInterfaces { get { return BasesCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey, interfaces: true); } } public EnvDTE.CodeElements Members { get { return TypeCollection.Create(this.State, this, this.FileCodeModel, this.NodeKey); } } public EnvDTE.CodeNamespace Namespace { get { var namespaceNode = GetNamespaceNode(); return namespaceNode != null ? FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeNamespace>(namespaceNode) : null; } } /// <returns>True if the current type inherits from or equals the type described by the /// given full name.</returns> /// <remarks>Equality is included in the check as per Dev10 Bug #725630</remarks> public bool get_IsDerivedFrom(string fullName) { var currentType = LookupTypeSymbol(); if (currentType == null) { return false; } var baseType = GetSemanticModel().Compilation.GetTypeByMetadataName(fullName); if (baseType == null) { return false; } return currentType.InheritsFromOrEquals(baseType); } public override bool IsCodeType { get { return true; } } public void RemoveMember(object element) { // Is this an EnvDTE.CodeElement that we created? If so, try to get the underlying code element object. var abstractCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (abstractCodeElement == null) { if (element is EnvDTE.CodeElement codeElement) { // Is at least an EnvDTE.CodeElement? If so, try to retrieve it from the Members collection by name. // Note: This might throw an ArgumentException if the name isn't found in the collection. abstractCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Members.Item(codeElement.Name)); } else if (element is string || element is int) { // Is this a string or int? If so, try to retrieve it from the Members collection. Again, this will // throw an ArgumentException if the name or index isn't found in the collection. abstractCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.Members.Item(element)); } } if (abstractCodeElement == null) { throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element)); } abstractCodeElement.Delete(); } public EnvDTE.CodeElement AddBase(object @base, object position) { return FileCodeModel.EnsureEditor(() => { FileCodeModel.AddBase(LookupNode(), @base, position); var codeElements = this.Bases as ICodeElements; var hr = codeElements.Item(1, out var element); if (ErrorHandler.Succeeded(hr)) { return element; } return null; }); } public EnvDTE.CodeInterface AddImplementedInterface(object @base, object position) { return FileCodeModel.EnsureEditor(() => { var name = FileCodeModel.AddImplementedInterface(LookupNode(), @base, position); var codeElements = this.ImplementedInterfaces as ICodeElements; var hr = codeElements.Item(name, out var element); if (ErrorHandler.Succeeded(hr)) { return element as EnvDTE.CodeInterface; } return null; }); } public void RemoveBase(object element) { FileCodeModel.EnsureEditor(() => { FileCodeModel.RemoveBase(LookupNode(), element); }); } public void RemoveInterface(object element) { FileCodeModel.EnsureEditor(() => { FileCodeModel.RemoveImplementedInterface(LookupNode(), element); }); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseIsNullCheckForReferenceEqualsDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.LanguageServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.UseIsNullCheck; namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpUseIsNullCheckForReferenceEqualsDiagnosticAnalyzer : AbstractUseIsNullCheckForReferenceEqualsDiagnosticAnalyzer<SyntaxKind> { public CSharpUseIsNullCheckForReferenceEqualsDiagnosticAnalyzer() : base(CSharpAnalyzersResources.Use_is_null_check) { } protected override bool IsLanguageVersionSupported(Compilation compilation) => ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp7; protected override bool IsUnconstrainedGenericSupported(Compilation compilation) => ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp8; protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.UseIsNullCheck; namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpUseIsNullCheckForReferenceEqualsDiagnosticAnalyzer : AbstractUseIsNullCheckForReferenceEqualsDiagnosticAnalyzer<SyntaxKind> { public CSharpUseIsNullCheckForReferenceEqualsDiagnosticAnalyzer() : base(CSharpAnalyzersResources.Use_is_null_check) { } protected override bool IsLanguageVersionSupported(Compilation compilation) => ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp7; protected override bool IsUnconstrainedGenericSupported(Compilation compilation) => ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp8; protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Impl/SolutionExplorer/AnalyzerNodeSetup.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.ComponentModel.Design; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { [Export(typeof(IAnalyzerNodeSetup))] internal sealed class AnalyzerNodeSetup : IAnalyzerNodeSetup { private readonly AnalyzerItemsTracker _analyzerTracker; private readonly AnalyzersCommandHandler _analyzerCommandHandler; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public AnalyzerNodeSetup(AnalyzerItemsTracker analyzerTracker, AnalyzersCommandHandler analyzerCommandHandler) { _analyzerTracker = analyzerTracker; _analyzerCommandHandler = analyzerCommandHandler; } public void Initialize(IServiceProvider serviceProvider) { _analyzerTracker.Register(); _analyzerCommandHandler.Initialize((IMenuCommandService)serviceProvider.GetService(typeof(IMenuCommandService))); } public void Unregister() { _analyzerTracker.Unregister(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.ComponentModel.Design; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { [Export(typeof(IAnalyzerNodeSetup))] internal sealed class AnalyzerNodeSetup : IAnalyzerNodeSetup { private readonly AnalyzerItemsTracker _analyzerTracker; private readonly AnalyzersCommandHandler _analyzerCommandHandler; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public AnalyzerNodeSetup(AnalyzerItemsTracker analyzerTracker, AnalyzersCommandHandler analyzerCommandHandler) { _analyzerTracker = analyzerTracker; _analyzerCommandHandler = analyzerCommandHandler; } public void Initialize(IServiceProvider serviceProvider) { _analyzerTracker.Register(); _analyzerCommandHandler.Initialize((IMenuCommandService)serviceProvider.GetService(typeof(IMenuCommandService))); } public void Unregister() { _analyzerTracker.Unregister(); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Text/xlf/TextEditorResources.pt-BR.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="pt-BR" original="../TextEditorResources.resx"> <body> <trans-unit id="The_snapshot_does_not_contain_the_specified_position"> <source>The snapshot does not contain the specified position.</source> <target state="translated">O instantâneo não contém a posição especificada.</target> <note /> </trans-unit> <trans-unit id="The_snapshot_does_not_contain_the_specified_span"> <source>The snapshot does not contain the specified span.</source> <target state="translated">O instantâneo não contém o intervalo especificado.</target> <note /> </trans-unit> <trans-unit id="textContainer_is_not_a_SourceTextContainer_that_was_created_from_an_ITextBuffer"> <source>textContainer is not a SourceTextContainer that was created from an ITextBuffer.</source> <target state="translated">textContainer não é um SourceTextContainer que foi criado por meio de um ITextBuffer.</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="pt-BR" original="../TextEditorResources.resx"> <body> <trans-unit id="The_snapshot_does_not_contain_the_specified_position"> <source>The snapshot does not contain the specified position.</source> <target state="translated">O instantâneo não contém a posição especificada.</target> <note /> </trans-unit> <trans-unit id="The_snapshot_does_not_contain_the_specified_span"> <source>The snapshot does not contain the specified span.</source> <target state="translated">O instantâneo não contém o intervalo especificado.</target> <note /> </trans-unit> <trans-unit id="textContainer_is_not_a_SourceTextContainer_that_was_created_from_an_ITextBuffer"> <source>textContainer is not a SourceTextContainer that was created from an ITextBuffer.</source> <target state="translated">textContainer não é um SourceTextContainer que foi criado por meio de um ITextBuffer.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.Formatting.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ChangeSignature; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_KeepCountsPerLine() { var markup = @" class C { void $$Method(int a, int b, int c, int d, int e, int f) { Method(1, 2, 3, 4, 5, 6); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(5), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(3), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" class C { void Method(int f, int e, int d, byte bb, int c, int b, int a) { Method(6, 5, 4, 34, 3, 2, 1); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(28156, "https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_KeepTrivia() { var markup = @" class C { void $$Method( int a, int b, int c, int d, int e, int f) { Method( 1, 2, 3, 4, 5, 6); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(3), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(5)}; var expectedUpdatedCode = @" class C { void Method( int b, int c, int d, byte bb, int e, int f) { Method( 2, 3, 4, 34, 5, 6); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(28156, "https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_KeepTrivia_WithArgumentNames() { var markup = @" class C { void $$Method( int a, int b, int c, int d, int e, int f) { Method( a: 1, b: 2, c: 3, d: 4, e: 5, f: 6); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(3), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(5)}; var expectedUpdatedCode = @" class C { void Method( int b, int c, int d, byte bb, int e, int f) { Method( b: 2, c: 3, d: 4, bb: 34, e: 5, f: 6); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_Method() { var markup = @" class C { void $$Method(int a, int b) { Method(1, 2); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" class C { void Method(int b, byte bb, int a) { Method(2, 34, 1); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_Constructor() { var markup = @" class SomeClass { $$SomeClass(int a, int b) { new SomeClass(1, 2); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" class SomeClass { SomeClass(int b, byte bb, int a) { new SomeClass(2, 34, 1); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_Indexer() { var markup = @" class SomeClass { public int $$this[int a, int b] { get { return new SomeClass()[1, 2]; } } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" class SomeClass { public int this[int b, byte bb, int a] { get { return new SomeClass()[2, 34, 1]; } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_Delegate() { var markup = @" class SomeClass { delegate void $$MyDelegate(int a, int b); void M(int a, int b) { var myDel = new MyDelegate(M); myDel(1, 2); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" class SomeClass { delegate void MyDelegate(int b, byte bb, int a); void M(int b, byte bb, int a) { var myDel = new MyDelegate(M); myDel(2, 34, 1); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_AnonymousMethod() { var markup = @" class SomeClass { delegate void $$MyDelegate(int a, int b); void M() { MyDelegate myDel = delegate (int x, int y) { // Nothing }; } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" class SomeClass { delegate void MyDelegate(int b, byte bb, int a); void M() { MyDelegate myDel = delegate (int y, byte bb, int x) { // Nothing }; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_ConstructorInitializers() { var markup = @" class B { public $$B(int x, int y) { } public B() : this(1, 2) { } } class D : B { public D() : base(1, 2) { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" class B { public B(int y, byte bb, int x) { } public B() : this(2, 34, 1) { } } class D : B { public D() : base(2, 34, 1) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_Attribute() { var markup = @" [Custom(1, 2)] class CustomAttribute : System.Attribute { public $$CustomAttribute(int x, int y) { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" [Custom(2, 34, 1)] class CustomAttribute : System.Attribute { public CustomAttribute(int y, byte bb, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(28156, "https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_Attribute_KeepTrivia() { var markup = @" [Custom( 1, 2)] class CustomAttribute : System.Attribute { public $$CustomAttribute(int x, int y) { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte") }; var expectedUpdatedCode = @" [Custom( 2, 34)] class CustomAttribute : System.Attribute { public CustomAttribute(int y, byte bb) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(28156, "https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_Attribute_KeepTrivia_RemovingSecond() { var markup = @" [Custom( 1, 2)] class CustomAttribute : System.Attribute { public $$CustomAttribute(int x, int y) { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte")}; var expectedUpdatedCode = @" [Custom( 1, 34)] class CustomAttribute : System.Attribute { public CustomAttribute(int x, byte bb) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(28156, "https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_Attribute_KeepTrivia_RemovingBothAddingNew() { var markup = @" [Custom( 1, 2)] class CustomAttribute : System.Attribute { public $$CustomAttribute(int x, int y) { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte")}; var expectedUpdatedCode = @" [Custom( 34)] class CustomAttribute : System.Attribute { public CustomAttribute(byte bb) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(28156, "https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_Attribute_KeepTrivia_RemovingBeforeNewlineComma() { var markup = @" [Custom(1 , 2, 3)] class CustomAttribute : System.Attribute { public $$CustomAttribute(int x, int y, int z) { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(2)}; var expectedUpdatedCode = @" [Custom(2, 34, 3)] class CustomAttribute : System.Attribute { public CustomAttribute(int y, byte bb, int z) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [WorkItem(946220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946220")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_LambdaAsArgument() { var markup = @"class C { void M(System.Action<int, int> f, int z$$) { M((x, y) => System.Console.WriteLine(x + y), 5); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte")}; var expectedUpdatedCode = @"class C { void M(System.Action<int, int> f, byte bb) { M((x, y) => System.Console.WriteLine(x + y), 34); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [WorkItem(46595, "https://github.com/dotnet/roslyn/issues/46595")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_PreserveIndentBraces() { var markup = @"public class C { public void M$$() { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "a", CallSiteKind.Value, "12345"), "int")}; var expectedUpdatedCode = @"public class C { public void M(int a) { } }"; await TestChangeSignatureViaCommandAsync( LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, options: Option(CSharpFormattingOptions2.IndentBraces, true)); } [WorkItem(46595, "https://github.com/dotnet/roslyn/issues/46595")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_PreserveIndentBraces_Editorconfig() { var markup = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> public class C { public void M$$() { } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_indent_braces = true </AnalyzerConfigDocument> </Project> </Workspace>"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "a", CallSiteKind.Value, "12345"), "int")}; var expectedUpdatedCode = @" public class C { public void M(int a) { } } "; await TestChangeSignatureViaCommandAsync("XML", markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ChangeSignature; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_KeepCountsPerLine() { var markup = @" class C { void $$Method(int a, int b, int c, int d, int e, int f) { Method(1, 2, 3, 4, 5, 6); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(5), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(3), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" class C { void Method(int f, int e, int d, byte bb, int c, int b, int a) { Method(6, 5, 4, 34, 3, 2, 1); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(28156, "https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_KeepTrivia() { var markup = @" class C { void $$Method( int a, int b, int c, int d, int e, int f) { Method( 1, 2, 3, 4, 5, 6); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(3), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(5)}; var expectedUpdatedCode = @" class C { void Method( int b, int c, int d, byte bb, int e, int f) { Method( 2, 3, 4, 34, 5, 6); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(28156, "https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_KeepTrivia_WithArgumentNames() { var markup = @" class C { void $$Method( int a, int b, int c, int d, int e, int f) { Method( a: 1, b: 2, c: 3, d: 4, e: 5, f: 6); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(2), new AddedParameterOrExistingIndex(3), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(4), new AddedParameterOrExistingIndex(5)}; var expectedUpdatedCode = @" class C { void Method( int b, int c, int d, byte bb, int e, int f) { Method( b: 2, c: 3, d: 4, bb: 34, e: 5, f: 6); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_Method() { var markup = @" class C { void $$Method(int a, int b) { Method(1, 2); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" class C { void Method(int b, byte bb, int a) { Method(2, 34, 1); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_Constructor() { var markup = @" class SomeClass { $$SomeClass(int a, int b) { new SomeClass(1, 2); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" class SomeClass { SomeClass(int b, byte bb, int a) { new SomeClass(2, 34, 1); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_Indexer() { var markup = @" class SomeClass { public int $$this[int a, int b] { get { return new SomeClass()[1, 2]; } } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" class SomeClass { public int this[int b, byte bb, int a] { get { return new SomeClass()[2, 34, 1]; } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_Delegate() { var markup = @" class SomeClass { delegate void $$MyDelegate(int a, int b); void M(int a, int b) { var myDel = new MyDelegate(M); myDel(1, 2); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" class SomeClass { delegate void MyDelegate(int b, byte bb, int a); void M(int b, byte bb, int a) { var myDel = new MyDelegate(M); myDel(2, 34, 1); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_AnonymousMethod() { var markup = @" class SomeClass { delegate void $$MyDelegate(int a, int b); void M() { MyDelegate myDel = delegate (int x, int y) { // Nothing }; } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" class SomeClass { delegate void MyDelegate(int b, byte bb, int a); void M() { MyDelegate myDel = delegate (int y, byte bb, int x) { // Nothing }; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_ConstructorInitializers() { var markup = @" class B { public $$B(int x, int y) { } public B() : this(1, 2) { } } class D : B { public D() : base(1, 2) { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" class B { public B(int y, byte bb, int x) { } public B() : this(2, 34, 1) { } } class D : B { public D() : base(2, 34, 1) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_Attribute() { var markup = @" [Custom(1, 2)] class CustomAttribute : System.Attribute { public $$CustomAttribute(int x, int y) { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(0)}; var expectedUpdatedCode = @" [Custom(2, 34, 1)] class CustomAttribute : System.Attribute { public CustomAttribute(int y, byte bb, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(28156, "https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_Attribute_KeepTrivia() { var markup = @" [Custom( 1, 2)] class CustomAttribute : System.Attribute { public $$CustomAttribute(int x, int y) { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte") }; var expectedUpdatedCode = @" [Custom( 2, 34)] class CustomAttribute : System.Attribute { public CustomAttribute(int y, byte bb) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(28156, "https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_Attribute_KeepTrivia_RemovingSecond() { var markup = @" [Custom( 1, 2)] class CustomAttribute : System.Attribute { public $$CustomAttribute(int x, int y) { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte")}; var expectedUpdatedCode = @" [Custom( 1, 34)] class CustomAttribute : System.Attribute { public CustomAttribute(int x, byte bb) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(28156, "https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_Attribute_KeepTrivia_RemovingBothAddingNew() { var markup = @" [Custom( 1, 2)] class CustomAttribute : System.Attribute { public $$CustomAttribute(int x, int y) { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte")}; var expectedUpdatedCode = @" [Custom( 34)] class CustomAttribute : System.Attribute { public CustomAttribute(byte bb) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(28156, "https://github.com/dotnet/roslyn/issues/28156")] public async Task AddParameter_Formatting_Attribute_KeepTrivia_RemovingBeforeNewlineComma() { var markup = @" [Custom(1 , 2, 3)] class CustomAttribute : System.Attribute { public $$CustomAttribute(int x, int y, int z) { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(1), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte"), new AddedParameterOrExistingIndex(2)}; var expectedUpdatedCode = @" [Custom(2, 34, 3)] class CustomAttribute : System.Attribute { public CustomAttribute(int y, byte bb, int z) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [WorkItem(946220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946220")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_LambdaAsArgument() { var markup = @"class C { void M(System.Action<int, int> f, int z$$) { M((x, y) => System.Console.WriteLine(x + y), 5); } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(0), new AddedParameterOrExistingIndex(new AddedParameter(null, "byte", "bb", CallSiteKind.Value, "34"), "byte")}; var expectedUpdatedCode = @"class C { void M(System.Action<int, int> f, byte bb) { M((x, y) => System.Console.WriteLine(x + y), 34); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } [WorkItem(46595, "https://github.com/dotnet/roslyn/issues/46595")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_PreserveIndentBraces() { var markup = @"public class C { public void M$$() { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "a", CallSiteKind.Value, "12345"), "int")}; var expectedUpdatedCode = @"public class C { public void M(int a) { } }"; await TestChangeSignatureViaCommandAsync( LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode, options: Option(CSharpFormattingOptions2.IndentBraces, true)); } [WorkItem(46595, "https://github.com/dotnet/roslyn/issues/46595")] [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameter_Formatting_PreserveIndentBraces_Editorconfig() { var markup = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> public class C { public void M$$() { } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_indent_braces = true </AnalyzerConfigDocument> </Project> </Workspace>"; var updatedSignature = new[] { new AddedParameterOrExistingIndex(new AddedParameter(null, "int", "a", CallSiteKind.Value, "12345"), "int")}; var expectedUpdatedCode = @" public class C { public void M(int a) { } } "; await TestChangeSignatureViaCommandAsync("XML", markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: expectedUpdatedCode); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Remote/Core/SolutionAsset.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Represents a part of solution snapshot along with its checksum. /// </summary> internal sealed class SolutionAsset { public static readonly SolutionAsset Null = new SolutionAsset(value: null, Checksum.Null, WellKnownSynchronizationKind.Null); /// <summary> /// Indicates what kind of object it. /// /// Used in tranportation framework and deserialization service /// to hand shake how to send over data and deserialize serialized data. /// </summary> public readonly WellKnownSynchronizationKind Kind; /// <summary> /// Checksum of <see cref="Value"/>. /// </summary> public readonly Checksum Checksum; public readonly object? Value; public SolutionAsset(object? value, Checksum checksum, WellKnownSynchronizationKind kind) { // SolutionAsset is not allowed to hold strong references to SourceText. SerializableSourceText is used // instead to allow data to be released from process address space when it is also held in temporary // storage. // https://github.com/dotnet/roslyn/issues/43802 Contract.ThrowIfTrue(kind is WellKnownSynchronizationKind.SourceText); Checksum = checksum; Kind = kind; Value = value; } public SolutionAsset(Checksum checksum, object value) : this(value, checksum, value.GetWellKnownSynchronizationKind()) { } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Represents a part of solution snapshot along with its checksum. /// </summary> internal sealed class SolutionAsset { public static readonly SolutionAsset Null = new SolutionAsset(value: null, Checksum.Null, WellKnownSynchronizationKind.Null); /// <summary> /// Indicates what kind of object it. /// /// Used in tranportation framework and deserialization service /// to hand shake how to send over data and deserialize serialized data. /// </summary> public readonly WellKnownSynchronizationKind Kind; /// <summary> /// Checksum of <see cref="Value"/>. /// </summary> public readonly Checksum Checksum; public readonly object? Value; public SolutionAsset(object? value, Checksum checksum, WellKnownSynchronizationKind kind) { // SolutionAsset is not allowed to hold strong references to SourceText. SerializableSourceText is used // instead to allow data to be released from process address space when it is also held in temporary // storage. // https://github.com/dotnet/roslyn/issues/43802 Contract.ThrowIfTrue(kind is WellKnownSynchronizationKind.SourceText); Checksum = checksum; Kind = kind; Value = value; } public SolutionAsset(Checksum checksum, object value) : this(value, checksum, value.GetWellKnownSynchronizationKind()) { } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/CodeAnalysisTest/Diagnostics/SarifV2ErrorLoggerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.IO; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { // See also VB and C# command line unit tests for additional coverage. [Trait(Traits.Feature, Traits.Features.SarifErrorLogging)] public class SarifV2ErrorLoggerTests : SarifErrorLoggerTests { internal override SarifErrorLogger CreateLogger( Stream stream, string toolName, string toolFileVersion, Version toolAssemblyVersion, CultureInfo culture) { return new SarifV2ErrorLogger(stream, toolName, toolFileVersion, toolAssemblyVersion, culture); } protected override string ExpectedOutputForAdditionalLocationsAsRelatedLocations => @"{ ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"", ""version"": ""2.1.0"", ""runs"": [ { ""results"": [ { ""ruleId"": ""TST"", ""ruleIndex"": 0, ""level"": ""error"", ""locations"": [ { ""physicalLocation"": { ""artifactLocation"": { ""uri"": """ + (PathUtilities.IsUnixLikePlatform ? "Z:/Main%20Location.cs" : "file:///Z:/Main%20Location.cs") + @""" }, ""region"": { ""startLine"": 1, ""startColumn"": 1, ""endLine"": 1, ""endColumn"": 1 } } } ], ""relatedLocations"": [ { ""physicalLocation"": { ""artifactLocation"": { ""uri"": ""Relative%20Additional/Location.cs"" }, ""region"": { ""startLine"": 1, ""startColumn"": 1, ""endLine"": 1, ""endColumn"": 1 } } } ] } ], ""tool"": { ""driver"": { ""name"": ""toolName"", ""version"": ""1.2.3.4 for Windows"", ""dottedQuadFileVersion"": ""1.2.3.4"", ""semanticVersion"": ""1.2.3"", ""language"": ""fr-CA"", ""rules"": [ { ""id"": ""TST"", ""shortDescription"": { ""text"": ""_TST_"" }, ""defaultConfiguration"": { ""level"": ""error"", ""enabled"": false } } ] } }, ""columnKind"": ""utf16CodeUnits"" } ] }"; [Fact] public void AdditionalLocationsAsRelatedLocations() { AdditionalLocationsAsRelatedLocationsImpl(); } protected override string ExpectedOutputForDescriptorIdCollision => @"{ ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"", ""version"": ""2.1.0"", ""runs"": [ { ""results"": [ { ""ruleId"": ""TST001-001"", ""ruleIndex"": 0, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST001"", ""ruleIndex"": 1, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST001"", ""ruleIndex"": 2, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST001"", ""ruleIndex"": 3, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 4, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 4, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 4, ""level"": ""warning"", ""message"": { ""text"": ""messageFormat"" }, ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 5, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 6, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 7, ""level"": ""error"" }, { ""ruleId"": ""TST002"", ""ruleIndex"": 8, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 9, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST001-001"", ""ruleIndex"": 0, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST001"", ""ruleIndex"": 1, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST001"", ""ruleIndex"": 2, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST001"", ""ruleIndex"": 3, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 4, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 4, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 4, ""level"": ""warning"", ""message"": { ""text"": ""messageFormat"" }, ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 5, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 6, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 7, ""level"": ""error"" }, { ""ruleId"": ""TST002"", ""ruleIndex"": 8, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 9, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } } ], ""tool"": { ""driver"": { ""name"": ""toolName"", ""version"": ""1.2.3.4 for Windows"", ""dottedQuadFileVersion"": ""1.2.3.4"", ""semanticVersion"": ""1.2.3"", ""language"": ""en-US"", ""rules"": [ { ""id"": ""TST001-001"", ""shortDescription"": { ""text"": ""_TST001-001_"" } }, { ""id"": ""TST001"", ""shortDescription"": { ""text"": ""_TST001_"" } }, { ""id"": ""TST001"", ""shortDescription"": { ""text"": ""_TST001-002_"" } }, { ""id"": ""TST001"", ""shortDescription"": { ""text"": ""_TST001-003_"" } }, { ""id"": ""TST002"" }, { ""id"": ""TST002"", ""shortDescription"": { ""text"": ""title_001"" } }, { ""id"": ""TST002"", ""properties"": { ""category"": ""category_002"" } }, { ""id"": ""TST002"", ""defaultConfiguration"": { ""level"": ""error"" } }, { ""id"": ""TST002"", ""defaultConfiguration"": { ""enabled"": false } }, { ""id"": ""TST002"", ""fullDescription"": { ""text"": ""description_005"" } } ] } }, ""columnKind"": ""utf16CodeUnits"" } ] }"; [Fact] public void DescriptorIdCollision() { DescriptorIdCollisionImpl(); } [Fact] public void PathToUri() { PathToUriImpl(@"{{ ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"", ""version"": ""2.1.0"", ""runs"": [ {{ ""results"": [ {{ ""ruleId"": ""uriDiagnostic"", ""ruleIndex"": 0, ""level"": ""warning"", ""message"": {{ ""text"": ""blank diagnostic"" }}, ""locations"": [ {{ ""physicalLocation"": {{ ""artifactLocation"": {{ ""uri"": ""{0}"" }}, ""region"": {{ ""startLine"": 1, ""startColumn"": 1, ""endLine"": 1, ""endColumn"": 1 }} }} }} ], ""properties"": {{ ""warningLevel"": 3 }} }} ], ""tool"": {{ ""driver"": {{ ""name"": """", ""version"": """", ""dottedQuadFileVersion"": ""1.0.0"", ""semanticVersion"": ""1.0.0"", ""language"": """", ""rules"": [ {{ ""id"": ""uriDiagnostic"" }} ] }} }}, ""columnKind"": ""utf16CodeUnits"" }} ] }}"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.IO; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { // See also VB and C# command line unit tests for additional coverage. [Trait(Traits.Feature, Traits.Features.SarifErrorLogging)] public class SarifV2ErrorLoggerTests : SarifErrorLoggerTests { internal override SarifErrorLogger CreateLogger( Stream stream, string toolName, string toolFileVersion, Version toolAssemblyVersion, CultureInfo culture) { return new SarifV2ErrorLogger(stream, toolName, toolFileVersion, toolAssemblyVersion, culture); } protected override string ExpectedOutputForAdditionalLocationsAsRelatedLocations => @"{ ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"", ""version"": ""2.1.0"", ""runs"": [ { ""results"": [ { ""ruleId"": ""TST"", ""ruleIndex"": 0, ""level"": ""error"", ""locations"": [ { ""physicalLocation"": { ""artifactLocation"": { ""uri"": """ + (PathUtilities.IsUnixLikePlatform ? "Z:/Main%20Location.cs" : "file:///Z:/Main%20Location.cs") + @""" }, ""region"": { ""startLine"": 1, ""startColumn"": 1, ""endLine"": 1, ""endColumn"": 1 } } } ], ""relatedLocations"": [ { ""physicalLocation"": { ""artifactLocation"": { ""uri"": ""Relative%20Additional/Location.cs"" }, ""region"": { ""startLine"": 1, ""startColumn"": 1, ""endLine"": 1, ""endColumn"": 1 } } } ] } ], ""tool"": { ""driver"": { ""name"": ""toolName"", ""version"": ""1.2.3.4 for Windows"", ""dottedQuadFileVersion"": ""1.2.3.4"", ""semanticVersion"": ""1.2.3"", ""language"": ""fr-CA"", ""rules"": [ { ""id"": ""TST"", ""shortDescription"": { ""text"": ""_TST_"" }, ""defaultConfiguration"": { ""level"": ""error"", ""enabled"": false } } ] } }, ""columnKind"": ""utf16CodeUnits"" } ] }"; [Fact] public void AdditionalLocationsAsRelatedLocations() { AdditionalLocationsAsRelatedLocationsImpl(); } protected override string ExpectedOutputForDescriptorIdCollision => @"{ ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"", ""version"": ""2.1.0"", ""runs"": [ { ""results"": [ { ""ruleId"": ""TST001-001"", ""ruleIndex"": 0, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST001"", ""ruleIndex"": 1, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST001"", ""ruleIndex"": 2, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST001"", ""ruleIndex"": 3, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 4, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 4, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 4, ""level"": ""warning"", ""message"": { ""text"": ""messageFormat"" }, ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 5, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 6, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 7, ""level"": ""error"" }, { ""ruleId"": ""TST002"", ""ruleIndex"": 8, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 9, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST001-001"", ""ruleIndex"": 0, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST001"", ""ruleIndex"": 1, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST001"", ""ruleIndex"": 2, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST001"", ""ruleIndex"": 3, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 4, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 4, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 4, ""level"": ""warning"", ""message"": { ""text"": ""messageFormat"" }, ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 5, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 6, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 7, ""level"": ""error"" }, { ""ruleId"": ""TST002"", ""ruleIndex"": 8, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } }, { ""ruleId"": ""TST002"", ""ruleIndex"": 9, ""level"": ""warning"", ""properties"": { ""warningLevel"": 1 } } ], ""tool"": { ""driver"": { ""name"": ""toolName"", ""version"": ""1.2.3.4 for Windows"", ""dottedQuadFileVersion"": ""1.2.3.4"", ""semanticVersion"": ""1.2.3"", ""language"": ""en-US"", ""rules"": [ { ""id"": ""TST001-001"", ""shortDescription"": { ""text"": ""_TST001-001_"" } }, { ""id"": ""TST001"", ""shortDescription"": { ""text"": ""_TST001_"" } }, { ""id"": ""TST001"", ""shortDescription"": { ""text"": ""_TST001-002_"" } }, { ""id"": ""TST001"", ""shortDescription"": { ""text"": ""_TST001-003_"" } }, { ""id"": ""TST002"" }, { ""id"": ""TST002"", ""shortDescription"": { ""text"": ""title_001"" } }, { ""id"": ""TST002"", ""properties"": { ""category"": ""category_002"" } }, { ""id"": ""TST002"", ""defaultConfiguration"": { ""level"": ""error"" } }, { ""id"": ""TST002"", ""defaultConfiguration"": { ""enabled"": false } }, { ""id"": ""TST002"", ""fullDescription"": { ""text"": ""description_005"" } } ] } }, ""columnKind"": ""utf16CodeUnits"" } ] }"; [Fact] public void DescriptorIdCollision() { DescriptorIdCollisionImpl(); } [Fact] public void PathToUri() { PathToUriImpl(@"{{ ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"", ""version"": ""2.1.0"", ""runs"": [ {{ ""results"": [ {{ ""ruleId"": ""uriDiagnostic"", ""ruleIndex"": 0, ""level"": ""warning"", ""message"": {{ ""text"": ""blank diagnostic"" }}, ""locations"": [ {{ ""physicalLocation"": {{ ""artifactLocation"": {{ ""uri"": ""{0}"" }}, ""region"": {{ ""startLine"": 1, ""startColumn"": 1, ""endLine"": 1, ""endColumn"": 1 }} }} }} ], ""properties"": {{ ""warningLevel"": 3 }} }} ], ""tool"": {{ ""driver"": {{ ""name"": """", ""version"": """", ""dottedQuadFileVersion"": ""1.0.0"", ""semanticVersion"": ""1.0.0"", ""language"": """", ""rules"": [ {{ ""id"": ""uriDiagnostic"" }} ] }} }}, ""columnKind"": ""utf16CodeUnits"" }} ] }}"); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Symbol/Compilation/GetSemanticInfoTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class GetSemanticInfoTests : SemanticModelTestBase { [WorkItem(544320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544320")] [Fact] public void TestBug12592() { var text = @" class B { public B(int x = 42) {} } class D : B { public D(int y) : base(/*<bind>*/x/*</bind>*/: y) { } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal(SymbolKind.Parameter, sym.Symbol.Kind); Assert.Equal("x", sym.Symbol.Name); } [WorkItem(541948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541948")] [Fact] public void DelegateArgumentType() { var text = @"using System; delegate void MyEvent(); class Test { event MyEvent Clicked; void Handler() { } public void Run() { Test t = new Test(); t.Clicked += new MyEvent(/*<bind>*/Handler/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal(SymbolKind.Method, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); } [WorkItem(541949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541949")] [Fact] public void LambdaWithParenthesis_BindOutsideOfParenthesis() { var text = @"using System; public class Test { delegate int D(); static void Main(int xx) { // int x = (xx); D d = /*<bind>*/( delegate() { return 0; } )/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.NotNull(sym.Symbol); Assert.Equal(SymbolKind.Method, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.AnonymousFunction, conv.Kind); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); Assert.Equal("Test.D", info.ConvertedType.ToTestDisplayString()); } [WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")] [WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")] [Fact] public void LambdaWithParenthesis_BindInsideOfParenthesis() { var text = @"using System; public class Test { delegate int D(); static void Main(int xx) { // int x = (xx); D d = (/*<bind>*/ delegate() { return 0; }/*</bind>*/) ; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.NotNull(sym.Symbol); Assert.Equal(SymbolKind.Method, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.AnonymousFunction, conv.Kind); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); Assert.Equal("Test.D", info.ConvertedType.ToTestDisplayString()); } [Fact, WorkItem(528656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528656")] public void SemanticInfoForInvalidExpression() { var text = @" public class A { static void Main() { Console.WriteLine(/*<bind>*/ delegate * delegate /*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Null(sym.Symbol); } [WorkItem(541973, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541973")] [Fact] public void LambdaAsAttributeArgumentErr() { var text = @"using System; delegate void D(); class MyAttr: Attribute { public MyAttr(D d) { } } [MyAttr((D)/*<bind>*/delegate { }/*</bind>*/)] // CS0182 public class A { } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetTypeInfo(expr); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); } [Fact] public void ClassifyConversionImplicit() { var text = @"using System; enum E { One, Two, Three } public class Test { static byte[] ary; static int Main() { // Identity ary = new byte[3]; // ImplicitConstant ary[0] = 0x0F; // ImplicitNumeric ushort ret = ary[0]; // ImplicitReference Test obj = null; // Identity obj = new Test(); // ImplicitNumeric obj.M(ary[0]); // boxing object box = -1; // ImplicitEnumeration E e = 0; // Identity E e2 = E.Two; // bind 'Two' return (int)ret; } void M(ulong p) { } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[1] as TypeDeclarationSyntax; Assert.Equal(3, testClass.Members.Count); var mainMethod = testClass.Members[1] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(10, mainStats.Count); // ary = new byte[3]; var v1 = (mainStats[0] as ExpressionStatementSyntax).Expression; Assert.Equal(SyntaxKind.SimpleAssignmentExpression, v1.Kind()); ConversionTestHelper(model, (v1 as AssignmentExpressionSyntax).Right, ConversionKind.Identity, ConversionKind.Identity); // ary[0] = 0x0F; var v2 = (mainStats[1] as ExpressionStatementSyntax).Expression; ConversionTestHelper(model, (v2 as AssignmentExpressionSyntax).Right, ConversionKind.ImplicitConstant, ConversionKind.ExplicitNumeric); // ushort ret = ary[0]; var v3 = (mainStats[2] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v3[0].Initializer.Value, ConversionKind.ImplicitNumeric, ConversionKind.ImplicitNumeric); // object obj01 = null; var v4 = (mainStats[3] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v4[0].Initializer.Value, ConversionKind.ImplicitReference, ConversionKind.NoConversion); // obj.M(ary[0]); var v6 = (mainStats[5] as ExpressionStatementSyntax).Expression; Assert.Equal(SyntaxKind.InvocationExpression, v6.Kind()); var v61 = (v6 as InvocationExpressionSyntax).ArgumentList.Arguments; ConversionTestHelper(model, v61[0].Expression, ConversionKind.ImplicitNumeric, ConversionKind.ImplicitNumeric); // object box = -1; var v7 = (mainStats[6] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v7[0].Initializer.Value, ConversionKind.Boxing, ConversionKind.Boxing); // E e = 0; var v8 = (mainStats[7] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v8[0].Initializer.Value, ConversionKind.ImplicitEnumeration, ConversionKind.ExplicitEnumeration); // E e2 = E.Two; var v9 = (mainStats[8] as LocalDeclarationStatementSyntax).Declaration.Variables; var v9val = (MemberAccessExpressionSyntax)(v9[0].Initializer.Value); var v9right = v9val.Name; ConversionTestHelper(model, v9right, ConversionKind.Identity, ConversionKind.Identity); } private void TestClassifyConversionBuiltInNumeric(string from, string to, ConversionKind ck) { const string template = @" class C {{ static void Goo({1} v) {{ }} static void Main() {{ {0} v = default({0}); Goo({2}v); }} }} "; var isExplicitConversion = ck == ConversionKind.ExplicitNumeric; var source = string.Format(template, from, to, isExplicitConversion ? "(" + to + ")" : ""); var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); var c = (TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]; var main = (MethodDeclarationSyntax)c.Members[1]; var call = (InvocationExpressionSyntax)((ExpressionStatementSyntax)main.Body.Statements[1]).Expression; var arg = call.ArgumentList.Arguments[0].Expression; if (isExplicitConversion) { ConversionTestHelper(model, ((CastExpressionSyntax)arg).Expression, model.GetTypeInfo(arg).ConvertedType, ck); } else { ConversionTestHelper(model, arg, ck, ck); } } [Fact] public void ClassifyConversionBuiltInNumeric() { const ConversionKind ID = ConversionKind.Identity; const ConversionKind IN = ConversionKind.ImplicitNumeric; const ConversionKind XN = ConversionKind.ExplicitNumeric; var types = new[] { "sbyte", "byte", "short", "ushort", "int", "uint", "long", "ulong", "char", "float", "double", "decimal" }; var conversions = new ConversionKind[,] { // to sb b s us i ui l ul c f d m // from /* sb */ { ID, XN, IN, XN, IN, XN, IN, XN, XN, IN, IN, IN }, /* b */ { XN, ID, IN, IN, IN, IN, IN, IN, XN, IN, IN, IN }, /* s */ { XN, XN, ID, XN, IN, XN, IN, XN, XN, IN, IN, IN }, /* us */ { XN, XN, XN, ID, IN, IN, IN, IN, XN, IN, IN, IN }, /* i */ { XN, XN, XN, XN, ID, XN, IN, XN, XN, IN, IN, IN }, /* ui */ { XN, XN, XN, XN, XN, ID, IN, IN, XN, IN, IN, IN }, /* l */ { XN, XN, XN, XN, XN, XN, ID, XN, XN, IN, IN, IN }, /* ul */ { XN, XN, XN, XN, XN, XN, XN, ID, XN, IN, IN, IN }, /* c */ { XN, XN, XN, IN, IN, IN, IN, IN, ID, IN, IN, IN }, /* f */ { XN, XN, XN, XN, XN, XN, XN, XN, XN, ID, IN, XN }, /* d */ { XN, XN, XN, XN, XN, XN, XN, XN, XN, XN, ID, XN }, /* m */ { XN, XN, XN, XN, XN, XN, XN, XN, XN, XN, XN, ID } }; for (var from = 0; from < types.Length; from++) { for (var to = 0; to < types.Length; to++) { TestClassifyConversionBuiltInNumeric(types[from], types[to], conversions[from, to]); } } } [WorkItem(527486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527486")] [Fact] public void ClassifyConversionExplicit() { var text = @"using System; public class Test { object obj01; public void Testing(int x, Test obj02) { uint y = 5678; // Cast y = (uint) x; // Boxing obj01 = x; // Cast x = (int)obj01; // NoConversion obj02 = (Test)obj01; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; Assert.Equal(2, testClass.Members.Count); var mainMethod = testClass.Members[1] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(5, mainStats.Count); // y = (uint) x; var v1 = ((mainStats[1] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, (v1 as CastExpressionSyntax).Expression, comp.GetSpecialType(SpecialType.System_UInt32), ConversionKind.ExplicitNumeric); // obj01 = x; var v2 = (mainStats[2] as ExpressionStatementSyntax).Expression; ConversionTestHelper(model, (v2 as AssignmentExpressionSyntax).Right, comp.GetSpecialType(SpecialType.System_Object), ConversionKind.Boxing); // x = (int)obj01; var v3 = ((mainStats[3] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, (v3 as CastExpressionSyntax).Expression, comp.GetSpecialType(SpecialType.System_Int32), ConversionKind.Unboxing); // obj02 = (Test)obj01; var tsym = comp.SourceModule.GlobalNamespace.GetTypeMembers("Test").FirstOrDefault(); var v4 = ((mainStats[4] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, (v4 as CastExpressionSyntax).Expression, tsym, ConversionKind.ExplicitReference); } [Fact] public void DiagnosticsInStages() { var text = @" public class Test { object obj01; public void Testing(int x, Test obj02) { // ExplicitReference -> CS0266 obj02 = obj01; } binding error; parse err } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var errs = model.GetDiagnostics(); Assert.Equal(4, errs.Count()); errs = model.GetSyntaxDiagnostics(); Assert.Equal(1, errs.Count()); errs = model.GetDeclarationDiagnostics(); Assert.Equal(2, errs.Count()); errs = model.GetMethodBodyDiagnostics(); Assert.Equal(1, errs.Count()); } [Fact] public void DiagnosticsFilteredWithPragmas() { var text = @" public class Test { #pragma warning disable 1633 #pragma xyzzy whatever #pragma warning restore 1633 } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var errs = model.GetDiagnostics(); Assert.Equal(0, errs.Count()); errs = model.GetSyntaxDiagnostics(); Assert.Equal(0, errs.Count()); } [Fact] public void ClassifyConversionExplicitNeg() { var text = @" public class Test { object obj01; public void Testing(int x, Test obj02) { uint y = 5678; // ExplicitNumeric - CS0266 y = x; // Boxing obj01 = x; // unboxing - CS0266 x = obj01; // ExplicitReference -> CS0266 obj02 = obj01; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; Assert.Equal(2, testClass.Members.Count); var mainMethod = testClass.Members[1] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(5, mainStats.Count); // y = x; var v1 = ((mainStats[1] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, v1, ConversionKind.ExplicitNumeric, ConversionKind.ExplicitNumeric); // x = obj01; var v2 = ((mainStats[3] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, v2, ConversionKind.Unboxing, ConversionKind.Unboxing); // obj02 = obj01; var v3 = ((mainStats[4] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, v3, ConversionKind.ExplicitReference, ConversionKind.ExplicitReference); // CC var errs = model.GetDiagnostics(); Assert.Equal(3, errs.Count()); errs = model.GetDeclarationDiagnostics(); Assert.Equal(0, errs.Count()); } [WorkItem(527767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527767")] [Fact] public void ClassifyConversionNullable() { var text = @"using System; public class Test { static void Main() { // NullLiteral sbyte? nullable = null; // ImplicitNullable uint? nullable01 = 100; ushort localVal = 123; // ImplicitNullable nullable01 = localVal; E e = 0; E? en = 0; // Oddly enough, C# classifies this as an implicit enumeration conversion. } } enum E { zero, one } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; Assert.Equal(1, testClass.Members.Count); var mainMethod = testClass.Members[0] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(6, mainStats.Count); // sbyte? nullable = null; var v1 = (mainStats[0] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v1[0].Initializer.Value, ConversionKind.NullLiteral, ConversionKind.NoConversion); // uint? nullable01 = 100; var v2 = (mainStats[1] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v2[0].Initializer.Value, ConversionKind.ImplicitNullable, ConversionKind.ExplicitNullable); // nullable01 = localVal; var v3 = (mainStats[3] as ExpressionStatementSyntax).Expression; Assert.Equal(SyntaxKind.SimpleAssignmentExpression, v3.Kind()); ConversionTestHelper(model, (v3 as AssignmentExpressionSyntax).Right, ConversionKind.ImplicitNullable, ConversionKind.ImplicitNullable); // E e = 0; var v4 = (mainStats[4] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v4[0].Initializer.Value, ConversionKind.ImplicitEnumeration, ConversionKind.ExplicitEnumeration); // E? en = 0; var v5 = (mainStats[5] as LocalDeclarationStatementSyntax).Declaration.Variables; // Bug#5035 (ByDesign): Conversion from literal 0 to nullable enum is Implicit Enumeration (not ImplicitNullable). Conversion from int to nullable enum is Explicit Nullable. ConversionTestHelper(model, v5[0].Initializer.Value, ConversionKind.ImplicitEnumeration, ConversionKind.ExplicitNullable); } [Fact, WorkItem(543994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543994")] public void ClassifyConversionImplicitUserDef() { var text = @"using System; class MyClass { public static bool operator true(MyClass p) { return true; } public static bool operator false(MyClass p) { return false; } public static MyClass operator &(MyClass mc1, MyClass mc2) { return new MyClass(); } public static int Main() { var cls1 = new MyClass(); var cls2 = new MyClass(); if (/*<bind0>*/cls1/*</bind0>*/) return 0; if (/*<bind1>*/cls1 && cls2/*</bind1>*/) return 1; return 2; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); var expr2 = exprs.Last(); var info = model.GetTypeInfo(expr1); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); // It was ImplicitUserDef -> Design Meeting resolution: not expose op_True|False as conversion through API var impconv = model.GetConversion(expr1); Assert.Equal(Conversion.Identity, impconv); Conversion conv = model.ClassifyConversion(expr1, info.ConvertedType); CheckIsAssignableTo(model, expr1); Assert.Equal(impconv, conv); Assert.Equal("Identity", conv.ToString()); conv = model.ClassifyConversion(expr2, info.ConvertedType); CheckIsAssignableTo(model, expr2); Assert.Equal(impconv, conv); } [Fact, WorkItem(1019372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019372")] public void ClassifyConversionImplicitUserDef02() { var text = @" class C { public static implicit operator int(C c) { return 0; } public C() { int? i = /*<bind0>*/this/*</bind0>*/; } }"; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); var info = model.GetTypeInfo(expr1); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); var impconv = model.GetConversion(expr1); Assert.True(impconv.IsImplicit); Assert.True(impconv.IsUserDefined); Conversion conv = model.ClassifyConversion(expr1, info.ConvertedType); CheckIsAssignableTo(model, expr1); Assert.Equal(impconv, conv); Assert.True(conv.IsImplicit); Assert.True(conv.IsUserDefined); } private void CheckIsAssignableTo(SemanticModel model, ExpressionSyntax syntax) { var info = model.GetTypeInfo(syntax); var conversion = info.Type != null && info.ConvertedType != null ? model.Compilation.ClassifyConversion(info.Type, info.ConvertedType) : Conversion.NoConversion; Assert.Equal(conversion.IsImplicit, model.Compilation.HasImplicitConversion(info.Type, info.ConvertedType)); } [Fact, WorkItem(544151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544151")] public void PublicViewOfPointerConversions() { ValidateConversion(Conversion.PointerToVoid, ConversionKind.ImplicitPointerToVoid); ValidateConversion(Conversion.NullToPointer, ConversionKind.ImplicitNullToPointer); ValidateConversion(Conversion.PointerToPointer, ConversionKind.ExplicitPointerToPointer); ValidateConversion(Conversion.IntegerToPointer, ConversionKind.ExplicitIntegerToPointer); ValidateConversion(Conversion.PointerToInteger, ConversionKind.ExplicitPointerToInteger); ValidateConversion(Conversion.IntPtr, ConversionKind.IntPtr); } #region "Conversion helper" private void ValidateConversion(Conversion conv, ConversionKind kind) { Assert.Equal(conv.Kind, kind); switch (kind) { case ConversionKind.NoConversion: Assert.False(conv.Exists); Assert.False(conv.IsImplicit); Assert.False(conv.IsExplicit); break; case ConversionKind.Identity: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsIdentity); break; case ConversionKind.ImplicitNumeric: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsNumeric); break; case ConversionKind.ImplicitEnumeration: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsEnumeration); break; case ConversionKind.ImplicitNullable: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsNullable); break; case ConversionKind.NullLiteral: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsNullLiteral); break; case ConversionKind.ImplicitReference: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsReference); break; case ConversionKind.Boxing: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsBoxing); break; case ConversionKind.ImplicitDynamic: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsDynamic); break; case ConversionKind.ExplicitDynamic: Assert.True(conv.Exists); Assert.True(conv.IsExplicit); Assert.False(conv.IsImplicit); Assert.True(conv.IsDynamic); break; case ConversionKind.ImplicitConstant: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsConstantExpression); break; case ConversionKind.ImplicitUserDefined: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsUserDefined); break; case ConversionKind.AnonymousFunction: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsAnonymousFunction); break; case ConversionKind.MethodGroup: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsMethodGroup); break; case ConversionKind.ExplicitNumeric: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsNumeric); break; case ConversionKind.ExplicitEnumeration: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsEnumeration); break; case ConversionKind.ExplicitNullable: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsNullable); break; case ConversionKind.ExplicitReference: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsReference); break; case ConversionKind.Unboxing: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsUnboxing); break; case ConversionKind.ExplicitUserDefined: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsUserDefined); break; case ConversionKind.ImplicitNullToPointer: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ImplicitPointerToVoid: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ExplicitPointerToPointer: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ExplicitIntegerToPointer: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ExplicitPointerToInteger: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.IntPtr: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.False(conv.IsPointer); Assert.True(conv.IsIntPtr); break; } } /// <summary> /// /// </summary> /// <param name="semanticModel"></param> /// <param name="expr"></param> /// <param name="ept1">expr -> TypeInParent</param> /// <param name="ept2">Type(expr) -> TypeInParent</param> private void ConversionTestHelper(SemanticModel semanticModel, ExpressionSyntax expr, ConversionKind ept1, ConversionKind ept2) { var info = semanticModel.GetTypeInfo(expr); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); var conv = semanticModel.GetConversion(expr); // NOT expect NoConversion Conversion act1 = semanticModel.ClassifyConversion(expr, info.ConvertedType); CheckIsAssignableTo(semanticModel, expr); Assert.Equal(ept1, act1.Kind); ValidateConversion(act1, ept1); ValidateConversion(act1, conv.Kind); if (ept2 == ConversionKind.NoConversion) { Assert.Null(info.Type); } else { Assert.NotNull(info.Type); var act2 = semanticModel.Compilation.ClassifyConversion(info.Type, info.ConvertedType); Assert.Equal(ept2, act2.Kind); ValidateConversion(act2, ept2); } } private void ConversionTestHelper(SemanticModel semanticModel, ExpressionSyntax expr, ITypeSymbol expsym, ConversionKind expkind) { var info = semanticModel.GetTypeInfo(expr); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); // NOT expect NoConversion Conversion act1 = semanticModel.ClassifyConversion(expr, expsym); CheckIsAssignableTo(semanticModel, expr); Assert.Equal(expkind, act1.Kind); ValidateConversion(act1, expkind); } #endregion [Fact] public void EnumOffsets() { // sbyte EnumOffset(ConstantValue.Create((sbyte)sbyte.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(sbyte.MinValue + 1))); EnumOffset(ConstantValue.Create((sbyte)sbyte.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(sbyte.MinValue + 2))); EnumOffset(ConstantValue.Create((sbyte)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(-1))); EnumOffset(ConstantValue.Create((sbyte)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(1))); EnumOffset(ConstantValue.Create((sbyte)(sbyte.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)sbyte.MaxValue)); EnumOffset(ConstantValue.Create((sbyte)(sbyte.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((sbyte)(sbyte.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // byte EnumOffset(ConstantValue.Create((byte)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((byte)1)); EnumOffset(ConstantValue.Create((byte)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((byte)2)); EnumOffset(ConstantValue.Create((byte)(byte.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((byte)byte.MaxValue)); EnumOffset(ConstantValue.Create((byte)(byte.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((byte)(byte.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // short EnumOffset(ConstantValue.Create((short)short.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(short.MinValue + 1))); EnumOffset(ConstantValue.Create((short)short.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(short.MinValue + 2))); EnumOffset(ConstantValue.Create((short)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(-1))); EnumOffset(ConstantValue.Create((short)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(1))); EnumOffset(ConstantValue.Create((short)(short.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)short.MaxValue)); EnumOffset(ConstantValue.Create((short)(short.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((short)(short.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // ushort EnumOffset(ConstantValue.Create((ushort)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((ushort)1)); EnumOffset(ConstantValue.Create((ushort)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((ushort)2)); EnumOffset(ConstantValue.Create((ushort)(ushort.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((ushort)ushort.MaxValue)); EnumOffset(ConstantValue.Create((ushort)(ushort.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((ushort)(ushort.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // int EnumOffset(ConstantValue.Create((int)int.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(int.MinValue + 1))); EnumOffset(ConstantValue.Create((int)int.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(int.MinValue + 2))); EnumOffset(ConstantValue.Create((int)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(-1))); EnumOffset(ConstantValue.Create((int)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(1))); EnumOffset(ConstantValue.Create((int)(int.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)int.MaxValue)); EnumOffset(ConstantValue.Create((int)(int.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((int)(int.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // uint EnumOffset(ConstantValue.Create((uint)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((uint)1)); EnumOffset(ConstantValue.Create((uint)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((uint)2)); EnumOffset(ConstantValue.Create((uint)(uint.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((uint)uint.MaxValue)); EnumOffset(ConstantValue.Create((uint)(uint.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((uint)(uint.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // long EnumOffset(ConstantValue.Create((long)long.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(long.MinValue + 1))); EnumOffset(ConstantValue.Create((long)long.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(long.MinValue + 2))); EnumOffset(ConstantValue.Create((long)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(-1))); EnumOffset(ConstantValue.Create((long)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(1))); EnumOffset(ConstantValue.Create((long)(long.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)long.MaxValue)); EnumOffset(ConstantValue.Create((long)(long.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((long)(long.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // ulong EnumOffset(ConstantValue.Create((ulong)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((ulong)1)); EnumOffset(ConstantValue.Create((ulong)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((ulong)2)); EnumOffset(ConstantValue.Create((ulong)(ulong.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((ulong)ulong.MaxValue)); EnumOffset(ConstantValue.Create((ulong)(ulong.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((ulong)(ulong.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); } private void EnumOffset(ConstantValue constantValue, uint offset, EnumOverflowKind expectedOverflowKind, ConstantValue expectedValue) { ConstantValue actualValue; var actualOverflowKind = EnumConstantHelper.OffsetValue(constantValue, offset, out actualValue); Assert.Equal(expectedOverflowKind, actualOverflowKind); Assert.Equal(expectedValue, actualValue); } [Fact] public void TestGetSemanticInfoInParentInIf() { var compilation = CreateCompilation(@" class C { void M(int x) { if (x == 10) {} } } "); var tree = compilation.SyntaxTrees[0]; var methodDecl = (MethodDeclarationSyntax)((TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]).Members[0]; var ifStatement = (IfStatementSyntax)methodDecl.Body.Statements[0]; var condition = ifStatement.Condition; var model = compilation.GetSemanticModel(tree); var info = model.GetSemanticInfoSummary(condition); Assert.NotNull(info.ConvertedType); Assert.Equal("Boolean", info.Type.Name); Assert.Equal("System.Boolean System.Int32.op_Equality(System.Int32 left, System.Int32 right)", info.Symbol.ToTestDisplayString()); Assert.Equal(0, info.CandidateSymbols.Length); } [Fact] public void TestGetSemanticInfoInParentInFor() { var compilation = CreateCompilation(@" class C { void M(int x) { for (int i = 0; i < 10; i = i + 1) { } } } "); var tree = compilation.SyntaxTrees[0]; var methodDecl = (MethodDeclarationSyntax)((TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]).Members[0]; var forStatement = (ForStatementSyntax)methodDecl.Body.Statements[0]; var condition = forStatement.Condition; var model = compilation.GetSemanticModel(tree); var info = model.GetSemanticInfoSummary(condition); Assert.NotNull(info.ConvertedType); Assert.Equal("Boolean", info.ConvertedType.Name); Assert.Equal("System.Boolean System.Int32.op_LessThan(System.Int32 left, System.Int32 right)", info.Symbol.ToTestDisplayString()); Assert.Equal(0, info.CandidateSymbols.Length); } [WorkItem(540279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540279")] [Fact] public void NoMembersForVoidReturnType() { var text = @" class C { void M() { /*<bind>*/System.Console.WriteLine()/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); IMethodSymbol methodSymbol = (IMethodSymbol)bindInfo.Symbol; ITypeSymbol returnType = methodSymbol.ReturnType; var symbols = model.LookupSymbols(0, returnType); Assert.Equal(0, symbols.Length); } [WorkItem(540767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540767")] [Fact] public void BindIncompleteVarDeclWithDoKeyword() { var code = @" class Test { static int Main(string[] args) { do"; var compilation = CreateCompilation(code); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var exprSyntaxList = GetExprSyntaxList(tree); Assert.Equal(6, exprSyntaxList.Count); // Note the omitted array size expression in "string[]" Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxList[4].Kind()); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxList[5].Kind()); Assert.Equal("", exprSyntaxList[4].ToFullString()); Assert.Equal("", exprSyntaxList[5].ToFullString()); var exprSyntaxToBind = exprSyntaxList[exprSyntaxList.Count - 2]; model.GetSemanticInfoSummary(exprSyntaxToBind); } [Fact] public void TestBindBaseConstructorInitializer() { var text = @" class C { C() : base() { } } "; var bindInfo = BindFirstConstructorInitializer(text); Assert.NotEqual(default, bindInfo); var baseConstructor = bindInfo.Symbol; Assert.Equal(SymbolKind.Method, baseConstructor.Kind); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)baseConstructor).MethodKind); Assert.Equal("System.Object..ctor()", baseConstructor.ToTestDisplayString()); } [Fact] public void TestBindThisConstructorInitializer() { var text = @" class C { C() : this(1) { } C(int x) { } } "; var bindInfo = BindFirstConstructorInitializer(text); Assert.NotEqual(default, bindInfo); var baseConstructor = bindInfo.Symbol; Assert.Equal(SymbolKind.Method, baseConstructor.Kind); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)baseConstructor).MethodKind); Assert.Equal("C..ctor(System.Int32 x)", baseConstructor.ToTestDisplayString()); } [WorkItem(540862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540862")] [Fact] public void BindThisStaticConstructorInitializer() { var text = @" class MyClass { static MyClass() : this() { intI = 2; } public MyClass() { } static int intI = 1; } "; var bindInfo = BindFirstConstructorInitializer(text); Assert.NotEqual(default, bindInfo); var invokedConstructor = (IMethodSymbol)bindInfo.Symbol; Assert.Equal(MethodKind.Constructor, invokedConstructor.MethodKind); Assert.Equal("MyClass..ctor()", invokedConstructor.ToTestDisplayString()); } [WorkItem(541053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541053")] [Fact] public void CheckAndAdjustPositionOutOfRange() { var text = @" using System; > 1 "; var tree = Parse(text, options: TestOptions.Script); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); Assert.NotEqual(0, root.SpanStart); var stmt = (GlobalStatementSyntax)root.Members.Single(); var expr = ((ExpressionStatementSyntax)stmt.Statement).Expression; Assert.Equal(SyntaxKind.GreaterThanExpression, expr.Kind()); var info = model.GetSemanticInfoSummary(expr); Assert.Equal(SpecialType.System_Boolean, info.Type.SpecialType); } [Fact] public void AddAccessorValueParameter() { var text = @" class C { private System.Action e; event System.Action E { add { e += /*<bind>*/value/*</bind>*/; } remove { e -= value; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var parameterSymbol = (IParameterSymbol)bindInfo.Symbol; Assert.Equal(systemActionType, parameterSymbol.Type); Assert.Equal("value", parameterSymbol.Name); Assert.Equal(MethodKind.EventAdd, ((IMethodSymbol)parameterSymbol.ContainingSymbol).MethodKind); } [Fact] public void RemoveAccessorValueParameter() { var text = @" class C { private System.Action e; event System.Action E { add { e += value; } remove { e -= /*<bind>*/value/*</bind>*/; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var parameterSymbol = (IParameterSymbol)bindInfo.Symbol; Assert.Equal(systemActionType, parameterSymbol.Type); Assert.Equal("value", parameterSymbol.Name); Assert.Equal(MethodKind.EventRemove, ((IMethodSymbol)parameterSymbol.ContainingSymbol).MethodKind); } [Fact] public void FieldLikeEventInitializer() { var text = @" class C { event System.Action E = /*<bind>*/new System.Action(() => { })/*</bind>*/; } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); Assert.Null(bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); } [Fact] public void FieldLikeEventInitializer2() { var text = @" class C { event System.Action E = new /*<bind>*/System.Action/*</bind>*/(() => { }); } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Null(bindInfo.Type); Assert.Equal(systemActionType, bindInfo.Symbol); } [Fact] public void CustomEventAccess() { var text = @" class C { event System.Action E { add { } remove { } } void Method() { /*<bind>*/E/*</bind>*/ += null; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol, bindInfo.Symbol); } [Fact] public void FieldLikeEventAccess() { var text = @" class C { event System.Action E; void Method() { /*<bind>*/E/*</bind>*/ += null; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol, bindInfo.Symbol); } [Fact] public void CustomEventAssignmentOperator() { var text = @" class C { event System.Action E { add { } remove { } } void Method() { /*<bind>*/E += null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Equal(SpecialType.System_Void, bindInfo.Type.SpecialType); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol.AddMethod, bindInfo.Symbol); } [Fact] public void FieldLikeEventAssignmentOperator() { var text = @" class C { event System.Action E; void Method() { /*<bind>*/E += null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Equal(SpecialType.System_Void, bindInfo.Type.SpecialType); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol.AddMethod, bindInfo.Symbol); } [Fact] public void CustomEventMissingAssignmentOperator() { var text = @" class C { event System.Action E { /*add { }*/ remove { } } //missing add void Method() { /*<bind>*/E += null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Null(bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(SpecialType.System_Void, bindInfo.Type.SpecialType); } private static INamedTypeSymbol GetSystemActionType(CSharpCompilation comp) { return GetSystemActionType((Compilation)comp); } private static INamedTypeSymbol GetSystemActionType(Compilation comp) { return (INamedTypeSymbol)comp.GlobalNamespace.GetMember<INamespaceSymbol>("System").GetMembers("Action").Where(s => !((INamedTypeSymbol)s).IsGenericType).Single(); } [Fact] public void IndexerAccess() { var text = @" class C { int this[int x] { get { return x; } } int this[int x, int y] { get { return x + y; } } void Method() { int x = /*<bind>*/this[1]/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ElementAccessExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var indexerSymbol = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Where(i => i.ParameterCount == 1).Single().GetPublicSymbol(); Assert.Equal(indexerSymbol, bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, bindInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, bindInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(0, bindInfo.MethodGroup.Length); Assert.False(bindInfo.IsCompileTimeConstant); Assert.Null(bindInfo.ConstantValue.Value); } [Fact] public void IndexerAccessOverloadResolutionFailure() { var text = @" class C { int this[int x] { get { return x; } } int this[int x, int y] { get { return x + y; } } void Method() { int x = /*<bind>*/this[1, 2, 3]/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ElementAccessExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var indexerSymbol1 = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Where(i => i.ParameterCount == 1).Single().GetPublicSymbol(); var indexerSymbol2 = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Where(i => i.ParameterCount == 2).Single().GetPublicSymbol(); var candidateIndexers = ImmutableArray.Create<ISymbol>(indexerSymbol1, indexerSymbol2); Assert.Null(bindInfo.Symbol); Assert.True(bindInfo.CandidateSymbols.SetEquals(candidateIndexers, EqualityComparer<ISymbol>.Default)); Assert.Equal(CandidateReason.OverloadResolutionFailure, bindInfo.CandidateReason); Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType); //still have the type since all candidates agree Assert.Equal(SpecialType.System_Int32, bindInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, bindInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.OverloadResolutionFailure, bindInfo.CandidateReason); Assert.Equal(0, bindInfo.MethodGroup.Length); Assert.False(bindInfo.IsCompileTimeConstant); Assert.Null(bindInfo.ConstantValue.Value); } [Fact] public void IndexerAccessNoIndexers() { var text = @" class C { void Method() { int x = /*<bind>*/this[1, 2, 3]/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ElementAccessExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Null(bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(TypeKind.Error, bindInfo.Type.TypeKind); Assert.Equal(TypeKind.Struct, bindInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, bindInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(0, bindInfo.MethodGroup.Length); Assert.False(bindInfo.IsCompileTimeConstant); Assert.Null(bindInfo.ConstantValue.Value); } [WorkItem(542296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542296")] [Fact] public void TypeArgumentsOnFieldAccess1() { var text = @" public class Test { public int Fld; public int Func() { return (int)(/*<bind>*/Fld<int>/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.GenericName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Null(bindInfo.Symbol); Assert.Equal(CandidateReason.WrongArity, bindInfo.CandidateReason); Assert.Equal(1, bindInfo.CandidateSymbols.Length); var candidate = bindInfo.CandidateSymbols.Single(); Assert.Equal(SymbolKind.Field, candidate.Kind); Assert.Equal("Fld", candidate.Name); } [WorkItem(542296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542296")] [Fact] public void TypeArgumentsOnFieldAccess2() { var text = @" public class Test { public int Fld; public int Func() { return (int)(Fld</*<bind>*/Test/*</bind>*/>); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.NamedType, symbol.Kind); Assert.Equal("Test", symbol.Name); } [WorkItem(528785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528785")] [Fact] public void TopLevelIndexer() { var text = @" this[double E] { get { return /*<bind>*/E/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.Null(symbol); } [WorkItem(542360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542360")] [Fact] public void TypeAndMethodHaveSameTypeParameterName() { var text = @" interface I<T> { void Goo<T>(); } class A<T> : I<T> { void I</*<bind>*/T/*</bind>*/>.Goo<T>() { } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("T", symbol.Name); Assert.Equal(comp.GlobalNamespace.GetMember<INamedTypeSymbol>("A"), symbol.ContainingSymbol); //from the type, not the method } [WorkItem(542436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542436")] [Fact] public void RecoveryFromBadNamespaceDeclaration() { var text = @"namespace alias:: using alias = /*<bind>*/N/*</bind>*/; namespace N { } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); } /// Test that binding a local declared with var binds the same way when localSymbol.Type is called before BindVariableDeclaration. /// Assert occurs if the two do not compute the same type. [Fact] [WorkItem(542634, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542634")] public void VarInitializedWithStaticType() { var text = @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static string xunit = " + "@" + @"..\..\Closed\Tools\xUnit\xunit.console.x86.exe" + @"; static string test = " + @"Roslyn.VisualStudio.Services.UnitTests.dll" + @"; static string commandLine = test" + @" /html log.html" + @"; static void Main(string[] args) { var options = CreateOptions(); /*<bind>*/Parallel/*</bind>*/.For(0, 100, RunTest, options); } private static Parallel CreateOptions() { var result = new ParallelOptions(); } private static void RunTest(int i) { } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); // Bind Parallel from line Parallel.For(0, 100, RunTest, options); // This will implicitly bind "var" to determine type of options. // This calls LocalSymbol.GetType var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var varIdentifier = (IdentifierNameSyntax)tree.GetCompilationUnitRoot().DescendantNodes().First(n => n.ToString() == "var"); // var from line var options = CreateOptions; // Explicitly bind "var". // This path calls BindvariableDeclaration. bindInfo = model.GetSemanticInfoSummary(varIdentifier); } [WorkItem(542186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542186")] [Fact] public void IndexerParameter() { var text = @" class C { int this[int x] { get { return /*<bind>*/x/*</bind>*/; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("x", symbol.Name); Assert.Equal(SymbolKind.Method, symbol.ContainingSymbol.Kind); var lookupSymbols = model.LookupSymbols(exprSyntaxToBind.SpanStart, name: "x"); Assert.Equal(symbol, lookupSymbols.Single()); } [WorkItem(542186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542186")] [Fact] public void IndexerValueParameter() { var text = @" class C { int this[int x] { set { x = /*<bind>*/value/*</bind>*/; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("value", symbol.Name); Assert.Equal(SymbolKind.Method, symbol.ContainingSymbol.Kind); var lookupSymbols = model.LookupSymbols(exprSyntaxToBind.SpanStart, name: "value"); Assert.Equal(symbol, lookupSymbols.Single()); } [WorkItem(542777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542777")] [Fact] public void IndexerThisParameter() { var text = @" class C { int this[int x] { set { System.Console.Write(/*<bind>*/this/*</bind>*/); } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ThisExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("this", symbol.Name); Assert.Equal(SymbolKind.Method, symbol.ContainingSymbol.Kind); } [WorkItem(542592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542592")] [Fact] public void TypeParameterParamsParameter() { var text = @" class Test<T> { public void Method(params T arr) { } } class Program { static void Main(string[] args) { new Test<int[]>()./*<bind>*/Method/*</bind>*/(new int[][] { }); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.Null(symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, bindInfo.CandidateReason); var candidate = (IMethodSymbol)bindInfo.CandidateSymbols.Single(); Assert.Equal("void Test<System.Int32[]>.Method(params System.Int32[] arr)", candidate.ToTestDisplayString()); Assert.Equal(TypeKind.Array, candidate.Parameters.Last().Type.TypeKind); Assert.Equal(TypeKind.TypeParameter, ((IMethodSymbol)candidate.OriginalDefinition).Parameters.Last().Type.TypeKind); } [WorkItem(542458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542458")] [Fact] public void ParameterDefaultValues() { var text = @" struct S { void M( int i = 1, string str = ""hello"", object o = null, S s = default(S)) { /*<bind>*/M/*</bind>*/(); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); var method = (IMethodSymbol)bindInfo.Symbol; Assert.NotNull(method); var parameters = method.Parameters; Assert.Equal(4, parameters.Length); Assert.True(parameters[0].HasExplicitDefaultValue); Assert.Equal(1, parameters[0].ExplicitDefaultValue); Assert.True(parameters[1].HasExplicitDefaultValue); Assert.Equal("hello", parameters[1].ExplicitDefaultValue); Assert.True(parameters[2].HasExplicitDefaultValue); Assert.Null(parameters[2].ExplicitDefaultValue); Assert.True(parameters[3].HasExplicitDefaultValue); Assert.Null(parameters[3].ExplicitDefaultValue); } [WorkItem(542764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542764")] [Fact] public void UnboundGenericTypeArity() { var text = @" class C<T, U, V> { void M() { System.Console.Write(typeof(/*<bind>*/C<,,>/*</bind>*/)); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var nameSyntaxToBind = (SimpleNameSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.GenericName, nameSyntaxToBind.Kind()); Assert.Equal(3, nameSyntaxToBind.Arity); var bindInfo = model.GetSymbolInfo(nameSyntaxToBind); var type = (INamedTypeSymbol)bindInfo.Symbol; Assert.NotNull(type); Assert.True(type.IsUnboundGenericType); Assert.Equal(3, type.Arity); Assert.Equal("C<,,>", type.ToTestDisplayString()); } [Fact] public void GetType_VoidArray() { var text = @" class C { void M() { var x = typeof(/*<bind>*/System.Void[]/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ArrayType, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); var arrayType = (IArrayTypeSymbol)bindInfo.Symbol; Assert.NotNull(arrayType); Assert.Equal("System.Void[]", arrayType.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance1() { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { } public class C<T> where T : IA, IB // can find IA.P in two different ways { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Object> System.Collections.Generic.IEnumerable<T>.Select<T, System.Object>(System.Func<T, System.Object> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance2() //add hiding member in derived interface { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { new int P { get; } } public class C<T> where T : IA, IB { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Int32> System.Collections.Generic.IEnumerable<T>.Select<T, System.Int32>(System.Func<T, System.Int32> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance3() //reverse order of interface list (shouldn't matter) { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { new int P { get; } } public class C<T> where T : IB, IA { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Int32> System.Collections.Generic.IEnumerable<T>.Select<T, System.Int32>(System.Func<T, System.Int32> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance4() //Two interfaces with a common base { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { } public interface IC : IA { } public class C<T> where T : IB, IC { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Object> System.Collections.Generic.IEnumerable<T>.Select<T, System.Object>(System.Func<T, System.Object> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup1() { var types = @" public interface IA { object P { get; } } "; var members = LookupTypeParameterMembers(types, "IA", "P", out _); Assert.Equal("System.Object IA.P { get; }", members.Single().ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup2() { var types = @" public interface IA { object P { get; } } public interface IB { object P { get; } } "; ITypeParameterSymbol typeParameter; var members = LookupTypeParameterMembers(types, "IA, IB", "P", out typeParameter); Assert.True(members.SetEquals(typeParameter.AllEffectiveInterfacesNoUseSiteDiagnostics().Select(i => i.GetMember<IPropertySymbol>("P")))); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup3() { var types = @" public interface IA { object P { get; } } public interface IB : IA { new object P { get; } } "; var members = LookupTypeParameterMembers(types, "IA, IB", "P", out _); Assert.Equal("System.Object IB.P { get; }", members.Single().ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup4() { var types = @" public interface IA { object P { get; } } public class D { public object P { get; set; } } "; var members = LookupTypeParameterMembers(types, "D, IA", "P", out _); Assert.Equal("System.Object D.P { get; set; }", members.Single().ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup5() { var types = @" public interface IA { void M(); } public class D { public void M() { } } "; var members = LookupTypeParameterMembers(types, "IA", "M", out _); Assert.Equal("void IA.M()", members.Single().ToTestDisplayString()); members = LookupTypeParameterMembers(types, "D, IA", "M", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "void IA.M()", "void D.M()" })); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup6() { var types = @" public interface IA { void M(); void M(int x); } public class D { public void M() { } } "; var members = LookupTypeParameterMembers(types, "IA", "M", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "void IA.M()", "void IA.M(System.Int32 x)" })); members = LookupTypeParameterMembers(types, "D, IA", "M", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "void D.M()", "void IA.M()", "void IA.M(System.Int32 x)" })); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup7() { var types = @" public interface IA { string ToString(); } public class D { public new string ToString() { return null; } } "; var members = LookupTypeParameterMembers(types, "IA", "ToString", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "System.String System.Object.ToString()", "System.String IA.ToString()" })); members = LookupTypeParameterMembers(types, "D, IA", "ToString", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "System.String System.Object.ToString()", "System.String D.ToString()", "System.String IA.ToString()" })); } private IEnumerable<ISymbol> LookupTypeParameterMembers(string types, string constraints, string memberName, out ITypeParameterSymbol typeParameter) { var template = @" {0} public class C<T> where T : {1} {{ void M() {{ System.Console.WriteLine(/*<bind>*/default(T)/*</bind>*/); }} }} "; var tree = Parse(string.Format(template, types, constraints)); var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); var classC = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); typeParameter = classC.TypeParameters.Single(); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.DefaultExpression, exprSyntaxToBind.Kind()); return model.LookupSymbols(exprSyntaxToBind.SpanStart, typeParameter, memberName); } [WorkItem(542966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542966")] [Fact] public async Task IndexerMemberRaceAsync() { var text = @" using System; interface IA { [System.Runtime.CompilerServices.IndexerName(""Goo"")] string this[int index] { get; } } class A : IA { public virtual string this[int index] { get { return """"; } } string IA.this[int index] { get { return """"; } } } class B : A, IA { public override string this[int index] { get { return """"; } } } class Program { public static void Main(string[] args) { IA x = new B(); Console.WriteLine(x[0]); } } "; TimeSpan timeout = TimeSpan.FromSeconds(2); for (int i = 0; i < 20; i++) { var comp = CreateCompilation(text); var task1 = new Task(() => comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMembers()); var task2 = new Task(() => comp.GlobalNamespace.GetMember<NamedTypeSymbol>("IA").GetMembers()); if (i % 2 == 0) { task1.Start(); task2.Start(); } else { task2.Start(); task1.Start(); } comp.VerifyDiagnostics(); await Task.WhenAll(task1, task2); } } [Fact] public void ImplicitDeclarationMultipleDeclarators() { var text = @" using System.IO; class C { static void Main() { /*<bind>*/var a = new StreamWriter(""""), b = new StreamReader("""")/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (8,19): error CS0819: Implicitly-typed variables cannot have multiple declarators // /*<bind>*/var a = new StreamWriter(""), b = new StreamReader("")/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, @"var a = new StreamWriter(""""), b = new StreamReader("""")").WithLocation(8, 19) ); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var typeInfo = model.GetSymbolInfo(expr); // the type info uses the type inferred for the first declared local Assert.Equal("System.IO.StreamWriter", typeInfo.Symbol.ToTestDisplayString()); } [WorkItem(543169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543169")] [Fact] public void ParameterOfLambdaPassedToOutParameter() { var text = @" using System.Linq; class D { static void Main(string[] args) { string[] str = new string[] { }; label1: var s = str.Where(out /*<bind>*/x/*</bind>*/ => { return x == ""1""; }); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(); var parameterSymbol = model.GetDeclaredSymbol(lambdaSyntax.Parameter); Assert.NotNull(parameterSymbol); Assert.Equal("x", parameterSymbol.Name); Assert.Equal(MethodKind.AnonymousFunction, ((IMethodSymbol)parameterSymbol.ContainingSymbol).MethodKind); } [WorkItem(529096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529096")] [Fact] public void MemberAccessExpressionResults() { var text = @" class C { public static int A; public static byte B() { return 3; } public static string D { get; set; } static void Main(string[] args) { /*<bind0>*/C.A/*</bind0>*/; /*<bind1>*/C.B/*</bind1>*/(); /*<bind2>*/C.D/*</bind2>*/; /*<bind3>*/C.B()/*</bind3>*/; int goo = /*<bind4>*/C.B()/*</bind4>*/; goo = /*<bind5>*/C.B/*</bind5>*/(); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); for (int i = 0; i < exprs.Count; i++) { var expr = exprs[i]; var symbolInfo = model.GetSymbolInfo(expr); Assert.NotNull(symbolInfo.Symbol); var typeInfo = model.GetTypeInfo(expr); switch (i) { case 0: Assert.Equal("A", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); break; case 1: case 5: Assert.Equal("B", symbolInfo.Symbol.Name); Assert.Null(typeInfo.Type); break; case 2: Assert.Equal("D", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.String", typeInfo.ConvertedType.ToTestDisplayString()); break; case 3: Assert.Equal("B", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.Byte", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Byte", typeInfo.ConvertedType.ToTestDisplayString()); break; case 4: Assert.Equal("B", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.Byte", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); break; } // switch } } [WorkItem(543554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543554")] [Fact] public void SemanticInfoForUncheckedExpression() { var text = @" public class A { static void Main() { Console.WriteLine(/*<bind>*/unchecked(42 + 42.1)/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal("System.Double System.Double.op_Addition(System.Double left, System.Double right)", sym.Symbol.ToTestDisplayString()); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.Identity, conv.Kind); Assert.Equal(SpecialType.System_Double, info.Type.SpecialType); Assert.Equal(SpecialType.System_Double, info.ConvertedType.SpecialType); } [WorkItem(543554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543554")] [Fact] public void SemanticInfoForCheckedExpression() { var text = @" class Program { public static int Add(int a, int b) { return /*<bind>*/checked(a+b)/*</bind>*/; } } "; var comp = CreateCompilation(text); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal("System.Int32 System.Int32.op_Addition(System.Int32 left, System.Int32 right)", sym.Symbol.ToTestDisplayString()); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.Identity, conv.Kind); Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, info.ConvertedType.SpecialType); } [WorkItem(543554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543554")] [Fact] public void CheckedUncheckedExpression() { var text = @" class Test { public void F() { int y = /*<bind>*/(checked(unchecked((1))))/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetTypeInfo(expr); Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, info.ConvertedType.SpecialType); } [WorkItem(543543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543543")] [Fact] public void SymbolInfoForImplicitOperatorParameter() { var text = @" class Program { public Program(string s) { } public static implicit operator Program(string str) { return new Program(/*<bind>*/str/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetSymbolInfo(expr); var symbol = info.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal(MethodKind.Conversion, ((IMethodSymbol)symbol.ContainingSymbol).MethodKind); } [WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")] [WorkItem(543560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543560")] [Fact] public void BrokenPropertyDeclaration() { var source = @" using System; Class Program // this will get a Property declaration ... *sigh* { static void Main(string[] args) { Func<int, int> f = /*<bind0>*/x/*</bind0>*/ => x + 1; } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<ParameterSyntax>().First(); var declaredSymbol = model.GetDeclaredSymbol(expr); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedBinaryOperator() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } static void Main() { C c1 = new C(); C c2 = new C(); C c3 = /*<bind>*/c1 + c2/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.AdditionOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedLogicalOperator() { var text = @" class C { public static C operator &(C c1, C c2) { return c1 ?? c2; } public static bool operator true(C c) { return true; } public static bool operator false(C c) { return false; } static void Main() { C c1 = new C(); C c2 = new C(); C c3 = /*<bind>*/c1 && c2/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.BitwiseAndOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedUnaryOperator() { var text = @" class C { public static C operator+(C c1) { return c1; } static void Main() { C c1 = new C(); C c2 = /*<bind>*/+c1/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.UnaryPlusOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedExplicitConversion() { var text = @" class C { public static explicit operator C(int i) { return null; } static void Main() { C c1 = /*<bind>*/(C)1/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.ExplicitConversionName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedImplicitConversion() { var text = @" class C { public static implicit operator C(int i) { return null; } static void Main() { C c1 = /*<bind>*/(C)1/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.ImplicitConversionName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedTrueOperator() { var text = @" class C { public static bool operator true(C c) { return true; } public static bool operator false(C c) { return false; } static void Main() { C c = new C(); if (/*<bind>*/c/*</bind>*/) { } } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var type = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); var symbol = symbolInfo.Symbol; Assert.Equal(SymbolKind.Local, symbol.Kind); Assert.Equal("c", symbol.Name); Assert.Equal(type, ((ILocalSymbol)symbol).Type); var typeInfo = model.GetTypeInfo(expr); Assert.Equal(type, typeInfo.Type); Assert.Equal(type, typeInfo.ConvertedType); var conv = model.GetConversion(expr); Assert.Equal(Conversion.Identity, conv); Assert.False(model.GetConstantValue(expr).HasValue); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedIncrement() { var text = @" class C { public static C operator ++(C c) { return c; } static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1++/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.IncrementOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedCompoundAssignment() { var text = @" class C { public static C operator +(C c1, C c2) { return c1 ?? c2; } static void Main() { C c1 = new C(); C c2 = new C(); /*<bind>*/c1 += c2/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.AdditionOperatorName); } private void CheckOperatorSemanticInfo(string text, string operatorName) { var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operatorSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>(operatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal(operatorSymbol, symbolInfo.Symbol); var method = (IMethodSymbol)symbolInfo.Symbol; var returnType = method.ReturnType; var typeInfo = model.GetTypeInfo(expr); Assert.Equal(returnType, typeInfo.Type); Assert.Equal(returnType, typeInfo.ConvertedType); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.Identity, conv.Kind); Assert.False(model.GetConstantValue(expr).HasValue); } [Fact, WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550"), WorkItem(543439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543439")] public void SymbolInfoForUserDefinedConversionOverloadResolutionFailure() { var text = @" struct S { public static explicit operator S(string s) { return default(S); } public static explicit operator S(System.Text.StringBuilder s) { return default(S); } static void Main() { S s = /*<bind>*/(S)null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var conversions = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("S").GetMembers(WellKnownMemberNames.ExplicitConversionName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(conversions, EqualityComparer<ISymbol>.Default)); } [Fact, WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550"), WorkItem(543439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543439")] public void SymbolInfoForUserDefinedConversionOverloadResolutionFailureEmpty() { var text = @" struct S { static void Main() { S s = /*<bind>*/(S)null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var conversions = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("S").GetMembers(WellKnownMemberNames.ExplicitConversionName); Assert.Equal(0, conversions.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedUnaryOperatorOverloadResolutionFailure() { var il = @" .class public auto ansi beforefieldinit UnaryOperator extends [mscorlib]System.Object { .method public hidebysig specialname static class UnaryOperator op_UnaryPlus(class UnaryOperator unaryOperator) cil managed { ldnull throw } // Differs only by return type .method public hidebysig specialname static string op_UnaryPlus(class UnaryOperator unaryOperator) cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var text = @" class Program { static void Main() { UnaryOperator u1 = new UnaryOperator(); UnaryOperator u2 = /*<bind>*/+u1/*</bind>*/; } } "; var comp = (Compilation)CreateCompilationWithILAndMscorlib40(text, il); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("UnaryOperator").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedUnaryOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c1 = new C(); C c2 = /*<bind>*/+c1/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedIncrementOperatorOverloadResolutionFailure() { var il = @" .class public auto ansi beforefieldinit IncrementOperator extends [mscorlib]System.Object { .method public hidebysig specialname static class IncrementOperator op_Increment(class IncrementOperator incrementOperator) cil managed { ldnull throw } .method public hidebysig specialname static string op_Increment(class IncrementOperator incrementOperator) cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var text = @" class Program { static void Main() { IncrementOperator i1 = new IncrementOperator(); IncrementOperator i2 = /*<bind>*/i1++/*</bind>*/; } } "; var comp = (Compilation)CreateCompilationWithILAndMscorlib40(text, il); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("IncrementOperator").GetMembers(WellKnownMemberNames.IncrementOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedIncrementOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1++/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.IncrementOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedBinaryOperatorOverloadResolutionFailure() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } public static C operator+(C c1, string s) { return c1; } static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1 + null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedBinaryOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1 + null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("System.String System.String.op_Addition(System.Object left, System.String right)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedCompoundAssignmentOperatorOverloadResolutionFailure() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } public static C operator+(C c1, string s) { return c1; } static void Main() { C c = new C(); /*<bind>*/c += null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedCompoundAssignmentOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c = new C(); /*<bind>*/c += null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("System.String System.String.op_Addition(System.Object left, System.String right)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550"), WorkItem(529158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529158")] [Fact] public void MethodGroupForUserDefinedBinaryOperator() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } public static C operator+(C c1, int i) { return c1; } static void Main() { C c1 = new C(); C c2 = new C(); C c3 = /*<bind>*/c1 + c2/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName).Cast<IMethodSymbol>(); var operatorSymbol = operators.Where(method => method.Parameters[0].Type.Equals(method.Parameters[1].Type, SymbolEqualityComparer.ConsiderEverything)).Single(); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal(operatorSymbol, symbolInfo.Symbol); // NOTE: This check captures, rather than enforces, the current behavior (i.e. feel free to change it). var memberGroup = model.GetMemberGroup(expr); Assert.Equal(0, memberGroup.Length); } [Fact] public void CacheDuplicates() { var text = @" class C { static void Main() { long l = /*<bind>*/(long)1/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); bool sawWrongConversionKind = false; ThreadStart ts = () => sawWrongConversionKind |= ConversionKind.Identity != model.GetConversion(expr).Kind; Thread[] threads = new Thread[4]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(ts); } foreach (Thread t in threads) { t.Start(); } foreach (Thread t in threads) { t.Join(); } Assert.False(sawWrongConversionKind); } [WorkItem(543674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543674")] [Fact()] public void SemanticInfo_NormalVsLiftedUserDefinedImplicitConversion() { string text = @" using System; struct G { } struct L { public static implicit operator G(L l) { return default(G); } } class Z { public static void Main() { MNG(/*<bind>*/default(L)/*</bind>*/); } static void MNG(G? g) { } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var gType = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("G"); var mngMethod = (IMethodSymbol)comp.GlobalNamespace.GetMember<INamedTypeSymbol>("Z").GetMembers("MNG").First(); var gNullableType = mngMethod.GetParameterType(0); Assert.True(gNullableType.IsNullableType(), "MNG parameter is not a nullable type?"); Assert.Equal(gType, gNullableType.StrippedType()); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var conversion = model.ClassifyConversion(expr, gNullableType); CheckIsAssignableTo(model, expr); // Here we have a situation where Roslyn deliberately violates the specification in order // to be compatible with the native compiler. // // The specification states that there are two applicable candidates: We can use // the "lifted" operator from L? to G?, or we can use the unlifted operator // from L to G, and then convert the G that comes out the back end to G?. // The specification says that the second conversion is the better conversion. // Therefore, the conversion on the "front end" should be an identity conversion, // and the conversion on the "back end" of the user-defined conversion should // be an implicit nullable conversion. // // This is not at all what the native compiler does, and we match the native // compiler behavior. The native compiler says that there is a "half lifted" // conversion from L-->G?, and that this is the winner. Therefore the conversion // "on the back end" of the user-defined conversion is in fact an *identity* // conversion, even though obviously we are going to have to // do code generation as though it was an implicit nullable conversion. Assert.Equal(ConversionKind.Identity, conversion.UserDefinedFromConversion.Kind); Assert.Equal(ConversionKind.Identity, conversion.UserDefinedToConversion.Kind); Assert.Equal("ImplicitUserDefined", conversion.ToString()); } [WorkItem(543715, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543715")] [Fact] public void SemanticInfo_NormalVsLiftedUserDefinedConversion_ImplicitConversion() { string text = @" using System; struct G {} struct M { public static implicit operator G(M m) { System.Console.WriteLine(1); return default(G); } public static implicit operator G(M? m) {System.Console.WriteLine(2); return default(G); } } class Z { public static void Main() { M? m = new M(); MNG(/*<bind>*/m/*</bind>*/); } static void MNG(G? g) { } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var gType = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("G"); var mngMethod = (IMethodSymbol)comp.GlobalNamespace.GetMember<INamedTypeSymbol>("Z").GetMembers("MNG").First(); var gNullableType = mngMethod.GetParameterType(0); Assert.True(gNullableType.IsNullableType(), "MNG parameter is not a nullable type?"); Assert.Equal(gType, gNullableType.StrippedType()); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var conversion = model.ClassifyConversion(expr, gNullableType); CheckIsAssignableTo(model, expr); Assert.Equal(ConversionKind.ImplicitUserDefined, conversion.Kind); // Dev10 violates the spec for finding the most specific operator for an implicit user-defined conversion. // SPEC: • Find the most specific conversion operator: // SPEC: (a) If U contains exactly one user-defined conversion operator that converts from SX to TX, then this is the most specific conversion operator. // SPEC: (b) Otherwise, if U contains exactly one lifted conversion operator that converts from SX to TX, then this is the most specific conversion operator. // SPEC: (c) Otherwise, the conversion is ambiguous and a compile-time error occurs. // In this test we try to classify conversion from M? to G?. // 1) Classify conversion establishes that SX: M? and TX: G?. // 2) Most specific conversion operator from M? to G?: // (a) does not hold here as neither of the implicit operators convert from M? to G? // (b) does hold here as the lifted form of "implicit operator G(M m)" converts from M? to G? // Hence "operator G(M m)" must be chosen in lifted form, but Dev10 chooses "G M.op_Implicit(System.Nullable<M> m)" in normal form. // We may want to maintain compatibility with Dev10. Assert.Equal("G M.op_Implicit(M? m)", conversion.MethodSymbol.ToTestDisplayString()); Assert.Equal("ImplicitUserDefined", conversion.ToString()); } [Fact] public void AmbiguousImplicitConversionOverloadResolution1() { var source = @" public class A { static public implicit operator A(B b) { return default(A); } } public class B { static public implicit operator A(B b) { return default(A); } } class Test { static void M(A a) { } static void M(object o) { } static void Main() { B b = new B(); /*<bind>*/M(b)/*</bind>*/; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (26,21): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A' Diagnostic(ErrorCode.ERR_AmbigUDConv, "b").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A")); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = (InvocationExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("void Test.M(A a)", symbolInfo.Symbol.ToTestDisplayString()); var argexpr = expr.ArgumentList.Arguments.Single().Expression; var argTypeInfo = model.GetTypeInfo(argexpr); Assert.Equal("B", argTypeInfo.Type.ToTestDisplayString()); Assert.Equal("A", argTypeInfo.ConvertedType.ToTestDisplayString()); var argConversion = model.GetConversion(argexpr); Assert.Equal(ConversionKind.ImplicitUserDefined, argConversion.Kind); Assert.False(argConversion.IsValid); Assert.Null(argConversion.Method); } [Fact] public void AmbiguousImplicitConversionOverloadResolution2() { var source = @" public class A { static public implicit operator A(B<A> b) { return default(A); } } public class B<T> { static public implicit operator T(B<T> b) { return default(T); } } class C { static void M(A a) { } static void M<T>(T t) { } static void Main() { B<A> b = new B<A>(); /*<bind>*/M(b)/*</bind>*/; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); // since no conversion is performed, the ambiguity doesn't matter var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = (InvocationExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("void C.M<B<A>>(B<A> t)", symbolInfo.Symbol.ToTestDisplayString()); var argexpr = expr.ArgumentList.Arguments.Single().Expression; var argTypeInfo = model.GetTypeInfo(argexpr); Assert.Equal("B<A>", argTypeInfo.Type.ToTestDisplayString()); Assert.Equal("B<A>", argTypeInfo.ConvertedType.ToTestDisplayString()); var argConversion = model.GetConversion(argexpr); Assert.Equal(ConversionKind.Identity, argConversion.Kind); Assert.True(argConversion.IsValid); Assert.Null(argConversion.Method); } [Fact] public void DefaultParameterLocalScope() { var source = @" public class A { static void Main(string[] args, int a = /*<bind>*/System/*</bind>*/.) { } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal("System", expr.ToString()); var info = model.GetSemanticInfoSummary(expr); //Shouldn't throw/assert Assert.Equal(SymbolKind.Namespace, info.Symbol.Kind); } [Fact] public void PinvokeSemanticModel() { var source = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""user32.dll"", CharSet = CharSet.Unicode, ExactSpelling = false, EntryPoint = ""MessageBox"")] public static extern int MessageBox(IntPtr hwnd, string t, string c, UInt32 t2); static void Main() { /*<bind>*/MessageBox(IntPtr.Zero, """", """", 1)/*</bind>*/; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = (InvocationExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal("MessageBox(IntPtr.Zero, \"\", \"\", 1)", expr.ToString()); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("C.MessageBox(System.IntPtr, string, string, uint)", symbolInfo.Symbol.ToDisplayString()); var argTypeInfo = model.GetTypeInfo(expr.ArgumentList.Arguments.First().Expression); Assert.Equal("System.IntPtr", argTypeInfo.Type.ToTestDisplayString()); Assert.Equal("System.IntPtr", argTypeInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void ImplicitBoxingConversion1() { var source = @" class C { static void Main() { object o = 1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var conv = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Boxing, conv.Kind); } [Fact] public void ImplicitBoxingConversion2() { var source = @" class C { static void Main() { object o = (long)1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var literalConversion = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, literalConversion.Kind); var cast = (CastExpressionSyntax)literal.Parent; var castTypeInfo = model.GetTypeInfo(cast); var castConversion = model.GetConversion(cast); Assert.Equal(SpecialType.System_Int64, castTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, castTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Boxing, castConversion.Kind); } [Fact] public void ExplicitBoxingConversion1() { var source = @" class C { static void Main() { object o = (object)1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var literalConversion = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, literalConversion.Kind); var cast = (CastExpressionSyntax)literal.Parent; var castTypeInfo = model.GetTypeInfo(cast); var castConversion = model.GetConversion(cast); Assert.Equal(SpecialType.System_Object, castTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, castTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, castConversion.Kind); Assert.Equal(ConversionKind.Boxing, model.ClassifyConversion(literal, castTypeInfo.Type).Kind); CheckIsAssignableTo(model, literal); } [Fact] public void ExplicitBoxingConversion2() { var source = @" class C { static void Main() { object o = (object)(long)1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var literalConversion = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, literalConversion.Kind); var cast1 = (CastExpressionSyntax)literal.Parent; var cast1TypeInfo = model.GetTypeInfo(cast1); var cast1Conversion = model.GetConversion(cast1); Assert.Equal(SpecialType.System_Int64, cast1TypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int64, cast1TypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, cast1Conversion.Kind); // Note that this reflects the hypothetical conversion, not the cast in the code. Assert.Equal(ConversionKind.ImplicitNumeric, model.ClassifyConversion(literal, cast1TypeInfo.Type).Kind); CheckIsAssignableTo(model, literal); var cast2 = (CastExpressionSyntax)cast1.Parent; var cast2TypeInfo = model.GetTypeInfo(cast2); var cast2Conversion = model.GetConversion(cast2); Assert.Equal(SpecialType.System_Object, cast2TypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, cast2TypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, cast2Conversion.Kind); Assert.Equal(ConversionKind.Boxing, model.ClassifyConversion(cast1, cast2TypeInfo.Type).Kind); CheckIsAssignableTo(model, cast1); } [WorkItem(545136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545136")] [WorkItem(538320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538320")] [Fact()] // TODO: Dev10 does not report ERR_SameFullNameAggAgg here - source wins. public void SpecialTypeInSourceAndMetadata() { var text = @" using System; namespace System { public struct Void { static void Main() { System./*<bind>*/Void/*</bind>*/.Equals(1, 1); } } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("System.Void", symbolInfo.Symbol.ToString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [Fact] public void SpeculativelyBindMethodGroup1() { var text = @" using System; class C { static void M() { int here; } } "; var compilation = (Compilation)CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" C.M"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), info.CandidateSymbols.Single()); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [Fact] public void SpeculativelyBindMethodGroup2() { var text = @" using System; class C { static void M() { int here; } static void M(int x) { } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" C.M"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); Assert.Equal(2, info.CandidateSymbols.Length); } [WorkItem(546046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546046")] [Fact] public void UnambiguousMethodGroupWithoutBoundParent1() { var text = @" using System; class C { static void M() { /*<bind>*/M/*</bind>*/ "; var compilation = (Compilation)CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, syntax.Kind()); var info = model.GetSymbolInfo(syntax); Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), info.CandidateSymbols.Single()); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); } [WorkItem(546046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546046")] [Fact] public void UnambiguousMethodGroupWithoutBoundParent2() { var text = @" using System; class C { static void M() { /*<bind>*/M/*</bind>*/[] "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, syntax.Kind()); var info = model.GetSymbolInfo(syntax); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.NotATypeOrNamespace, info.CandidateReason); Assert.Equal(1, info.CandidateSymbols.Length); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [ClrOnlyFact] public void SpeculativelyBindPropertyGroup1() { var source1 = @"Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface IA Property P(o As Object) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @" using System; class C { static void M(IA a) { int here; } } "; var compilation = (Compilation)CreateCompilation(source2, new[] { reference1 }, assemblyName: "SpeculativelyBindPropertyGroup"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = source2.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" a.P"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("IA").GetMember<IPropertySymbol>("P"), info.Symbol); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [ClrOnlyFact] public void SpeculativelyBindPropertyGroup2() { var source1 = @"Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface IA Property P(o As Object) As Object Property P(x As Object, y As Object) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @" using System; class C { static void M(IA a) { int here; } } "; var compilation = CreateCompilation(source2, new[] { reference1 }, assemblyName: "SpeculativelyBindPropertyGroup"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = source2.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" a.P"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); Assert.Equal(2, info.CandidateSymbols.Length); } // There is no test analogous to UnambiguousMethodGroupWithoutBoundParent1 because // a.P does not yield a bound property group - it yields a bound indexer access // (i.e. it doesn't actually hit the code path that formerly contained the assert). //[WorkItem(15177)] //[Fact] //public void UnambiguousPropertyGroupWithoutBoundParent1() [WorkItem(546117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546117")] [ClrOnlyFact] public void UnambiguousPropertyGroupWithoutBoundParent2() { var source1 = @"Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface IA Property P(o As Object) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @" using System; class C { static void M(IA a) { /*<bind>*/a.P/*</bind>*/[] "; var compilation = CreateCompilation(source2, new[] { reference1 }, assemblyName: "SpeculativelyBindPropertyGroup"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.QualifiedName, syntax.Kind()); var info = model.GetSymbolInfo(syntax); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.NotATypeOrNamespace, info.CandidateReason); Assert.Equal(1, info.CandidateSymbols.Length); } [WorkItem(544648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544648")] [Fact] public void SpeculativelyBindExtensionMethod() { var source = @" using System; using System.Collections.Generic; using System.Reflection; static class Program { static void Main() { FieldInfo[] fields = typeof(Exception).GetFields(); Console.WriteLine(/*<bind>*/fields.Any((Func<FieldInfo, bool>)(field => field.IsStatic))/*</bind>*/); } static bool Any<T>(this IEnumerable<T> s, Func<T, bool> predicate) { return false; } static bool Any<T>(this ICollection<T> s, Func<T, bool> predicate) { return true; } } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var originalSyntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.InvocationExpression, originalSyntax.Kind()); var info1 = model.GetSymbolInfo(originalSyntax); var method1 = info1.Symbol as IMethodSymbol; Assert.NotNull(method1); Assert.Equal("System.Boolean System.Collections.Generic.ICollection<System.Reflection.FieldInfo>.Any<System.Reflection.FieldInfo>(System.Func<System.Reflection.FieldInfo, System.Boolean> predicate)", method1.ToTestDisplayString()); Assert.Same(method1.ReducedFrom.TypeParameters[0], method1.TypeParameters[0].ReducedFrom); Assert.Null(method1.ReducedFrom.TypeParameters[0].ReducedFrom); Assert.Equal("System.Boolean Program.Any<T>(this System.Collections.Generic.ICollection<T> s, System.Func<T, System.Boolean> predicate)", method1.ReducedFrom.ToTestDisplayString()); Assert.Equal("System.Collections.Generic.ICollection<System.Reflection.FieldInfo>", method1.ReceiverType.ToTestDisplayString()); Assert.Equal("System.Reflection.FieldInfo", method1.GetTypeInferredDuringReduction(method1.ReducedFrom.TypeParameters[0]).ToTestDisplayString()); Assert.Throws<InvalidOperationException>(() => method1.ReducedFrom.GetTypeInferredDuringReduction(null)); Assert.Throws<ArgumentNullException>(() => method1.GetTypeInferredDuringReduction(null)); Assert.Throws<ArgumentException>(() => method1.GetTypeInferredDuringReduction( comp.Assembly.GlobalNamespace.GetMember<INamedTypeSymbol>("Program").GetMembers("Any"). Where((m) => (object)m != (object)method1.ReducedFrom).Cast<IMethodSymbol>().Single().TypeParameters[0])); Assert.Equal("Any", method1.Name); var reducedFrom1 = method1.GetSymbol().CallsiteReducedFromMethod; Assert.NotNull(reducedFrom1); Assert.Equal("System.Boolean Program.Any<System.Reflection.FieldInfo>(this System.Collections.Generic.ICollection<System.Reflection.FieldInfo> s, System.Func<System.Reflection.FieldInfo, System.Boolean> predicate)", reducedFrom1.ToTestDisplayString()); Assert.Equal("Program", reducedFrom1.ReceiverType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Collections_Generic_ICollection_T, ((TypeSymbol)reducedFrom1.Parameters[0].Type.OriginalDefinition).SpecialType); var speculativeSyntax = SyntaxFactory.ParseExpression("fields.Any((field => field.IsStatic))"); //cast removed Assert.Equal(SyntaxKind.InvocationExpression, speculativeSyntax.Kind()); var info2 = model.GetSpeculativeSymbolInfo(originalSyntax.SpanStart, speculativeSyntax, SpeculativeBindingOption.BindAsExpression); var method2 = info2.Symbol as IMethodSymbol; Assert.NotNull(method2); Assert.Equal("Any", method2.Name); var reducedFrom2 = method2.GetSymbol().CallsiteReducedFromMethod; Assert.NotNull(reducedFrom2); Assert.Equal(SpecialType.System_Collections_Generic_ICollection_T, ((TypeSymbol)reducedFrom2.Parameters[0].Type.OriginalDefinition).SpecialType); Assert.Equal(reducedFrom1, reducedFrom2); Assert.Equal(method1, method2); } /// <summary> /// This test reproduces the issue we were seeing in DevDiv #13366: LocalSymbol.SetType was asserting /// because it was set to IEnumerable&lt;int&gt; before binding the declaration of x but to an error /// type after binding the declaration of x. /// </summary> [WorkItem(545097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545097")] [Fact] public void NameConflictDuringLambdaBinding1() { var source = @" using System.Linq; class C { static void Main() { var x = 0; var q = from e in """" let x = 2 select x; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var localDecls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclarationSyntax>(); var localDecl1 = localDecls.First(); Assert.Equal("x", localDecl1.Variables.Single().Identifier.ValueText); var localDecl2 = localDecls.Last(); Assert.Equal("q", localDecl2.Variables.Single().Identifier.ValueText); var model = comp.GetSemanticModel(tree); var info0 = model.GetSymbolInfo(localDecl2.Type); Assert.Equal(SpecialType.System_Collections_Generic_IEnumerable_T, ((ITypeSymbol)info0.Symbol.OriginalDefinition).SpecialType); Assert.Equal(SpecialType.System_Int32, ((INamedTypeSymbol)info0.Symbol).TypeArguments.Single().SpecialType); var info1 = model.GetSymbolInfo(localDecl1.Type); Assert.Equal(SpecialType.System_Int32, ((ITypeSymbol)info1.Symbol).SpecialType); // This used to assert because the second binding would see the declaration of x and report CS7040, disrupting the delegate conversion. var info2 = model.GetSymbolInfo(localDecl2.Type); Assert.Equal(SpecialType.System_Collections_Generic_IEnumerable_T, ((ITypeSymbol)info2.Symbol.OriginalDefinition).SpecialType); Assert.Equal(SpecialType.System_Int32, ((INamedTypeSymbol)info2.Symbol).TypeArguments.Single().SpecialType); comp.VerifyDiagnostics( // (9,34): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // var q = from e in "" let x = 2 select x; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(9, 34), // (8,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(8, 13) ); } /// <summary> /// This test reverses the order of statement binding from NameConflictDuringLambdaBinding2 to confirm that /// the results are the same. /// </summary> [WorkItem(545097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545097")] [Fact] public void NameConflictDuringLambdaBinding2() { var source = @" using System.Linq; class C { static void Main() { var x = 0; var q = from e in """" let x = 2 select x; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var localDecls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclarationSyntax>(); var localDecl1 = localDecls.First(); Assert.Equal("x", localDecl1.Variables.Single().Identifier.ValueText); var localDecl2 = localDecls.Last(); Assert.Equal("q", localDecl2.Variables.Single().Identifier.ValueText); var model = comp.GetSemanticModel(tree); var info1 = model.GetSymbolInfo(localDecl1.Type); Assert.Equal(SpecialType.System_Int32, ((ITypeSymbol)info1.Symbol).SpecialType); // This used to assert because the second binding would see the declaration of x and report CS7040, disrupting the delegate conversion. var info2 = model.GetSymbolInfo(localDecl2.Type); Assert.Equal(SpecialType.System_Collections_Generic_IEnumerable_T, ((ITypeSymbol)info2.Symbol.OriginalDefinition).SpecialType); Assert.Equal(SpecialType.System_Int32, ((INamedTypeSymbol)info2.Symbol).TypeArguments.Single().SpecialType); comp.VerifyDiagnostics( // (9,34): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // var q = from e in "" let x = 2 select x; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(9, 34), // (8,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(8, 13) ); } [WorkItem(546263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546263")] [Fact] public void SpeculativeSymbolInfoForOmittedTypeArgumentSyntaxNode() { var text = @"namespace N2 { using N1; class Test { class N1<G1> {} static void Main() { int res = 0; N1<int> n1 = new N1<int>(); global::N1 < > .C1 c1 = null; } } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("< >", StringComparison.Ordinal); var syntax = tree.GetCompilationUnitRoot().FindToken(position).Parent.DescendantNodesAndSelf().OfType<OmittedTypeArgumentSyntax>().Single(); var info = model.GetSpeculativeSymbolInfo(syntax.SpanStart, syntax, SpeculativeBindingOption.BindAsTypeOrNamespace); Assert.Null(info.Symbol); } [WorkItem(530313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530313")] [Fact] public void SpeculativeTypeInfoForOmittedTypeArgumentSyntaxNode() { var text = @"namespace N2 { using N1; class Test { class N1<G1> {} static void Main() { int res = 0; N1<int> n1 = new N1<int>(); global::N1 < > .C1 c1 = null; } } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("< >", StringComparison.Ordinal); var syntax = tree.GetCompilationUnitRoot().FindToken(position).Parent.DescendantNodesAndSelf().OfType<OmittedTypeArgumentSyntax>().Single(); var info = model.GetSpeculativeTypeInfo(syntax.SpanStart, syntax, SpeculativeBindingOption.BindAsTypeOrNamespace); Assert.Equal(TypeInfo.None, info); } [WorkItem(546266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546266")] [Fact] public void SpeculativeTypeInfoForGenericNameSyntaxWithinTypeOfInsideAnonMethod() { var text = @" delegate void Del(); class C { public void M1() { Del d = delegate () { var v1 = typeof(S<,,,>); }; } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("S<,,,>", StringComparison.Ordinal); var syntax = tree.GetCompilationUnitRoot().FindToken(position).Parent.DescendantNodesAndSelf().OfType<GenericNameSyntax>().Single(); var info = model.GetSpeculativeTypeInfo(syntax.SpanStart, syntax, SpeculativeBindingOption.BindAsTypeOrNamespace); Assert.NotNull(info.Type); } [WorkItem(547160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547160")] [Fact, WorkItem(531496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531496")] public void SemanticInfoForOmittedTypeArgumentInIncompleteMember() { var text = @" class Test { C<> "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<OmittedTypeArgumentSyntax>().Single(); var info = model.GetSemanticInfoSummary(syntax); Assert.Null(info.Alias); Assert.Equal(CandidateReason.None, info.CandidateReason); Assert.True(info.CandidateSymbols.IsEmpty); Assert.False(info.ConstantValue.HasValue); Assert.Null(info.ConvertedType); Assert.Equal(Conversion.Identity, info.ImplicitConversion); Assert.False(info.IsCompileTimeConstant); Assert.True(info.MemberGroup.IsEmpty); Assert.True(info.MethodGroup.IsEmpty); Assert.Null(info.Symbol); Assert.Null(info.Type); } [WorkItem(547160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547160")] [Fact, WorkItem(531496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531496")] public void CollectionInitializerSpeculativeInfo() { var text = @" class Test { } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var speculativeSyntax = SyntaxFactory.ParseExpression("new List { 1, 2 }"); var initializerSyntax = speculativeSyntax.DescendantNodesAndSelf().OfType<InitializerExpressionSyntax>().Single(); var symbolInfo = model.GetSpeculativeSymbolInfo(0, initializerSyntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); var typeInfo = model.GetSpeculativeTypeInfo(0, initializerSyntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(TypeInfo.None, typeInfo); } [WorkItem(531362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531362")] [Fact] public void DelegateElementAccess() { var text = @" class C { void M(bool b) { System.Action o = delegate { if (b) { } } [1]; } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (6,27): error CS0021: Cannot apply indexing with [] to an expression of type 'anonymous method' // System.Action o = delegate { if (b) { } } [1]; Diagnostic(ErrorCode.ERR_BadIndexLHS, "delegate { if (b) { } } [1]").WithArguments("anonymous method")); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Last(id => id.Identifier.ValueText == "b"); var info = model.GetSymbolInfo(syntax); } [Fact] public void EnumBitwiseComplement() { var text = @" using System; enum Color { Red, Green, Blue } class C { static void Main() { Func<Color, Color> f2 = x => /*<bind>*/~x/*</bind>*/; } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetTypeInfo(syntax); var conv = model.GetConversion(syntax); Assert.Equal(TypeKind.Enum, info.Type.TypeKind); Assert.Equal(ConversionKind.Identity, conv.Kind); } [WorkItem(531534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531534")] [Fact] public void LambdaOutsideMemberModel() { var text = @" int P { badAccessorName { M(env => env); "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Last(); var symbol = model.GetDeclaredSymbol(syntax); // Doesn't assert. Assert.Null(symbol); } [WorkItem(633340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633340")] [Fact] public void MemberOfInaccessibleType() { var text = @" class A { private class Nested { public class Another { } } } public class B : A { public Nested.Another a; } "; var compilation = (Compilation)CreateCompilation(text); var global = compilation.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var classNested = classA.GetMember<INamedTypeSymbol>("Nested"); var classAnother = classNested.GetMember<INamedTypeSymbol>("Another"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var fieldSyntax = tree.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>().Single(); var qualifiedSyntax = (QualifiedNameSyntax)fieldSyntax.Declaration.Type; var leftSyntax = qualifiedSyntax.Left; var rightSyntax = qualifiedSyntax.Right; var leftInfo = model.GetSymbolInfo(leftSyntax); Assert.Equal(CandidateReason.Inaccessible, leftInfo.CandidateReason); Assert.Equal(classNested, leftInfo.CandidateSymbols.Single()); var rightInfo = model.GetSymbolInfo(rightSyntax); Assert.Equal(CandidateReason.Inaccessible, rightInfo.CandidateReason); Assert.Equal(classAnother, rightInfo.CandidateSymbols.Single()); compilation.VerifyDiagnostics( // (12,14): error CS0060: Inconsistent accessibility: base type 'A' is less accessible than class 'B' // public class B : A Diagnostic(ErrorCode.ERR_BadVisBaseClass, "B").WithArguments("B", "A"), // (14,12): error CS0122: 'A.Nested' is inaccessible due to its protection level // public Nested.Another a; Diagnostic(ErrorCode.ERR_BadAccess, "Nested").WithArguments("A.Nested")); } [WorkItem(633340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633340")] [Fact] public void NotReferencableMemberOfInaccessibleType() { var text = @" class A { private class Nested { public int P { get; set; } } } class B : A { int Test(Nested nested) { return nested.get_P(); } } "; var compilation = (Compilation)CreateCompilation(text); var global = compilation.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var classNested = classA.GetMember<INamedTypeSymbol>("Nested"); var propertyP = classNested.GetMember<IPropertySymbol>("P"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccessSyntax = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var info = model.GetSymbolInfo(memberAccessSyntax); Assert.Equal(CandidateReason.NotReferencable, info.CandidateReason); Assert.Equal(propertyP.GetMethod, info.CandidateSymbols.Single()); compilation.VerifyDiagnostics( // (12,14): error CS0122: 'A.Nested' is inaccessible due to its protection level // int Test(Nested nested) Diagnostic(ErrorCode.ERR_BadAccess, "Nested").WithArguments("A.Nested"), // (14,23): error CS0571: 'A.Nested.P.get': cannot explicitly call operator or accessor // return nested.get_P(); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("A.Nested.P.get") ); } [WorkItem(633340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633340")] [Fact] public void AccessibleMemberOfInaccessibleType() { var text = @" public class A { private class Nested { } } public class B : A { void Test() { Nested.ReferenceEquals(null, null); // Actually object.ReferenceEquals. } } "; var compilation = (Compilation)CreateCompilation(text); var global = compilation.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var classNested = classA.GetMember<INamedTypeSymbol>("Nested"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var callSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var methodAccessSyntax = (MemberAccessExpressionSyntax)callSyntax.Expression; var nestedTypeAccessSyntax = methodAccessSyntax.Expression; var typeInfo = model.GetSymbolInfo(nestedTypeAccessSyntax); Assert.Equal(CandidateReason.Inaccessible, typeInfo.CandidateReason); Assert.Equal(classNested, typeInfo.CandidateSymbols.Single()); var methodInfo = model.GetSymbolInfo(callSyntax); Assert.Equal(compilation.GetSpecialTypeMember(SpecialMember.System_Object__ReferenceEquals), methodInfo.Symbol); compilation.VerifyDiagnostics( // (13,9): error CS0122: 'A.Nested' is inaccessible due to its protection level // Nested.ReferenceEquals(null, null); // Actually object.ReferenceEquals. Diagnostic(ErrorCode.ERR_BadAccess, "Nested").WithArguments("A.Nested")); } [WorkItem(530252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530252")] [Fact] public void MethodGroupHiddenSymbols1() { var text = @" class C { public override int GetHashCode() { return 0; } } struct S { public override int GetHashCode() { return 0; } } class Test { int M(C c) { return c.GetHashCode } int M(S s) { return s.GetHashCode } } "; var compilation = CreateCompilation(text); var global = compilation.GlobalNamespace; var classType = global.GetMember<NamedTypeSymbol>("C"); var structType = global.GetMember<NamedTypeSymbol>("S"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccesses = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().ToArray(); Assert.Equal(2, memberAccesses.Length); var classMemberAccess = memberAccesses[0]; var structMemberAccess = memberAccesses[1]; var classInfo = model.GetSymbolInfo(classMemberAccess); var structInfo = model.GetSymbolInfo(structMemberAccess); // Only one candidate. Assert.Equal(CandidateReason.OverloadResolutionFailure, classInfo.CandidateReason); Assert.Equal("System.Int32 C.GetHashCode()", classInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, structInfo.CandidateReason); Assert.Equal("System.Int32 S.GetHashCode()", structInfo.CandidateSymbols.Single().ToTestDisplayString()); } [WorkItem(530252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530252")] [Fact] public void MethodGroupHiddenSymbols2() { var text = @" class A { public virtual void M() { } } class B : A { public override void M() { } } class C : B { public override void M() { } } class Program { static void Main(string[] args) { C c = new C(); c.M } } "; var compilation = CreateCompilation(text); var classC = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccess = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var info = model.GetSymbolInfo(memberAccess); // Only one candidate. Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); Assert.Equal("void C.M()", info.CandidateSymbols.Single().ToTestDisplayString()); } [Fact] [WorkItem(645512, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645512")] public void LookupProtectedMemberOnConstrainedTypeParameter() { var source = @" class A { protected void Goo() { } } class C : A { public void Bar<T>(T t, C c) where T : C { t.Goo(); c.Goo(); } } "; var comp = (Compilation)CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var methodGoo = classA.GetMember<IMethodSymbol>("Goo"); var classC = global.GetMember<INamedTypeSymbol>("C"); var methodBar = classC.GetMember<IMethodSymbol>("Bar"); var paramType0 = methodBar.GetParameterType(0); Assert.Equal(TypeKind.TypeParameter, paramType0.TypeKind); var paramType1 = methodBar.GetParameterType(1); Assert.Equal(TypeKind.Class, paramType1.TypeKind); int position = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First().SpanStart; Assert.Contains("Goo", model.LookupNames(position, paramType0)); Assert.Contains("Goo", model.LookupNames(position, paramType1)); } [Fact] [WorkItem(645512, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645512")] public void LookupProtectedMemberOnConstrainedTypeParameter2() { var source = @" class A { protected void Goo() { } } class C : A { public void Bar<T, U>(T t, C c) where T : U where U : C { t.Goo(); c.Goo(); } } "; var comp = (Compilation)CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var methodGoo = classA.GetMember<IMethodSymbol>("Goo"); var classC = global.GetMember<INamedTypeSymbol>("C"); var methodBar = classC.GetMember<IMethodSymbol>("Bar"); var paramType0 = methodBar.GetParameterType(0); Assert.Equal(TypeKind.TypeParameter, paramType0.TypeKind); var paramType1 = methodBar.GetParameterType(1); Assert.Equal(TypeKind.Class, paramType1.TypeKind); int position = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First().SpanStart; Assert.Contains("Goo", model.LookupNames(position, paramType0)); Assert.Contains("Goo", model.LookupNames(position, paramType1)); } [Fact] [WorkItem(652583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/652583")] public void ParameterDefaultValueWithoutParameter() { var source = @" class A { protected void Goo(bool b, = true "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var trueLiteral = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal(SyntaxKind.TrueLiteralExpression, trueLiteral.Kind()); model.GetSymbolInfo(trueLiteral); var parameterSyntax = trueLiteral.FirstAncestorOrSelf<ParameterSyntax>(); Assert.Equal(SyntaxKind.Parameter, parameterSyntax.Kind()); model.GetDeclaredSymbol(parameterSyntax); } [Fact] [WorkItem(530791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530791")] public void Repro530791() { var source = @" class Program { static void Main(string[] args) { Test test = new Test(() => { return null; }); } } class Test { } "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(lambdaSyntax); var lambda = (IMethodSymbol)symbolInfo.Symbol; Assert.False(lambda.ReturnsVoid); Assert.Equal(SymbolKind.ErrorType, lambda.ReturnType.Kind); } [Fact] public void InvocationInLocalDeclarationInLambdaInConstructorInitializer() { var source = @" using System; public class C { public int M() { return null; } } public class Test { public Test() : this(c => { int i = c.M(); return i; }) { } public Test(Func<C, int> f) { } } "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(syntax); var methodSymbol = (IMethodSymbol)symbolInfo.Symbol; Assert.False(methodSymbol.ReturnsVoid); } [Fact] [WorkItem(654753, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/654753")] public void Repro654753() { var source = @" using System; using System.Collections.Generic; using System.Linq; public class C { private readonly C Instance = new C(); bool M(IDisposable d) { using(d) { bool any = this.Instance.GetList().OfType<D>().Any(); return any; } } IEnumerable<C> GetList() { return null; } } public class D : C { } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = source.IndexOf("this", StringComparison.Ordinal); var statement = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var newSyntax = SyntaxFactory.ParseExpression("Instance.GetList().OfType<D>().Any()"); var newStatement = statement.ReplaceNode(statement.Declaration.Variables[0].Initializer.Value, newSyntax); newSyntax = newStatement.Declaration.Variables[0].Initializer.Value; SemanticModel speculativeModel; bool success = model.TryGetSpeculativeSemanticModel(position, newStatement, out speculativeModel); Assert.True(success); Assert.NotNull(speculativeModel); var newSyntaxMemberAccess = newSyntax.DescendantNodesAndSelf().OfType<MemberAccessExpressionSyntax>(). Single(e => e.ToString() == "Instance.GetList().OfType<D>"); speculativeModel.GetTypeInfo(newSyntaxMemberAccess); } [Fact] [WorkItem(750557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750557")] public void MethodGroupFromMetadata() { var source = @" class Goo { delegate int D(int i); void M() { var v = ((D)(x => x)).Equals is bool; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = source.IndexOf("Equals", StringComparison.Ordinal); var equalsToken = tree.GetRoot().FindToken(position); var equalsNode = equalsToken.Parent; var symbolInfo = model.GetSymbolInfo(equalsNode); //note that we don't guarantee what symbol will come back on a method group in an is expression. Assert.Null(symbolInfo.Symbol); Assert.True(symbolInfo.CandidateSymbols.Length > 0); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); } [Fact, WorkItem(531304, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531304")] public void GetPreprocessingSymbolInfoForDefinedSymbol() { string sourceCode = @" #define X #if X //bind #define Z #endif #if Z //bind #endif // broken code cases #define A #if A + 1 //bind #endif #define B = 0 #if B //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "X //bind"); Assert.Equal("X", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "A + 1 //bind"); Assert.Equal("A", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "B //bind"); Assert.Equal("B", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); Assert.True(symbolInfo.Symbol.Equals(symbolInfo.Symbol)); Assert.False(symbolInfo.Symbol.Equals(null)); PreprocessingSymbolInfo symbolInfo2 = GetPreprocessingSymbolInfoForTest(sourceCode, "B //bind"); Assert.NotSame(symbolInfo.Symbol, symbolInfo2.Symbol); Assert.Equal(symbolInfo.Symbol, symbolInfo2.Symbol); Assert.Equal(symbolInfo.Symbol.GetHashCode(), symbolInfo2.Symbol.GetHashCode()); } [Fact, WorkItem(531304, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531304")] public void GetPreprocessingSymbolInfoForUndefinedSymbol() { string sourceCode = @" #define X #undef X #if X //bind #endif #if x //bind #endif #if Y //bind #define Z #endif #if Z //bind #endif // Not in preprocessor trivia #define A public class T { public int Goo(int A) { return A; //bind } } "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "X //bind"); Assert.Equal("X", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "x //bind"); Assert.Equal("x", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Y //bind"); Assert.Equal("Y", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "A; //bind"); Assert.Null(symbolInfo.Symbol); } [Fact, WorkItem(531304, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531304"), WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void GetPreprocessingSymbolInfoForSymbolDefinedLaterInSource() { string sourceCode = @" #if Z //bind #endif #define Z "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_01() { string sourceCode = @" #define Z #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_02() { string sourceCode = @" #if true #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_03() { string sourceCode = @" #if false #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_04() { string sourceCode = @" #if true #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_05() { string sourceCode = @" #if false #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_06() { string sourceCode = @" #if true #else #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_07() { string sourceCode = @" #if false #else #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_08() { string sourceCode = @" #if true #define Z #else #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_09() { string sourceCode = @" #if false #define Z #else #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_10() { string sourceCode = @" #if true #elif true #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_11() { string sourceCode = @" #if false #elif true #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_12() { string sourceCode = @" #if false #elif false #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_13() { string sourceCode = @" #if true #define Z #elif false #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_14() { string sourceCode = @" #if true #define Z #elif true #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_15() { string sourceCode = @" #if false #define Z #elif true #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_16() { string sourceCode = @" #if false #define Z #elif false #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_17() { string sourceCode = @" #if false #else #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_18() { string sourceCode = @" #if false #elif true #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_19() { string sourceCode = @" #if true #else #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_20() { string sourceCode = @" #if true #elif true #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_21() { string sourceCode = @" #if true #elif false #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_22() { string sourceCode = @" #if false #elif false #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [WorkItem(835391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835391")] [Fact] public void ConstructedErrorTypeValidation() { var text = @"class C1 : E1 { } class C2<T> : E2<T> { }"; var compilation = (Compilation)CreateCompilation(text); var objectType = compilation.GetSpecialType(SpecialType.System_Object); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); // Non-generic type. var type = (INamedTypeSymbol)model.GetDeclaredSymbol(root.Members[0]); Assert.False(type.IsGenericType); Assert.False(type.IsErrorType()); Assert.Throws<InvalidOperationException>(() => type.Construct(objectType)); // non-generic type // Non-generic error type. type = type.BaseType; Assert.False(type.IsGenericType); Assert.True(type.IsErrorType()); Assert.Throws<InvalidOperationException>(() => type.Construct(objectType)); // non-generic type // Generic type. type = (INamedTypeSymbol)model.GetDeclaredSymbol(root.Members[1]); Assert.True(type.IsGenericType); Assert.False(type.IsErrorType()); Assert.Throws<ArgumentException>(() => type.Construct(new ITypeSymbol[] { null })); // null type arg Assert.Throws<ArgumentException>(() => type.Construct()); // typeArgs.Length != Arity Assert.Throws<InvalidOperationException>(() => type.Construct(objectType).Construct(objectType)); // constructed type // Generic error type. type = type.BaseType.ConstructedFrom; Assert.True(type.IsGenericType); Assert.True(type.IsErrorType()); Assert.Throws<ArgumentException>(() => type.Construct(new ITypeSymbol[] { null })); // null type arg Assert.Throws<ArgumentException>(() => type.Construct()); // typeArgs.Length != Arity Assert.Throws<InvalidOperationException>(() => type.Construct(objectType).Construct(objectType)); // constructed type } [Fact] [WorkItem(849371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849371")] public void NestedLambdaErrorRecovery() { var source = @" using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main() { Task<IEnumerable<Task<A>>> teta = null; teta.ContinueWith(tasks => { var list = tasks.Result.Select(t => X(t.Result)); // Wrong argument type for X. list.ToString(); }); } static B X(int x) { return null; } class A { } class B { } } "; for (int i = 0; i < 10; i++) // Ten runs to ensure consistency. { var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (13,51): error CS1503: Argument 1: cannot convert from 'Program.A' to 'int' // var list = tasks.Result.Select(t => X(t.Result)); // Wrong argument type for X. Diagnostic(ErrorCode.ERR_BadArgType, "t.Result").WithArguments("1", "Program.A", "int").WithLocation(13, 51), // (13,30): error CS1061: 'System.Threading.Tasks.Task' does not contain a definition for 'Result' and no extension method 'Result' accepting a first argument of type 'System.Threading.Tasks.Task' could be found (are you missing a using directive or an assembly reference?) // var list = tasks.Result.Select(t => X(t.Result)); // Wrong argument type for X. Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Result").WithArguments("System.Threading.Tasks.Task", "Result").WithLocation(13, 30)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocationSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); var invocationInfo = model.GetSymbolInfo(invocationSyntax); Assert.Equal(CandidateReason.OverloadResolutionFailure, invocationInfo.CandidateReason); Assert.Null(invocationInfo.Symbol); Assert.NotEqual(0, invocationInfo.CandidateSymbols.Length); var parameterSyntax = invocationSyntax.DescendantNodes().OfType<ParameterSyntax>().First(); var parameterSymbol = model.GetDeclaredSymbol(parameterSyntax); Assert.Equal("System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<System.Threading.Tasks.Task<Program.A>>>", parameterSymbol.Type.ToTestDisplayString()); } } [WorkItem(849371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849371")] [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [WorkItem(854548, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854548")] [Fact] public void SemanticModelLambdaErrorRecovery() { var source = @" using System; class Program { static void Main() { M(() => 1); // Neither overload wins. } static void M(Func<string> a) { } static void M(Func<char> a) { } } "; { var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var otherFuncType = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(comp.GetSpecialType(SpecialType.System_Int32)); var typeInfo = model.GetTypeInfo(lambdaSyntax); Assert.Null(typeInfo.Type); Assert.NotEqual(otherFuncType, typeInfo.ConvertedType); } { var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var otherFuncType = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(comp.GetSpecialType(SpecialType.System_Int32)); var conversion = model.ClassifyConversion(lambdaSyntax, otherFuncType); CheckIsAssignableTo(model, lambdaSyntax); var typeInfo = model.GetTypeInfo(lambdaSyntax); Assert.Null(typeInfo.Type); Assert.NotEqual(otherFuncType, typeInfo.ConvertedType); // Not affected by call to ClassifyConversion. } } [Fact] [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] public void ClassifyConversionOnNull() { var source = @" class Program { static void Main() { M(null); // Ambiguous. } static void M(A a) { } static void M(B b) { } } class A { } class B { } class C { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); // Ambiguous. Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(6, 9)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var nullSyntax = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var typeC = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); var conversion = model.ClassifyConversion(nullSyntax, typeC); CheckIsAssignableTo(model, nullSyntax); Assert.Equal(ConversionKind.ImplicitReference, conversion.Kind); } [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [Fact] public void ClassifyConversionOnLambda() { var source = @" using System; class Program { static void Main() { M(() => null); } static void M(Func<A> a) { } } class A { } class B { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var typeB = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("B"); var typeFuncB = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(typeB); var conversion = model.ClassifyConversion(lambdaSyntax, typeFuncB); CheckIsAssignableTo(model, lambdaSyntax); Assert.Equal(ConversionKind.AnonymousFunction, conversion.Kind); } [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [Fact] public void ClassifyConversionOnAmbiguousLambda() { var source = @" using System; class Program { static void Main() { M(() => null); // Ambiguous. } static void M(Func<A> a) { } static void M(Func<B> b) { } } class A { } class B { } class C { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(System.Func<A>)' and 'Program.M(System.Func<B>)' // M(() => null); // Ambiguous. Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(System.Func<A>)", "Program.M(System.Func<B>)").WithLocation(8, 9)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var typeC = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); var typeFuncC = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(typeC); var conversion = model.ClassifyConversion(lambdaSyntax, typeFuncC); CheckIsAssignableTo(model, lambdaSyntax); Assert.Equal(ConversionKind.AnonymousFunction, conversion.Kind); } [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [Fact] public void ClassifyConversionOnAmbiguousMethodGroup() { var source = @" using System; class Base<T> { public A N(T t) { throw null; } public B N(int t) { throw null; } } class Derived : Base<int> { void Test() { M(N); // Ambiguous. } static void M(Func<int, A> a) { } static void M(Func<int, B> b) { } } class A { } class B { } class C { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Derived.M(System.Func<int, A>)' and 'Derived.M(System.Func<int, B>)' // M(N); // Ambiguous. Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Derived.M(System.Func<int, A>)", "Derived.M(System.Func<int, B>)").WithLocation(14, 9)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var methodGroupSyntax = tree.GetRoot().DescendantNodes().OfType<ArgumentSyntax>().Single().Expression; var global = comp.GlobalNamespace; var typeA = global.GetMember<INamedTypeSymbol>("A"); var typeB = global.GetMember<INamedTypeSymbol>("B"); var typeC = global.GetMember<INamedTypeSymbol>("C"); var typeInt = comp.GetSpecialType(SpecialType.System_Int32); var typeFunc = comp.GetWellKnownType(WellKnownType.System_Func_T2); var typeFuncA = typeFunc.Construct(typeInt, typeA); var typeFuncB = typeFunc.Construct(typeInt, typeB); var typeFuncC = typeFunc.Construct(typeInt, typeC); var conversionA = model.ClassifyConversion(methodGroupSyntax, typeFuncA); CheckIsAssignableTo(model, methodGroupSyntax); Assert.Equal(ConversionKind.MethodGroup, conversionA.Kind); var conversionB = model.ClassifyConversion(methodGroupSyntax, typeFuncB); Assert.Equal(ConversionKind.MethodGroup, conversionB.Kind); var conversionC = model.ClassifyConversion(methodGroupSyntax, typeFuncC); Assert.Equal(ConversionKind.NoConversion, conversionC.Kind); } [WorkItem(872064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872064")] [Fact] public void PartialMethodImplementationDiagnostics() { var file1 = @" namespace ConsoleApplication1 { class Program { static void Main(string[] args) { } } partial class MyPartialClass { partial void MyPartialMethod(MyUndefinedMethod m); } } "; var file2 = @" namespace ConsoleApplication1 { partial class MyPartialClass { partial void MyPartialMethod(MyUndefinedMethod m) { c = new MyUndefinedMethod(23, true); } } } "; var tree1 = Parse(file1); var tree2 = Parse(file2); var comp = CreateCompilation(new[] { tree1, tree2 }); var model = comp.GetSemanticModel(tree2); var errs = model.GetDiagnostics(); Assert.Equal(3, errs.Count()); errs = model.GetSyntaxDiagnostics(); Assert.Equal(0, errs.Count()); errs = model.GetDeclarationDiagnostics(); Assert.Equal(1, errs.Count()); errs = model.GetMethodBodyDiagnostics(); Assert.Equal(2, errs.Count()); } [Fact] public void PartialTypeDiagnostics_StaticConstructors() { var file1 = @" partial class C { static C() {} } "; var file2 = @" partial class C { static C() {} } "; var file3 = @" partial class C { static C() {} } "; var tree1 = Parse(file1); var tree2 = Parse(file2); var tree3 = Parse(file3); var comp = CreateCompilation(new[] { tree1, tree2, tree3 }); var model1 = comp.GetSemanticModel(tree1); var model2 = comp.GetSemanticModel(tree2); var model3 = comp.GetSemanticModel(tree3); model1.GetDeclarationDiagnostics().Verify(); model2.GetDeclarationDiagnostics().Verify( // (4,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 12)); model3.GetDeclarationDiagnostics().Verify( // (4,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 12)); Assert.Equal(3, comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").StaticConstructors.Length); } [Fact] public void PartialTypeDiagnostics_Constructors() { var file1 = @" partial class C { C() {} } "; var file2 = @" partial class C { C() {} } "; var file3 = @" partial class C { C() {} } "; var tree1 = Parse(file1); var tree2 = Parse(file2); var tree3 = Parse(file3); var comp = CreateCompilation(new[] { tree1, tree2, tree3 }); var model1 = comp.GetSemanticModel(tree1); var model2 = comp.GetSemanticModel(tree2); var model3 = comp.GetSemanticModel(tree3); model1.GetDeclarationDiagnostics().Verify(); model2.GetDeclarationDiagnostics().Verify( // (4,5): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 5)); model3.GetDeclarationDiagnostics().Verify( // (4,5): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 5)); Assert.Equal(3, comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Length); } [WorkItem(1076661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1076661")] [Fact] public void Bug1076661() { const string source = @" using X = System.Collections.Generic.List<dynamic>; class Test { void Goo(ref X. x) { } }"; var comp = CreateCompilation(source); var diag = comp.GetDiagnostics(); } [Fact] public void QueryClauseInBadStatement_Catch() { var source = @"using System; class C { static void F(object[] c) { catch (Exception) when (from o in c where true) { } } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tokens = tree.GetCompilationUnitRoot().DescendantTokens(); var expr = tokens.Single(t => t.Kind() == SyntaxKind.TrueKeyword).Parent; Assert.Null(model.GetSymbolInfo(expr).Symbol); Assert.Equal(SpecialType.System_Boolean, model.GetTypeInfo(expr).Type.SpecialType); } [Fact] public void GetSpecialType_ThrowsOnLessThanZero() { var source = "class C1 { }"; var comp = CreateCompilation(source); var specialType = (SpecialType)(-1); var exceptionThrown = false; try { comp.GetSpecialType(specialType); } catch (ArgumentOutOfRangeException e) { exceptionThrown = true; Assert.StartsWith(expectedStartString: $"Unexpected SpecialType: '{(int)specialType}'.", actualString: e.Message); } Assert.True(exceptionThrown, $"{nameof(comp.GetSpecialType)} did not throw when it should have."); } [Fact] public void GetSpecialType_ThrowsOnGreaterThanCount() { var source = "class C1 { }"; var comp = CreateCompilation(source); var specialType = SpecialType.Count + 1; var exceptionThrown = false; try { comp.GetSpecialType(specialType); } catch (ArgumentOutOfRangeException e) { exceptionThrown = true; Assert.StartsWith(expectedStartString: $"Unexpected SpecialType: '{(int)specialType}'.", actualString: e.Message); } Assert.True(exceptionThrown, $"{nameof(comp.GetSpecialType)} did not throw when it should have."); } [Fact] [WorkItem(34984, "https://github.com/dotnet/roslyn/issues/34984")] public void ConversionIsExplicit_UnsetConversionKind() { var source = @"class C1 { } class C2 { public void M() { var c = new C1(); foreach (string item in c.Items) { } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var foreachSyntaxNode = root.DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var foreachSymbolInfo = model.GetForEachStatementInfo(foreachSyntaxNode); Assert.Equal(Conversion.UnsetConversion, foreachSymbolInfo.CurrentConversion); Assert.True(foreachSymbolInfo.CurrentConversion.Exists); Assert.False(foreachSymbolInfo.CurrentConversion.IsImplicit); } [Fact, WorkItem(29933, "https://github.com/dotnet/roslyn/issues/29933")] public void SpeculativelyBindBaseInXmlDoc() { var text = @" class C { /// <summary> </summary> static void M() { } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf(">", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression("base"); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.NotReferencable, info.CandidateReason); } [Fact] [WorkItem(42840, "https://github.com/dotnet/roslyn/issues/42840")] public void DuplicateTypeArgument() { var source = @"class A<T> { } class B<T, U, U> where T : A<U> where U : class { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,15): error CS0692: Duplicate type parameter 'U' // class B<T, U, U> Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "U").WithArguments("U").WithLocation(4, 15), // (5,17): error CS0229: Ambiguity between 'U' and 'U' // where T : A<U> Diagnostic(ErrorCode.ERR_AmbigMember, "U").WithArguments("U", "U").WithLocation(5, 17)); comp = CreateCompilation(source); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var typeParameters = tree.GetRoot().DescendantNodes().OfType<TypeParameterSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(typeParameters[typeParameters.Length - 1]); Assert.False(symbol.IsReferenceType); symbol = model.GetDeclaredSymbol(typeParameters[typeParameters.Length - 2]); Assert.True(symbol.IsReferenceType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class GetSemanticInfoTests : SemanticModelTestBase { [WorkItem(544320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544320")] [Fact] public void TestBug12592() { var text = @" class B { public B(int x = 42) {} } class D : B { public D(int y) : base(/*<bind>*/x/*</bind>*/: y) { } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal(SymbolKind.Parameter, sym.Symbol.Kind); Assert.Equal("x", sym.Symbol.Name); } [WorkItem(541948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541948")] [Fact] public void DelegateArgumentType() { var text = @"using System; delegate void MyEvent(); class Test { event MyEvent Clicked; void Handler() { } public void Run() { Test t = new Test(); t.Clicked += new MyEvent(/*<bind>*/Handler/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal(SymbolKind.Method, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); } [WorkItem(541949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541949")] [Fact] public void LambdaWithParenthesis_BindOutsideOfParenthesis() { var text = @"using System; public class Test { delegate int D(); static void Main(int xx) { // int x = (xx); D d = /*<bind>*/( delegate() { return 0; } )/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.NotNull(sym.Symbol); Assert.Equal(SymbolKind.Method, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.AnonymousFunction, conv.Kind); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); Assert.Equal("Test.D", info.ConvertedType.ToTestDisplayString()); } [WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")] [WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")] [Fact] public void LambdaWithParenthesis_BindInsideOfParenthesis() { var text = @"using System; public class Test { delegate int D(); static void Main(int xx) { // int x = (xx); D d = (/*<bind>*/ delegate() { return 0; }/*</bind>*/) ; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.NotNull(sym.Symbol); Assert.Equal(SymbolKind.Method, sym.Symbol.Kind); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.AnonymousFunction, conv.Kind); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); Assert.Equal("Test.D", info.ConvertedType.ToTestDisplayString()); } [Fact, WorkItem(528656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528656")] public void SemanticInfoForInvalidExpression() { var text = @" public class A { static void Main() { Console.WriteLine(/*<bind>*/ delegate * delegate /*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Null(sym.Symbol); } [WorkItem(541973, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541973")] [Fact] public void LambdaAsAttributeArgumentErr() { var text = @"using System; delegate void D(); class MyAttr: Attribute { public MyAttr(D d) { } } [MyAttr((D)/*<bind>*/delegate { }/*</bind>*/)] // CS0182 public class A { } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetTypeInfo(expr); Assert.Null(info.Type); Assert.NotNull(info.ConvertedType); } [Fact] public void ClassifyConversionImplicit() { var text = @"using System; enum E { One, Two, Three } public class Test { static byte[] ary; static int Main() { // Identity ary = new byte[3]; // ImplicitConstant ary[0] = 0x0F; // ImplicitNumeric ushort ret = ary[0]; // ImplicitReference Test obj = null; // Identity obj = new Test(); // ImplicitNumeric obj.M(ary[0]); // boxing object box = -1; // ImplicitEnumeration E e = 0; // Identity E e2 = E.Two; // bind 'Two' return (int)ret; } void M(ulong p) { } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[1] as TypeDeclarationSyntax; Assert.Equal(3, testClass.Members.Count); var mainMethod = testClass.Members[1] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(10, mainStats.Count); // ary = new byte[3]; var v1 = (mainStats[0] as ExpressionStatementSyntax).Expression; Assert.Equal(SyntaxKind.SimpleAssignmentExpression, v1.Kind()); ConversionTestHelper(model, (v1 as AssignmentExpressionSyntax).Right, ConversionKind.Identity, ConversionKind.Identity); // ary[0] = 0x0F; var v2 = (mainStats[1] as ExpressionStatementSyntax).Expression; ConversionTestHelper(model, (v2 as AssignmentExpressionSyntax).Right, ConversionKind.ImplicitConstant, ConversionKind.ExplicitNumeric); // ushort ret = ary[0]; var v3 = (mainStats[2] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v3[0].Initializer.Value, ConversionKind.ImplicitNumeric, ConversionKind.ImplicitNumeric); // object obj01 = null; var v4 = (mainStats[3] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v4[0].Initializer.Value, ConversionKind.ImplicitReference, ConversionKind.NoConversion); // obj.M(ary[0]); var v6 = (mainStats[5] as ExpressionStatementSyntax).Expression; Assert.Equal(SyntaxKind.InvocationExpression, v6.Kind()); var v61 = (v6 as InvocationExpressionSyntax).ArgumentList.Arguments; ConversionTestHelper(model, v61[0].Expression, ConversionKind.ImplicitNumeric, ConversionKind.ImplicitNumeric); // object box = -1; var v7 = (mainStats[6] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v7[0].Initializer.Value, ConversionKind.Boxing, ConversionKind.Boxing); // E e = 0; var v8 = (mainStats[7] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v8[0].Initializer.Value, ConversionKind.ImplicitEnumeration, ConversionKind.ExplicitEnumeration); // E e2 = E.Two; var v9 = (mainStats[8] as LocalDeclarationStatementSyntax).Declaration.Variables; var v9val = (MemberAccessExpressionSyntax)(v9[0].Initializer.Value); var v9right = v9val.Name; ConversionTestHelper(model, v9right, ConversionKind.Identity, ConversionKind.Identity); } private void TestClassifyConversionBuiltInNumeric(string from, string to, ConversionKind ck) { const string template = @" class C {{ static void Goo({1} v) {{ }} static void Main() {{ {0} v = default({0}); Goo({2}v); }} }} "; var isExplicitConversion = ck == ConversionKind.ExplicitNumeric; var source = string.Format(template, from, to, isExplicitConversion ? "(" + to + ")" : ""); var tree = Parse(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); var c = (TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]; var main = (MethodDeclarationSyntax)c.Members[1]; var call = (InvocationExpressionSyntax)((ExpressionStatementSyntax)main.Body.Statements[1]).Expression; var arg = call.ArgumentList.Arguments[0].Expression; if (isExplicitConversion) { ConversionTestHelper(model, ((CastExpressionSyntax)arg).Expression, model.GetTypeInfo(arg).ConvertedType, ck); } else { ConversionTestHelper(model, arg, ck, ck); } } [Fact] public void ClassifyConversionBuiltInNumeric() { const ConversionKind ID = ConversionKind.Identity; const ConversionKind IN = ConversionKind.ImplicitNumeric; const ConversionKind XN = ConversionKind.ExplicitNumeric; var types = new[] { "sbyte", "byte", "short", "ushort", "int", "uint", "long", "ulong", "char", "float", "double", "decimal" }; var conversions = new ConversionKind[,] { // to sb b s us i ui l ul c f d m // from /* sb */ { ID, XN, IN, XN, IN, XN, IN, XN, XN, IN, IN, IN }, /* b */ { XN, ID, IN, IN, IN, IN, IN, IN, XN, IN, IN, IN }, /* s */ { XN, XN, ID, XN, IN, XN, IN, XN, XN, IN, IN, IN }, /* us */ { XN, XN, XN, ID, IN, IN, IN, IN, XN, IN, IN, IN }, /* i */ { XN, XN, XN, XN, ID, XN, IN, XN, XN, IN, IN, IN }, /* ui */ { XN, XN, XN, XN, XN, ID, IN, IN, XN, IN, IN, IN }, /* l */ { XN, XN, XN, XN, XN, XN, ID, XN, XN, IN, IN, IN }, /* ul */ { XN, XN, XN, XN, XN, XN, XN, ID, XN, IN, IN, IN }, /* c */ { XN, XN, XN, IN, IN, IN, IN, IN, ID, IN, IN, IN }, /* f */ { XN, XN, XN, XN, XN, XN, XN, XN, XN, ID, IN, XN }, /* d */ { XN, XN, XN, XN, XN, XN, XN, XN, XN, XN, ID, XN }, /* m */ { XN, XN, XN, XN, XN, XN, XN, XN, XN, XN, XN, ID } }; for (var from = 0; from < types.Length; from++) { for (var to = 0; to < types.Length; to++) { TestClassifyConversionBuiltInNumeric(types[from], types[to], conversions[from, to]); } } } [WorkItem(527486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527486")] [Fact] public void ClassifyConversionExplicit() { var text = @"using System; public class Test { object obj01; public void Testing(int x, Test obj02) { uint y = 5678; // Cast y = (uint) x; // Boxing obj01 = x; // Cast x = (int)obj01; // NoConversion obj02 = (Test)obj01; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; Assert.Equal(2, testClass.Members.Count); var mainMethod = testClass.Members[1] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(5, mainStats.Count); // y = (uint) x; var v1 = ((mainStats[1] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, (v1 as CastExpressionSyntax).Expression, comp.GetSpecialType(SpecialType.System_UInt32), ConversionKind.ExplicitNumeric); // obj01 = x; var v2 = (mainStats[2] as ExpressionStatementSyntax).Expression; ConversionTestHelper(model, (v2 as AssignmentExpressionSyntax).Right, comp.GetSpecialType(SpecialType.System_Object), ConversionKind.Boxing); // x = (int)obj01; var v3 = ((mainStats[3] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, (v3 as CastExpressionSyntax).Expression, comp.GetSpecialType(SpecialType.System_Int32), ConversionKind.Unboxing); // obj02 = (Test)obj01; var tsym = comp.SourceModule.GlobalNamespace.GetTypeMembers("Test").FirstOrDefault(); var v4 = ((mainStats[4] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, (v4 as CastExpressionSyntax).Expression, tsym, ConversionKind.ExplicitReference); } [Fact] public void DiagnosticsInStages() { var text = @" public class Test { object obj01; public void Testing(int x, Test obj02) { // ExplicitReference -> CS0266 obj02 = obj01; } binding error; parse err } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var errs = model.GetDiagnostics(); Assert.Equal(4, errs.Count()); errs = model.GetSyntaxDiagnostics(); Assert.Equal(1, errs.Count()); errs = model.GetDeclarationDiagnostics(); Assert.Equal(2, errs.Count()); errs = model.GetMethodBodyDiagnostics(); Assert.Equal(1, errs.Count()); } [Fact] public void DiagnosticsFilteredWithPragmas() { var text = @" public class Test { #pragma warning disable 1633 #pragma xyzzy whatever #pragma warning restore 1633 } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var errs = model.GetDiagnostics(); Assert.Equal(0, errs.Count()); errs = model.GetSyntaxDiagnostics(); Assert.Equal(0, errs.Count()); } [Fact] public void ClassifyConversionExplicitNeg() { var text = @" public class Test { object obj01; public void Testing(int x, Test obj02) { uint y = 5678; // ExplicitNumeric - CS0266 y = x; // Boxing obj01 = x; // unboxing - CS0266 x = obj01; // ExplicitReference -> CS0266 obj02 = obj01; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; Assert.Equal(2, testClass.Members.Count); var mainMethod = testClass.Members[1] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(5, mainStats.Count); // y = x; var v1 = ((mainStats[1] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, v1, ConversionKind.ExplicitNumeric, ConversionKind.ExplicitNumeric); // x = obj01; var v2 = ((mainStats[3] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, v2, ConversionKind.Unboxing, ConversionKind.Unboxing); // obj02 = obj01; var v3 = ((mainStats[4] as ExpressionStatementSyntax).Expression as AssignmentExpressionSyntax).Right; ConversionTestHelper(model, v3, ConversionKind.ExplicitReference, ConversionKind.ExplicitReference); // CC var errs = model.GetDiagnostics(); Assert.Equal(3, errs.Count()); errs = model.GetDeclarationDiagnostics(); Assert.Equal(0, errs.Count()); } [WorkItem(527767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527767")] [Fact] public void ClassifyConversionNullable() { var text = @"using System; public class Test { static void Main() { // NullLiteral sbyte? nullable = null; // ImplicitNullable uint? nullable01 = 100; ushort localVal = 123; // ImplicitNullable nullable01 = localVal; E e = 0; E? en = 0; // Oddly enough, C# classifies this as an implicit enumeration conversion. } } enum E { zero, one } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var testClass = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; Assert.Equal(1, testClass.Members.Count); var mainMethod = testClass.Members[0] as MethodDeclarationSyntax; var mainStats = mainMethod.Body.Statements; Assert.Equal(6, mainStats.Count); // sbyte? nullable = null; var v1 = (mainStats[0] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v1[0].Initializer.Value, ConversionKind.NullLiteral, ConversionKind.NoConversion); // uint? nullable01 = 100; var v2 = (mainStats[1] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v2[0].Initializer.Value, ConversionKind.ImplicitNullable, ConversionKind.ExplicitNullable); // nullable01 = localVal; var v3 = (mainStats[3] as ExpressionStatementSyntax).Expression; Assert.Equal(SyntaxKind.SimpleAssignmentExpression, v3.Kind()); ConversionTestHelper(model, (v3 as AssignmentExpressionSyntax).Right, ConversionKind.ImplicitNullable, ConversionKind.ImplicitNullable); // E e = 0; var v4 = (mainStats[4] as LocalDeclarationStatementSyntax).Declaration.Variables; ConversionTestHelper(model, v4[0].Initializer.Value, ConversionKind.ImplicitEnumeration, ConversionKind.ExplicitEnumeration); // E? en = 0; var v5 = (mainStats[5] as LocalDeclarationStatementSyntax).Declaration.Variables; // Bug#5035 (ByDesign): Conversion from literal 0 to nullable enum is Implicit Enumeration (not ImplicitNullable). Conversion from int to nullable enum is Explicit Nullable. ConversionTestHelper(model, v5[0].Initializer.Value, ConversionKind.ImplicitEnumeration, ConversionKind.ExplicitNullable); } [Fact, WorkItem(543994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543994")] public void ClassifyConversionImplicitUserDef() { var text = @"using System; class MyClass { public static bool operator true(MyClass p) { return true; } public static bool operator false(MyClass p) { return false; } public static MyClass operator &(MyClass mc1, MyClass mc2) { return new MyClass(); } public static int Main() { var cls1 = new MyClass(); var cls2 = new MyClass(); if (/*<bind0>*/cls1/*</bind0>*/) return 0; if (/*<bind1>*/cls1 && cls2/*</bind1>*/) return 1; return 2; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); var expr2 = exprs.Last(); var info = model.GetTypeInfo(expr1); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); // It was ImplicitUserDef -> Design Meeting resolution: not expose op_True|False as conversion through API var impconv = model.GetConversion(expr1); Assert.Equal(Conversion.Identity, impconv); Conversion conv = model.ClassifyConversion(expr1, info.ConvertedType); CheckIsAssignableTo(model, expr1); Assert.Equal(impconv, conv); Assert.Equal("Identity", conv.ToString()); conv = model.ClassifyConversion(expr2, info.ConvertedType); CheckIsAssignableTo(model, expr2); Assert.Equal(impconv, conv); } [Fact, WorkItem(1019372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019372")] public void ClassifyConversionImplicitUserDef02() { var text = @" class C { public static implicit operator int(C c) { return 0; } public C() { int? i = /*<bind0>*/this/*</bind0>*/; } }"; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); var expr1 = exprs.First(); var info = model.GetTypeInfo(expr1); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); var impconv = model.GetConversion(expr1); Assert.True(impconv.IsImplicit); Assert.True(impconv.IsUserDefined); Conversion conv = model.ClassifyConversion(expr1, info.ConvertedType); CheckIsAssignableTo(model, expr1); Assert.Equal(impconv, conv); Assert.True(conv.IsImplicit); Assert.True(conv.IsUserDefined); } private void CheckIsAssignableTo(SemanticModel model, ExpressionSyntax syntax) { var info = model.GetTypeInfo(syntax); var conversion = info.Type != null && info.ConvertedType != null ? model.Compilation.ClassifyConversion(info.Type, info.ConvertedType) : Conversion.NoConversion; Assert.Equal(conversion.IsImplicit, model.Compilation.HasImplicitConversion(info.Type, info.ConvertedType)); } [Fact, WorkItem(544151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544151")] public void PublicViewOfPointerConversions() { ValidateConversion(Conversion.PointerToVoid, ConversionKind.ImplicitPointerToVoid); ValidateConversion(Conversion.NullToPointer, ConversionKind.ImplicitNullToPointer); ValidateConversion(Conversion.PointerToPointer, ConversionKind.ExplicitPointerToPointer); ValidateConversion(Conversion.IntegerToPointer, ConversionKind.ExplicitIntegerToPointer); ValidateConversion(Conversion.PointerToInteger, ConversionKind.ExplicitPointerToInteger); ValidateConversion(Conversion.IntPtr, ConversionKind.IntPtr); } #region "Conversion helper" private void ValidateConversion(Conversion conv, ConversionKind kind) { Assert.Equal(conv.Kind, kind); switch (kind) { case ConversionKind.NoConversion: Assert.False(conv.Exists); Assert.False(conv.IsImplicit); Assert.False(conv.IsExplicit); break; case ConversionKind.Identity: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsIdentity); break; case ConversionKind.ImplicitNumeric: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsNumeric); break; case ConversionKind.ImplicitEnumeration: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsEnumeration); break; case ConversionKind.ImplicitNullable: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsNullable); break; case ConversionKind.NullLiteral: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsNullLiteral); break; case ConversionKind.ImplicitReference: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsReference); break; case ConversionKind.Boxing: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsBoxing); break; case ConversionKind.ImplicitDynamic: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsDynamic); break; case ConversionKind.ExplicitDynamic: Assert.True(conv.Exists); Assert.True(conv.IsExplicit); Assert.False(conv.IsImplicit); Assert.True(conv.IsDynamic); break; case ConversionKind.ImplicitConstant: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsConstantExpression); break; case ConversionKind.ImplicitUserDefined: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsUserDefined); break; case ConversionKind.AnonymousFunction: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsAnonymousFunction); break; case ConversionKind.MethodGroup: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.True(conv.IsMethodGroup); break; case ConversionKind.ExplicitNumeric: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsNumeric); break; case ConversionKind.ExplicitEnumeration: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsEnumeration); break; case ConversionKind.ExplicitNullable: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsNullable); break; case ConversionKind.ExplicitReference: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsReference); break; case ConversionKind.Unboxing: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsUnboxing); break; case ConversionKind.ExplicitUserDefined: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.True(conv.IsUserDefined); break; case ConversionKind.ImplicitNullToPointer: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ImplicitPointerToVoid: Assert.True(conv.Exists); Assert.True(conv.IsImplicit); Assert.False(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ExplicitPointerToPointer: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ExplicitIntegerToPointer: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.ExplicitPointerToInteger: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.True(conv.IsPointer); break; case ConversionKind.IntPtr: Assert.True(conv.Exists); Assert.False(conv.IsImplicit); Assert.True(conv.IsExplicit); Assert.False(conv.IsUserDefined); Assert.False(conv.IsPointer); Assert.True(conv.IsIntPtr); break; } } /// <summary> /// /// </summary> /// <param name="semanticModel"></param> /// <param name="expr"></param> /// <param name="ept1">expr -> TypeInParent</param> /// <param name="ept2">Type(expr) -> TypeInParent</param> private void ConversionTestHelper(SemanticModel semanticModel, ExpressionSyntax expr, ConversionKind ept1, ConversionKind ept2) { var info = semanticModel.GetTypeInfo(expr); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); var conv = semanticModel.GetConversion(expr); // NOT expect NoConversion Conversion act1 = semanticModel.ClassifyConversion(expr, info.ConvertedType); CheckIsAssignableTo(semanticModel, expr); Assert.Equal(ept1, act1.Kind); ValidateConversion(act1, ept1); ValidateConversion(act1, conv.Kind); if (ept2 == ConversionKind.NoConversion) { Assert.Null(info.Type); } else { Assert.NotNull(info.Type); var act2 = semanticModel.Compilation.ClassifyConversion(info.Type, info.ConvertedType); Assert.Equal(ept2, act2.Kind); ValidateConversion(act2, ept2); } } private void ConversionTestHelper(SemanticModel semanticModel, ExpressionSyntax expr, ITypeSymbol expsym, ConversionKind expkind) { var info = semanticModel.GetTypeInfo(expr); Assert.NotEqual(default, info); Assert.NotNull(info.ConvertedType); // NOT expect NoConversion Conversion act1 = semanticModel.ClassifyConversion(expr, expsym); CheckIsAssignableTo(semanticModel, expr); Assert.Equal(expkind, act1.Kind); ValidateConversion(act1, expkind); } #endregion [Fact] public void EnumOffsets() { // sbyte EnumOffset(ConstantValue.Create((sbyte)sbyte.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(sbyte.MinValue + 1))); EnumOffset(ConstantValue.Create((sbyte)sbyte.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(sbyte.MinValue + 2))); EnumOffset(ConstantValue.Create((sbyte)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(-1))); EnumOffset(ConstantValue.Create((sbyte)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)(1))); EnumOffset(ConstantValue.Create((sbyte)(sbyte.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((sbyte)sbyte.MaxValue)); EnumOffset(ConstantValue.Create((sbyte)(sbyte.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((sbyte)(sbyte.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // byte EnumOffset(ConstantValue.Create((byte)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((byte)1)); EnumOffset(ConstantValue.Create((byte)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((byte)2)); EnumOffset(ConstantValue.Create((byte)(byte.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((byte)byte.MaxValue)); EnumOffset(ConstantValue.Create((byte)(byte.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((byte)(byte.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // short EnumOffset(ConstantValue.Create((short)short.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(short.MinValue + 1))); EnumOffset(ConstantValue.Create((short)short.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(short.MinValue + 2))); EnumOffset(ConstantValue.Create((short)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(-1))); EnumOffset(ConstantValue.Create((short)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)(1))); EnumOffset(ConstantValue.Create((short)(short.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((short)short.MaxValue)); EnumOffset(ConstantValue.Create((short)(short.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((short)(short.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // ushort EnumOffset(ConstantValue.Create((ushort)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((ushort)1)); EnumOffset(ConstantValue.Create((ushort)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((ushort)2)); EnumOffset(ConstantValue.Create((ushort)(ushort.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((ushort)ushort.MaxValue)); EnumOffset(ConstantValue.Create((ushort)(ushort.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((ushort)(ushort.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // int EnumOffset(ConstantValue.Create((int)int.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(int.MinValue + 1))); EnumOffset(ConstantValue.Create((int)int.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(int.MinValue + 2))); EnumOffset(ConstantValue.Create((int)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(-1))); EnumOffset(ConstantValue.Create((int)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)(1))); EnumOffset(ConstantValue.Create((int)(int.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((int)int.MaxValue)); EnumOffset(ConstantValue.Create((int)(int.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((int)(int.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // uint EnumOffset(ConstantValue.Create((uint)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((uint)1)); EnumOffset(ConstantValue.Create((uint)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((uint)2)); EnumOffset(ConstantValue.Create((uint)(uint.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((uint)uint.MaxValue)); EnumOffset(ConstantValue.Create((uint)(uint.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((uint)(uint.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // long EnumOffset(ConstantValue.Create((long)long.MinValue), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(long.MinValue + 1))); EnumOffset(ConstantValue.Create((long)long.MinValue), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(long.MinValue + 2))); EnumOffset(ConstantValue.Create((long)-2), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(-1))); EnumOffset(ConstantValue.Create((long)-2), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)(1))); EnumOffset(ConstantValue.Create((long)(long.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((long)long.MaxValue)); EnumOffset(ConstantValue.Create((long)(long.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((long)(long.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); // ulong EnumOffset(ConstantValue.Create((ulong)0), 1, EnumOverflowKind.NoOverflow, ConstantValue.Create((ulong)1)); EnumOffset(ConstantValue.Create((ulong)0), 2, EnumOverflowKind.NoOverflow, ConstantValue.Create((ulong)2)); EnumOffset(ConstantValue.Create((ulong)(ulong.MaxValue - 3)), 3, EnumOverflowKind.NoOverflow, ConstantValue.Create((ulong)ulong.MaxValue)); EnumOffset(ConstantValue.Create((ulong)(ulong.MaxValue - 3)), 4, EnumOverflowKind.OverflowReport, ConstantValue.Bad); EnumOffset(ConstantValue.Create((ulong)(ulong.MaxValue - 3)), 5, EnumOverflowKind.OverflowIgnore, ConstantValue.Bad); } private void EnumOffset(ConstantValue constantValue, uint offset, EnumOverflowKind expectedOverflowKind, ConstantValue expectedValue) { ConstantValue actualValue; var actualOverflowKind = EnumConstantHelper.OffsetValue(constantValue, offset, out actualValue); Assert.Equal(expectedOverflowKind, actualOverflowKind); Assert.Equal(expectedValue, actualValue); } [Fact] public void TestGetSemanticInfoInParentInIf() { var compilation = CreateCompilation(@" class C { void M(int x) { if (x == 10) {} } } "); var tree = compilation.SyntaxTrees[0]; var methodDecl = (MethodDeclarationSyntax)((TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]).Members[0]; var ifStatement = (IfStatementSyntax)methodDecl.Body.Statements[0]; var condition = ifStatement.Condition; var model = compilation.GetSemanticModel(tree); var info = model.GetSemanticInfoSummary(condition); Assert.NotNull(info.ConvertedType); Assert.Equal("Boolean", info.Type.Name); Assert.Equal("System.Boolean System.Int32.op_Equality(System.Int32 left, System.Int32 right)", info.Symbol.ToTestDisplayString()); Assert.Equal(0, info.CandidateSymbols.Length); } [Fact] public void TestGetSemanticInfoInParentInFor() { var compilation = CreateCompilation(@" class C { void M(int x) { for (int i = 0; i < 10; i = i + 1) { } } } "); var tree = compilation.SyntaxTrees[0]; var methodDecl = (MethodDeclarationSyntax)((TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0]).Members[0]; var forStatement = (ForStatementSyntax)methodDecl.Body.Statements[0]; var condition = forStatement.Condition; var model = compilation.GetSemanticModel(tree); var info = model.GetSemanticInfoSummary(condition); Assert.NotNull(info.ConvertedType); Assert.Equal("Boolean", info.ConvertedType.Name); Assert.Equal("System.Boolean System.Int32.op_LessThan(System.Int32 left, System.Int32 right)", info.Symbol.ToTestDisplayString()); Assert.Equal(0, info.CandidateSymbols.Length); } [WorkItem(540279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540279")] [Fact] public void NoMembersForVoidReturnType() { var text = @" class C { void M() { /*<bind>*/System.Console.WriteLine()/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); IMethodSymbol methodSymbol = (IMethodSymbol)bindInfo.Symbol; ITypeSymbol returnType = methodSymbol.ReturnType; var symbols = model.LookupSymbols(0, returnType); Assert.Equal(0, symbols.Length); } [WorkItem(540767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540767")] [Fact] public void BindIncompleteVarDeclWithDoKeyword() { var code = @" class Test { static int Main(string[] args) { do"; var compilation = CreateCompilation(code); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var exprSyntaxList = GetExprSyntaxList(tree); Assert.Equal(6, exprSyntaxList.Count); // Note the omitted array size expression in "string[]" Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxList[4].Kind()); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxList[5].Kind()); Assert.Equal("", exprSyntaxList[4].ToFullString()); Assert.Equal("", exprSyntaxList[5].ToFullString()); var exprSyntaxToBind = exprSyntaxList[exprSyntaxList.Count - 2]; model.GetSemanticInfoSummary(exprSyntaxToBind); } [Fact] public void TestBindBaseConstructorInitializer() { var text = @" class C { C() : base() { } } "; var bindInfo = BindFirstConstructorInitializer(text); Assert.NotEqual(default, bindInfo); var baseConstructor = bindInfo.Symbol; Assert.Equal(SymbolKind.Method, baseConstructor.Kind); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)baseConstructor).MethodKind); Assert.Equal("System.Object..ctor()", baseConstructor.ToTestDisplayString()); } [Fact] public void TestBindThisConstructorInitializer() { var text = @" class C { C() : this(1) { } C(int x) { } } "; var bindInfo = BindFirstConstructorInitializer(text); Assert.NotEqual(default, bindInfo); var baseConstructor = bindInfo.Symbol; Assert.Equal(SymbolKind.Method, baseConstructor.Kind); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)baseConstructor).MethodKind); Assert.Equal("C..ctor(System.Int32 x)", baseConstructor.ToTestDisplayString()); } [WorkItem(540862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540862")] [Fact] public void BindThisStaticConstructorInitializer() { var text = @" class MyClass { static MyClass() : this() { intI = 2; } public MyClass() { } static int intI = 1; } "; var bindInfo = BindFirstConstructorInitializer(text); Assert.NotEqual(default, bindInfo); var invokedConstructor = (IMethodSymbol)bindInfo.Symbol; Assert.Equal(MethodKind.Constructor, invokedConstructor.MethodKind); Assert.Equal("MyClass..ctor()", invokedConstructor.ToTestDisplayString()); } [WorkItem(541053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541053")] [Fact] public void CheckAndAdjustPositionOutOfRange() { var text = @" using System; > 1 "; var tree = Parse(text, options: TestOptions.Script); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); Assert.NotEqual(0, root.SpanStart); var stmt = (GlobalStatementSyntax)root.Members.Single(); var expr = ((ExpressionStatementSyntax)stmt.Statement).Expression; Assert.Equal(SyntaxKind.GreaterThanExpression, expr.Kind()); var info = model.GetSemanticInfoSummary(expr); Assert.Equal(SpecialType.System_Boolean, info.Type.SpecialType); } [Fact] public void AddAccessorValueParameter() { var text = @" class C { private System.Action e; event System.Action E { add { e += /*<bind>*/value/*</bind>*/; } remove { e -= value; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var parameterSymbol = (IParameterSymbol)bindInfo.Symbol; Assert.Equal(systemActionType, parameterSymbol.Type); Assert.Equal("value", parameterSymbol.Name); Assert.Equal(MethodKind.EventAdd, ((IMethodSymbol)parameterSymbol.ContainingSymbol).MethodKind); } [Fact] public void RemoveAccessorValueParameter() { var text = @" class C { private System.Action e; event System.Action E { add { e += value; } remove { e -= /*<bind>*/value/*</bind>*/; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var parameterSymbol = (IParameterSymbol)bindInfo.Symbol; Assert.Equal(systemActionType, parameterSymbol.Type); Assert.Equal("value", parameterSymbol.Name); Assert.Equal(MethodKind.EventRemove, ((IMethodSymbol)parameterSymbol.ContainingSymbol).MethodKind); } [Fact] public void FieldLikeEventInitializer() { var text = @" class C { event System.Action E = /*<bind>*/new System.Action(() => { })/*</bind>*/; } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); Assert.Null(bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); } [Fact] public void FieldLikeEventInitializer2() { var text = @" class C { event System.Action E = new /*<bind>*/System.Action/*</bind>*/(() => { }); } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Null(bindInfo.Type); Assert.Equal(systemActionType, bindInfo.Symbol); } [Fact] public void CustomEventAccess() { var text = @" class C { event System.Action E { add { } remove { } } void Method() { /*<bind>*/E/*</bind>*/ += null; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol, bindInfo.Symbol); } [Fact] public void FieldLikeEventAccess() { var text = @" class C { event System.Action E; void Method() { /*<bind>*/E/*</bind>*/ += null; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var systemActionType = GetSystemActionType(comp); Assert.Equal(systemActionType, bindInfo.Type); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol, bindInfo.Symbol); } [Fact] public void CustomEventAssignmentOperator() { var text = @" class C { event System.Action E { add { } remove { } } void Method() { /*<bind>*/E += null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Equal(SpecialType.System_Void, bindInfo.Type.SpecialType); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol.AddMethod, bindInfo.Symbol); } [Fact] public void FieldLikeEventAssignmentOperator() { var text = @" class C { event System.Action E; void Method() { /*<bind>*/E += null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Equal(SpecialType.System_Void, bindInfo.Type.SpecialType); var eventSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E"); Assert.Equal(eventSymbol.AddMethod, bindInfo.Symbol); } [Fact] public void CustomEventMissingAssignmentOperator() { var text = @" class C { event System.Action E { /*add { }*/ remove { } } //missing add void Method() { /*<bind>*/E += null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Null(bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(SpecialType.System_Void, bindInfo.Type.SpecialType); } private static INamedTypeSymbol GetSystemActionType(CSharpCompilation comp) { return GetSystemActionType((Compilation)comp); } private static INamedTypeSymbol GetSystemActionType(Compilation comp) { return (INamedTypeSymbol)comp.GlobalNamespace.GetMember<INamespaceSymbol>("System").GetMembers("Action").Where(s => !((INamedTypeSymbol)s).IsGenericType).Single(); } [Fact] public void IndexerAccess() { var text = @" class C { int this[int x] { get { return x; } } int this[int x, int y] { get { return x + y; } } void Method() { int x = /*<bind>*/this[1]/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ElementAccessExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var indexerSymbol = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Where(i => i.ParameterCount == 1).Single().GetPublicSymbol(); Assert.Equal(indexerSymbol, bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, bindInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, bindInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(0, bindInfo.MethodGroup.Length); Assert.False(bindInfo.IsCompileTimeConstant); Assert.Null(bindInfo.ConstantValue.Value); } [Fact] public void IndexerAccessOverloadResolutionFailure() { var text = @" class C { int this[int x] { get { return x; } } int this[int x, int y] { get { return x + y; } } void Method() { int x = /*<bind>*/this[1, 2, 3]/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ElementAccessExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var indexerSymbol1 = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Where(i => i.ParameterCount == 1).Single().GetPublicSymbol(); var indexerSymbol2 = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").Indexers.Where(i => i.ParameterCount == 2).Single().GetPublicSymbol(); var candidateIndexers = ImmutableArray.Create<ISymbol>(indexerSymbol1, indexerSymbol2); Assert.Null(bindInfo.Symbol); Assert.True(bindInfo.CandidateSymbols.SetEquals(candidateIndexers, EqualityComparer<ISymbol>.Default)); Assert.Equal(CandidateReason.OverloadResolutionFailure, bindInfo.CandidateReason); Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType); //still have the type since all candidates agree Assert.Equal(SpecialType.System_Int32, bindInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, bindInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.OverloadResolutionFailure, bindInfo.CandidateReason); Assert.Equal(0, bindInfo.MethodGroup.Length); Assert.False(bindInfo.IsCompileTimeConstant); Assert.Null(bindInfo.ConstantValue.Value); } [Fact] public void IndexerAccessNoIndexers() { var text = @" class C { void Method() { int x = /*<bind>*/this[1, 2, 3]/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ElementAccessExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Null(bindInfo.Symbol); Assert.Equal(0, bindInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(TypeKind.Error, bindInfo.Type.TypeKind); Assert.Equal(TypeKind.Struct, bindInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, bindInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.None, bindInfo.CandidateReason); Assert.Equal(0, bindInfo.MethodGroup.Length); Assert.False(bindInfo.IsCompileTimeConstant); Assert.Null(bindInfo.ConstantValue.Value); } [WorkItem(542296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542296")] [Fact] public void TypeArgumentsOnFieldAccess1() { var text = @" public class Test { public int Fld; public int Func() { return (int)(/*<bind>*/Fld<int>/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.GenericName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); Assert.Null(bindInfo.Symbol); Assert.Equal(CandidateReason.WrongArity, bindInfo.CandidateReason); Assert.Equal(1, bindInfo.CandidateSymbols.Length); var candidate = bindInfo.CandidateSymbols.Single(); Assert.Equal(SymbolKind.Field, candidate.Kind); Assert.Equal("Fld", candidate.Name); } [WorkItem(542296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542296")] [Fact] public void TypeArgumentsOnFieldAccess2() { var text = @" public class Test { public int Fld; public int Func() { return (int)(Fld</*<bind>*/Test/*</bind>*/>); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.NamedType, symbol.Kind); Assert.Equal("Test", symbol.Name); } [WorkItem(528785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528785")] [Fact] public void TopLevelIndexer() { var text = @" this[double E] { get { return /*<bind>*/E/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.Null(symbol); } [WorkItem(542360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542360")] [Fact] public void TypeAndMethodHaveSameTypeParameterName() { var text = @" interface I<T> { void Goo<T>(); } class A<T> : I<T> { void I</*<bind>*/T/*</bind>*/>.Goo<T>() { } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.TypeParameter, symbol.Kind); Assert.Equal("T", symbol.Name); Assert.Equal(comp.GlobalNamespace.GetMember<INamedTypeSymbol>("A"), symbol.ContainingSymbol); //from the type, not the method } [WorkItem(542436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542436")] [Fact] public void RecoveryFromBadNamespaceDeclaration() { var text = @"namespace alias:: using alias = /*<bind>*/N/*</bind>*/; namespace N { } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); } /// Test that binding a local declared with var binds the same way when localSymbol.Type is called before BindVariableDeclaration. /// Assert occurs if the two do not compute the same type. [Fact] [WorkItem(542634, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542634")] public void VarInitializedWithStaticType() { var text = @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static string xunit = " + "@" + @"..\..\Closed\Tools\xUnit\xunit.console.x86.exe" + @"; static string test = " + @"Roslyn.VisualStudio.Services.UnitTests.dll" + @"; static string commandLine = test" + @" /html log.html" + @"; static void Main(string[] args) { var options = CreateOptions(); /*<bind>*/Parallel/*</bind>*/.For(0, 100, RunTest, options); } private static Parallel CreateOptions() { var result = new ParallelOptions(); } private static void RunTest(int i) { } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); // Bind Parallel from line Parallel.For(0, 100, RunTest, options); // This will implicitly bind "var" to determine type of options. // This calls LocalSymbol.GetType var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var varIdentifier = (IdentifierNameSyntax)tree.GetCompilationUnitRoot().DescendantNodes().First(n => n.ToString() == "var"); // var from line var options = CreateOptions; // Explicitly bind "var". // This path calls BindvariableDeclaration. bindInfo = model.GetSemanticInfoSummary(varIdentifier); } [WorkItem(542186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542186")] [Fact] public void IndexerParameter() { var text = @" class C { int this[int x] { get { return /*<bind>*/x/*</bind>*/; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("x", symbol.Name); Assert.Equal(SymbolKind.Method, symbol.ContainingSymbol.Kind); var lookupSymbols = model.LookupSymbols(exprSyntaxToBind.SpanStart, name: "x"); Assert.Equal(symbol, lookupSymbols.Single()); } [WorkItem(542186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542186")] [Fact] public void IndexerValueParameter() { var text = @" class C { int this[int x] { set { x = /*<bind>*/value/*</bind>*/; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("value", symbol.Name); Assert.Equal(SymbolKind.Method, symbol.ContainingSymbol.Kind); var lookupSymbols = model.LookupSymbols(exprSyntaxToBind.SpanStart, name: "value"); Assert.Equal(symbol, lookupSymbols.Single()); } [WorkItem(542777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542777")] [Fact] public void IndexerThisParameter() { var text = @" class C { int this[int x] { set { System.Console.Write(/*<bind>*/this/*</bind>*/); } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ThisExpression, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal("this", symbol.Name); Assert.Equal(SymbolKind.Method, symbol.ContainingSymbol.Kind); } [WorkItem(542592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542592")] [Fact] public void TypeParameterParamsParameter() { var text = @" class Test<T> { public void Method(params T arr) { } } class Program { static void Main(string[] args) { new Test<int[]>()./*<bind>*/Method/*</bind>*/(new int[][] { }); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSemanticInfoSummary(exprSyntaxToBind); var symbol = bindInfo.Symbol; Assert.Null(symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, bindInfo.CandidateReason); var candidate = (IMethodSymbol)bindInfo.CandidateSymbols.Single(); Assert.Equal("void Test<System.Int32[]>.Method(params System.Int32[] arr)", candidate.ToTestDisplayString()); Assert.Equal(TypeKind.Array, candidate.Parameters.Last().Type.TypeKind); Assert.Equal(TypeKind.TypeParameter, ((IMethodSymbol)candidate.OriginalDefinition).Parameters.Last().Type.TypeKind); } [WorkItem(542458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542458")] [Fact] public void ParameterDefaultValues() { var text = @" struct S { void M( int i = 1, string str = ""hello"", object o = null, S s = default(S)) { /*<bind>*/M/*</bind>*/(); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); var method = (IMethodSymbol)bindInfo.Symbol; Assert.NotNull(method); var parameters = method.Parameters; Assert.Equal(4, parameters.Length); Assert.True(parameters[0].HasExplicitDefaultValue); Assert.Equal(1, parameters[0].ExplicitDefaultValue); Assert.True(parameters[1].HasExplicitDefaultValue); Assert.Equal("hello", parameters[1].ExplicitDefaultValue); Assert.True(parameters[2].HasExplicitDefaultValue); Assert.Null(parameters[2].ExplicitDefaultValue); Assert.True(parameters[3].HasExplicitDefaultValue); Assert.Null(parameters[3].ExplicitDefaultValue); } [WorkItem(542764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542764")] [Fact] public void UnboundGenericTypeArity() { var text = @" class C<T, U, V> { void M() { System.Console.Write(typeof(/*<bind>*/C<,,>/*</bind>*/)); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var nameSyntaxToBind = (SimpleNameSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.GenericName, nameSyntaxToBind.Kind()); Assert.Equal(3, nameSyntaxToBind.Arity); var bindInfo = model.GetSymbolInfo(nameSyntaxToBind); var type = (INamedTypeSymbol)bindInfo.Symbol; Assert.NotNull(type); Assert.True(type.IsUnboundGenericType); Assert.Equal(3, type.Arity); Assert.Equal("C<,,>", type.ToTestDisplayString()); } [Fact] public void GetType_VoidArray() { var text = @" class C { void M() { var x = typeof(/*<bind>*/System.Void[]/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.ArrayType, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); var arrayType = (IArrayTypeSymbol)bindInfo.Symbol; Assert.NotNull(arrayType); Assert.Equal("System.Void[]", arrayType.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance1() { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { } public class C<T> where T : IA, IB // can find IA.P in two different ways { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Object> System.Collections.Generic.IEnumerable<T>.Select<T, System.Object>(System.Func<T, System.Object> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance2() //add hiding member in derived interface { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { new int P { get; } } public class C<T> where T : IA, IB { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Int32> System.Collections.Generic.IEnumerable<T>.Select<T, System.Int32>(System.Func<T, System.Int32> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance3() //reverse order of interface list (shouldn't matter) { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { new int P { get; } } public class C<T> where T : IB, IA { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Int32> System.Collections.Generic.IEnumerable<T>.Select<T, System.Int32>(System.Func<T, System.Int32> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterDiamondInheritance4() //Two interfaces with a common base { var text = @" using System.Linq; public interface IA { object P { get; } } public interface IB : IA { } public interface IC : IA { } public class C<T> where T : IB, IC { void M() { new T[1]./*<bind>*/Select/*</bind>*/(i => i.P); } } "; var tree = Parse(text); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); var model = comp.GetSemanticModel(tree); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, exprSyntaxToBind.Kind()); var bindInfo = model.GetSymbolInfo(exprSyntaxToBind); Assert.Equal("System.Collections.Generic.IEnumerable<System.Object> System.Collections.Generic.IEnumerable<T>.Select<T, System.Object>(System.Func<T, System.Object> selector)", bindInfo.Symbol.ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup1() { var types = @" public interface IA { object P { get; } } "; var members = LookupTypeParameterMembers(types, "IA", "P", out _); Assert.Equal("System.Object IA.P { get; }", members.Single().ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup2() { var types = @" public interface IA { object P { get; } } public interface IB { object P { get; } } "; ITypeParameterSymbol typeParameter; var members = LookupTypeParameterMembers(types, "IA, IB", "P", out typeParameter); Assert.True(members.SetEquals(typeParameter.AllEffectiveInterfacesNoUseSiteDiagnostics().Select(i => i.GetMember<IPropertySymbol>("P")))); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup3() { var types = @" public interface IA { object P { get; } } public interface IB : IA { new object P { get; } } "; var members = LookupTypeParameterMembers(types, "IA, IB", "P", out _); Assert.Equal("System.Object IB.P { get; }", members.Single().ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup4() { var types = @" public interface IA { object P { get; } } public class D { public object P { get; set; } } "; var members = LookupTypeParameterMembers(types, "D, IA", "P", out _); Assert.Equal("System.Object D.P { get; set; }", members.Single().ToTestDisplayString()); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup5() { var types = @" public interface IA { void M(); } public class D { public void M() { } } "; var members = LookupTypeParameterMembers(types, "IA", "M", out _); Assert.Equal("void IA.M()", members.Single().ToTestDisplayString()); members = LookupTypeParameterMembers(types, "D, IA", "M", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "void IA.M()", "void D.M()" })); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup6() { var types = @" public interface IA { void M(); void M(int x); } public class D { public void M() { } } "; var members = LookupTypeParameterMembers(types, "IA", "M", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "void IA.M()", "void IA.M(System.Int32 x)" })); members = LookupTypeParameterMembers(types, "D, IA", "M", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "void D.M()", "void IA.M()", "void IA.M(System.Int32 x)" })); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void TypeParameterMemberLookup7() { var types = @" public interface IA { string ToString(); } public class D { public new string ToString() { return null; } } "; var members = LookupTypeParameterMembers(types, "IA", "ToString", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "System.String System.Object.ToString()", "System.String IA.ToString()" })); members = LookupTypeParameterMembers(types, "D, IA", "ToString", out _); Assert.True(members.Select(m => m.ToTestDisplayString()).SetEquals(new[] { "System.String System.Object.ToString()", "System.String D.ToString()", "System.String IA.ToString()" })); } private IEnumerable<ISymbol> LookupTypeParameterMembers(string types, string constraints, string memberName, out ITypeParameterSymbol typeParameter) { var template = @" {0} public class C<T> where T : {1} {{ void M() {{ System.Console.WriteLine(/*<bind>*/default(T)/*</bind>*/); }} }} "; var tree = Parse(string.Format(template, types, constraints)); var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); comp.VerifyDiagnostics(); var model = comp.GetSemanticModel(tree); var classC = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); typeParameter = classC.TypeParameters.Single(); var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.DefaultExpression, exprSyntaxToBind.Kind()); return model.LookupSymbols(exprSyntaxToBind.SpanStart, typeParameter, memberName); } [WorkItem(542966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542966")] [Fact] public async Task IndexerMemberRaceAsync() { var text = @" using System; interface IA { [System.Runtime.CompilerServices.IndexerName(""Goo"")] string this[int index] { get; } } class A : IA { public virtual string this[int index] { get { return """"; } } string IA.this[int index] { get { return """"; } } } class B : A, IA { public override string this[int index] { get { return """"; } } } class Program { public static void Main(string[] args) { IA x = new B(); Console.WriteLine(x[0]); } } "; TimeSpan timeout = TimeSpan.FromSeconds(2); for (int i = 0; i < 20; i++) { var comp = CreateCompilation(text); var task1 = new Task(() => comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMembers()); var task2 = new Task(() => comp.GlobalNamespace.GetMember<NamedTypeSymbol>("IA").GetMembers()); if (i % 2 == 0) { task1.Start(); task2.Start(); } else { task2.Start(); task1.Start(); } comp.VerifyDiagnostics(); await Task.WhenAll(task1, task2); } } [Fact] public void ImplicitDeclarationMultipleDeclarators() { var text = @" using System.IO; class C { static void Main() { /*<bind>*/var a = new StreamWriter(""""), b = new StreamReader("""")/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (8,19): error CS0819: Implicitly-typed variables cannot have multiple declarators // /*<bind>*/var a = new StreamWriter(""), b = new StreamReader("")/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, @"var a = new StreamWriter(""""), b = new StreamReader("""")").WithLocation(8, 19) ); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var typeInfo = model.GetSymbolInfo(expr); // the type info uses the type inferred for the first declared local Assert.Equal("System.IO.StreamWriter", typeInfo.Symbol.ToTestDisplayString()); } [WorkItem(543169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543169")] [Fact] public void ParameterOfLambdaPassedToOutParameter() { var text = @" using System.Linq; class D { static void Main(string[] args) { string[] str = new string[] { }; label1: var s = str.Where(out /*<bind>*/x/*</bind>*/ => { return x == ""1""; }); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(); var parameterSymbol = model.GetDeclaredSymbol(lambdaSyntax.Parameter); Assert.NotNull(parameterSymbol); Assert.Equal("x", parameterSymbol.Name); Assert.Equal(MethodKind.AnonymousFunction, ((IMethodSymbol)parameterSymbol.ContainingSymbol).MethodKind); } [WorkItem(529096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529096")] [Fact] public void MemberAccessExpressionResults() { var text = @" class C { public static int A; public static byte B() { return 3; } public static string D { get; set; } static void Main(string[] args) { /*<bind0>*/C.A/*</bind0>*/; /*<bind1>*/C.B/*</bind1>*/(); /*<bind2>*/C.D/*</bind2>*/; /*<bind3>*/C.B()/*</bind3>*/; int goo = /*<bind4>*/C.B()/*</bind4>*/; goo = /*<bind5>*/C.B/*</bind5>*/(); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var exprs = GetBindingNodes<ExpressionSyntax>(comp); for (int i = 0; i < exprs.Count; i++) { var expr = exprs[i]; var symbolInfo = model.GetSymbolInfo(expr); Assert.NotNull(symbolInfo.Symbol); var typeInfo = model.GetTypeInfo(expr); switch (i) { case 0: Assert.Equal("A", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); break; case 1: case 5: Assert.Equal("B", symbolInfo.Symbol.Name); Assert.Null(typeInfo.Type); break; case 2: Assert.Equal("D", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.String", typeInfo.ConvertedType.ToTestDisplayString()); break; case 3: Assert.Equal("B", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.Byte", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Byte", typeInfo.ConvertedType.ToTestDisplayString()); break; case 4: Assert.Equal("B", symbolInfo.Symbol.Name); Assert.NotNull(typeInfo.Type); Assert.Equal("System.Byte", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); break; } // switch } } [WorkItem(543554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543554")] [Fact] public void SemanticInfoForUncheckedExpression() { var text = @" public class A { static void Main() { Console.WriteLine(/*<bind>*/unchecked(42 + 42.1)/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal("System.Double System.Double.op_Addition(System.Double left, System.Double right)", sym.Symbol.ToTestDisplayString()); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.Identity, conv.Kind); Assert.Equal(SpecialType.System_Double, info.Type.SpecialType); Assert.Equal(SpecialType.System_Double, info.ConvertedType.SpecialType); } [WorkItem(543554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543554")] [Fact] public void SemanticInfoForCheckedExpression() { var text = @" class Program { public static int Add(int a, int b) { return /*<bind>*/checked(a+b)/*</bind>*/; } } "; var comp = CreateCompilation(text); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal("System.Int32 System.Int32.op_Addition(System.Int32 left, System.Int32 right)", sym.Symbol.ToTestDisplayString()); var info = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.Identity, conv.Kind); Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, info.ConvertedType.SpecialType); } [WorkItem(543554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543554")] [Fact] public void CheckedUncheckedExpression() { var text = @" class Test { public void F() { int y = /*<bind>*/(checked(unchecked((1))))/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetTypeInfo(expr); Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, info.ConvertedType.SpecialType); } [WorkItem(543543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543543")] [Fact] public void SymbolInfoForImplicitOperatorParameter() { var text = @" class Program { public Program(string s) { } public static implicit operator Program(string str) { return new Program(/*<bind>*/str/*</bind>*/); } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetSymbolInfo(expr); var symbol = info.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.Equal(MethodKind.Conversion, ((IMethodSymbol)symbol.ContainingSymbol).MethodKind); } [WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")] [WorkItem(543560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543560")] [Fact] public void BrokenPropertyDeclaration() { var source = @" using System; Class Program // this will get a Property declaration ... *sigh* { static void Main(string[] args) { Func<int, int> f = /*<bind0>*/x/*</bind0>*/ => x + 1; } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<ParameterSyntax>().First(); var declaredSymbol = model.GetDeclaredSymbol(expr); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedBinaryOperator() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } static void Main() { C c1 = new C(); C c2 = new C(); C c3 = /*<bind>*/c1 + c2/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.AdditionOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedLogicalOperator() { var text = @" class C { public static C operator &(C c1, C c2) { return c1 ?? c2; } public static bool operator true(C c) { return true; } public static bool operator false(C c) { return false; } static void Main() { C c1 = new C(); C c2 = new C(); C c3 = /*<bind>*/c1 && c2/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.BitwiseAndOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedUnaryOperator() { var text = @" class C { public static C operator+(C c1) { return c1; } static void Main() { C c1 = new C(); C c2 = /*<bind>*/+c1/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.UnaryPlusOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedExplicitConversion() { var text = @" class C { public static explicit operator C(int i) { return null; } static void Main() { C c1 = /*<bind>*/(C)1/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.ExplicitConversionName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedImplicitConversion() { var text = @" class C { public static implicit operator C(int i) { return null; } static void Main() { C c1 = /*<bind>*/(C)1/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.ImplicitConversionName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedTrueOperator() { var text = @" class C { public static bool operator true(C c) { return true; } public static bool operator false(C c) { return false; } static void Main() { C c = new C(); if (/*<bind>*/c/*</bind>*/) { } } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var type = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); var symbol = symbolInfo.Symbol; Assert.Equal(SymbolKind.Local, symbol.Kind); Assert.Equal("c", symbol.Name); Assert.Equal(type, ((ILocalSymbol)symbol).Type); var typeInfo = model.GetTypeInfo(expr); Assert.Equal(type, typeInfo.Type); Assert.Equal(type, typeInfo.ConvertedType); var conv = model.GetConversion(expr); Assert.Equal(Conversion.Identity, conv); Assert.False(model.GetConstantValue(expr).HasValue); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedIncrement() { var text = @" class C { public static C operator ++(C c) { return c; } static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1++/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.IncrementOperatorName); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SemanticInfoForUserDefinedCompoundAssignment() { var text = @" class C { public static C operator +(C c1, C c2) { return c1 ?? c2; } static void Main() { C c1 = new C(); C c2 = new C(); /*<bind>*/c1 += c2/*</bind>*/; } } "; CheckOperatorSemanticInfo(text, WellKnownMemberNames.AdditionOperatorName); } private void CheckOperatorSemanticInfo(string text, string operatorName) { var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operatorSymbol = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>(operatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal(operatorSymbol, symbolInfo.Symbol); var method = (IMethodSymbol)symbolInfo.Symbol; var returnType = method.ReturnType; var typeInfo = model.GetTypeInfo(expr); Assert.Equal(returnType, typeInfo.Type); Assert.Equal(returnType, typeInfo.ConvertedType); var conv = model.GetConversion(expr); Assert.Equal(ConversionKind.Identity, conv.Kind); Assert.False(model.GetConstantValue(expr).HasValue); } [Fact, WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550"), WorkItem(543439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543439")] public void SymbolInfoForUserDefinedConversionOverloadResolutionFailure() { var text = @" struct S { public static explicit operator S(string s) { return default(S); } public static explicit operator S(System.Text.StringBuilder s) { return default(S); } static void Main() { S s = /*<bind>*/(S)null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var conversions = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("S").GetMembers(WellKnownMemberNames.ExplicitConversionName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(conversions, EqualityComparer<ISymbol>.Default)); } [Fact, WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550"), WorkItem(543439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543439")] public void SymbolInfoForUserDefinedConversionOverloadResolutionFailureEmpty() { var text = @" struct S { static void Main() { S s = /*<bind>*/(S)null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var conversions = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("S").GetMembers(WellKnownMemberNames.ExplicitConversionName); Assert.Equal(0, conversions.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedUnaryOperatorOverloadResolutionFailure() { var il = @" .class public auto ansi beforefieldinit UnaryOperator extends [mscorlib]System.Object { .method public hidebysig specialname static class UnaryOperator op_UnaryPlus(class UnaryOperator unaryOperator) cil managed { ldnull throw } // Differs only by return type .method public hidebysig specialname static string op_UnaryPlus(class UnaryOperator unaryOperator) cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var text = @" class Program { static void Main() { UnaryOperator u1 = new UnaryOperator(); UnaryOperator u2 = /*<bind>*/+u1/*</bind>*/; } } "; var comp = (Compilation)CreateCompilationWithILAndMscorlib40(text, il); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("UnaryOperator").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedUnaryOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c1 = new C(); C c2 = /*<bind>*/+c1/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.UnaryPlusOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedIncrementOperatorOverloadResolutionFailure() { var il = @" .class public auto ansi beforefieldinit IncrementOperator extends [mscorlib]System.Object { .method public hidebysig specialname static class IncrementOperator op_Increment(class IncrementOperator incrementOperator) cil managed { ldnull throw } .method public hidebysig specialname static string op_Increment(class IncrementOperator incrementOperator) cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var text = @" class Program { static void Main() { IncrementOperator i1 = new IncrementOperator(); IncrementOperator i2 = /*<bind>*/i1++/*</bind>*/; } } "; var comp = (Compilation)CreateCompilationWithILAndMscorlib40(text, il); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("IncrementOperator").GetMembers(WellKnownMemberNames.IncrementOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedIncrementOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1++/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.IncrementOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedBinaryOperatorOverloadResolutionFailure() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } public static C operator+(C c1, string s) { return c1; } static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1 + null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedBinaryOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c1 = new C(); C c2 = /*<bind>*/c1 + null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("System.String System.String.op_Addition(System.Object left, System.String right)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedCompoundAssignmentOperatorOverloadResolutionFailure() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } public static C operator+(C c1, string s) { return c1; } static void Main() { C c = new C(); /*<bind>*/c += null/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.True(candidates.SetEquals(operators, EqualityComparer<ISymbol>.Default)); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")] [Fact] public void SymbolInfoForUserDefinedCompoundAssignmentOperatorOverloadResolutionFailureEmpty() { var text = @" class C { static void Main() { C c = new C(); /*<bind>*/c += null/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName); Assert.Equal(0, operators.Length); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("System.String System.String.op_Addition(System.Object left, System.String right)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(0, candidates.Length); } [WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550"), WorkItem(529158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529158")] [Fact] public void MethodGroupForUserDefinedBinaryOperator() { var text = @" class C { public static C operator+(C c1, C c2) { return c1 ?? c2; } public static C operator+(C c1, int i) { return c1; } static void Main() { C c1 = new C(); C c2 = new C(); C c3 = /*<bind>*/c1 + c2/*</bind>*/; } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var operators = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMembers(WellKnownMemberNames.AdditionOperatorName).Cast<IMethodSymbol>(); var operatorSymbol = operators.Where(method => method.Parameters[0].Type.Equals(method.Parameters[1].Type, SymbolEqualityComparer.ConsiderEverything)).Single(); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal(operatorSymbol, symbolInfo.Symbol); // NOTE: This check captures, rather than enforces, the current behavior (i.e. feel free to change it). var memberGroup = model.GetMemberGroup(expr); Assert.Equal(0, memberGroup.Length); } [Fact] public void CacheDuplicates() { var text = @" class C { static void Main() { long l = /*<bind>*/(long)1/*</bind>*/; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); bool sawWrongConversionKind = false; ThreadStart ts = () => sawWrongConversionKind |= ConversionKind.Identity != model.GetConversion(expr).Kind; Thread[] threads = new Thread[4]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(ts); } foreach (Thread t in threads) { t.Start(); } foreach (Thread t in threads) { t.Join(); } Assert.False(sawWrongConversionKind); } [WorkItem(543674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543674")] [Fact()] public void SemanticInfo_NormalVsLiftedUserDefinedImplicitConversion() { string text = @" using System; struct G { } struct L { public static implicit operator G(L l) { return default(G); } } class Z { public static void Main() { MNG(/*<bind>*/default(L)/*</bind>*/); } static void MNG(G? g) { } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var gType = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("G"); var mngMethod = (IMethodSymbol)comp.GlobalNamespace.GetMember<INamedTypeSymbol>("Z").GetMembers("MNG").First(); var gNullableType = mngMethod.GetParameterType(0); Assert.True(gNullableType.IsNullableType(), "MNG parameter is not a nullable type?"); Assert.Equal(gType, gNullableType.StrippedType()); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var conversion = model.ClassifyConversion(expr, gNullableType); CheckIsAssignableTo(model, expr); // Here we have a situation where Roslyn deliberately violates the specification in order // to be compatible with the native compiler. // // The specification states that there are two applicable candidates: We can use // the "lifted" operator from L? to G?, or we can use the unlifted operator // from L to G, and then convert the G that comes out the back end to G?. // The specification says that the second conversion is the better conversion. // Therefore, the conversion on the "front end" should be an identity conversion, // and the conversion on the "back end" of the user-defined conversion should // be an implicit nullable conversion. // // This is not at all what the native compiler does, and we match the native // compiler behavior. The native compiler says that there is a "half lifted" // conversion from L-->G?, and that this is the winner. Therefore the conversion // "on the back end" of the user-defined conversion is in fact an *identity* // conversion, even though obviously we are going to have to // do code generation as though it was an implicit nullable conversion. Assert.Equal(ConversionKind.Identity, conversion.UserDefinedFromConversion.Kind); Assert.Equal(ConversionKind.Identity, conversion.UserDefinedToConversion.Kind); Assert.Equal("ImplicitUserDefined", conversion.ToString()); } [WorkItem(543715, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543715")] [Fact] public void SemanticInfo_NormalVsLiftedUserDefinedConversion_ImplicitConversion() { string text = @" using System; struct G {} struct M { public static implicit operator G(M m) { System.Console.WriteLine(1); return default(G); } public static implicit operator G(M? m) {System.Console.WriteLine(2); return default(G); } } class Z { public static void Main() { M? m = new M(); MNG(/*<bind>*/m/*</bind>*/); } static void MNG(G? g) { } } "; var tree = Parse(text); var comp = (Compilation)CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var gType = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("G"); var mngMethod = (IMethodSymbol)comp.GlobalNamespace.GetMember<INamedTypeSymbol>("Z").GetMembers("MNG").First(); var gNullableType = mngMethod.GetParameterType(0); Assert.True(gNullableType.IsNullableType(), "MNG parameter is not a nullable type?"); Assert.Equal(gType, gNullableType.StrippedType()); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var conversion = model.ClassifyConversion(expr, gNullableType); CheckIsAssignableTo(model, expr); Assert.Equal(ConversionKind.ImplicitUserDefined, conversion.Kind); // Dev10 violates the spec for finding the most specific operator for an implicit user-defined conversion. // SPEC: • Find the most specific conversion operator: // SPEC: (a) If U contains exactly one user-defined conversion operator that converts from SX to TX, then this is the most specific conversion operator. // SPEC: (b) Otherwise, if U contains exactly one lifted conversion operator that converts from SX to TX, then this is the most specific conversion operator. // SPEC: (c) Otherwise, the conversion is ambiguous and a compile-time error occurs. // In this test we try to classify conversion from M? to G?. // 1) Classify conversion establishes that SX: M? and TX: G?. // 2) Most specific conversion operator from M? to G?: // (a) does not hold here as neither of the implicit operators convert from M? to G? // (b) does hold here as the lifted form of "implicit operator G(M m)" converts from M? to G? // Hence "operator G(M m)" must be chosen in lifted form, but Dev10 chooses "G M.op_Implicit(System.Nullable<M> m)" in normal form. // We may want to maintain compatibility with Dev10. Assert.Equal("G M.op_Implicit(M? m)", conversion.MethodSymbol.ToTestDisplayString()); Assert.Equal("ImplicitUserDefined", conversion.ToString()); } [Fact] public void AmbiguousImplicitConversionOverloadResolution1() { var source = @" public class A { static public implicit operator A(B b) { return default(A); } } public class B { static public implicit operator A(B b) { return default(A); } } class Test { static void M(A a) { } static void M(object o) { } static void Main() { B b = new B(); /*<bind>*/M(b)/*</bind>*/; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (26,21): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A' Diagnostic(ErrorCode.ERR_AmbigUDConv, "b").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A")); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = (InvocationExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("void Test.M(A a)", symbolInfo.Symbol.ToTestDisplayString()); var argexpr = expr.ArgumentList.Arguments.Single().Expression; var argTypeInfo = model.GetTypeInfo(argexpr); Assert.Equal("B", argTypeInfo.Type.ToTestDisplayString()); Assert.Equal("A", argTypeInfo.ConvertedType.ToTestDisplayString()); var argConversion = model.GetConversion(argexpr); Assert.Equal(ConversionKind.ImplicitUserDefined, argConversion.Kind); Assert.False(argConversion.IsValid); Assert.Null(argConversion.Method); } [Fact] public void AmbiguousImplicitConversionOverloadResolution2() { var source = @" public class A { static public implicit operator A(B<A> b) { return default(A); } } public class B<T> { static public implicit operator T(B<T> b) { return default(T); } } class C { static void M(A a) { } static void M<T>(T t) { } static void Main() { B<A> b = new B<A>(); /*<bind>*/M(b)/*</bind>*/; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); // since no conversion is performed, the ambiguity doesn't matter var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = (InvocationExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.NotNull(expr); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("void C.M<B<A>>(B<A> t)", symbolInfo.Symbol.ToTestDisplayString()); var argexpr = expr.ArgumentList.Arguments.Single().Expression; var argTypeInfo = model.GetTypeInfo(argexpr); Assert.Equal("B<A>", argTypeInfo.Type.ToTestDisplayString()); Assert.Equal("B<A>", argTypeInfo.ConvertedType.ToTestDisplayString()); var argConversion = model.GetConversion(argexpr); Assert.Equal(ConversionKind.Identity, argConversion.Kind); Assert.True(argConversion.IsValid); Assert.Null(argConversion.Method); } [Fact] public void DefaultParameterLocalScope() { var source = @" public class A { static void Main(string[] args, int a = /*<bind>*/System/*</bind>*/.) { } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal("System", expr.ToString()); var info = model.GetSemanticInfoSummary(expr); //Shouldn't throw/assert Assert.Equal(SymbolKind.Namespace, info.Symbol.Kind); } [Fact] public void PinvokeSemanticModel() { var source = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""user32.dll"", CharSet = CharSet.Unicode, ExactSpelling = false, EntryPoint = ""MessageBox"")] public static extern int MessageBox(IntPtr hwnd, string t, string c, UInt32 t2); static void Main() { /*<bind>*/MessageBox(IntPtr.Zero, """", """", 1)/*</bind>*/; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = (InvocationExpressionSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal("MessageBox(IntPtr.Zero, \"\", \"\", 1)", expr.ToString()); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("C.MessageBox(System.IntPtr, string, string, uint)", symbolInfo.Symbol.ToDisplayString()); var argTypeInfo = model.GetTypeInfo(expr.ArgumentList.Arguments.First().Expression); Assert.Equal("System.IntPtr", argTypeInfo.Type.ToTestDisplayString()); Assert.Equal("System.IntPtr", argTypeInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void ImplicitBoxingConversion1() { var source = @" class C { static void Main() { object o = 1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var conv = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Boxing, conv.Kind); } [Fact] public void ImplicitBoxingConversion2() { var source = @" class C { static void Main() { object o = (long)1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var literalConversion = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, literalConversion.Kind); var cast = (CastExpressionSyntax)literal.Parent; var castTypeInfo = model.GetTypeInfo(cast); var castConversion = model.GetConversion(cast); Assert.Equal(SpecialType.System_Int64, castTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, castTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Boxing, castConversion.Kind); } [Fact] public void ExplicitBoxingConversion1() { var source = @" class C { static void Main() { object o = (object)1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var literalConversion = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, literalConversion.Kind); var cast = (CastExpressionSyntax)literal.Parent; var castTypeInfo = model.GetTypeInfo(cast); var castConversion = model.GetConversion(cast); Assert.Equal(SpecialType.System_Object, castTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, castTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, castConversion.Kind); Assert.Equal(ConversionKind.Boxing, model.ClassifyConversion(literal, castTypeInfo.Type).Kind); CheckIsAssignableTo(model, literal); } [Fact] public void ExplicitBoxingConversion2() { var source = @" class C { static void Main() { object o = (object)(long)1; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var literal = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var literalTypeInfo = model.GetTypeInfo(literal); var literalConversion = model.GetConversion(literal); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, literalTypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, literalConversion.Kind); var cast1 = (CastExpressionSyntax)literal.Parent; var cast1TypeInfo = model.GetTypeInfo(cast1); var cast1Conversion = model.GetConversion(cast1); Assert.Equal(SpecialType.System_Int64, cast1TypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Int64, cast1TypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, cast1Conversion.Kind); // Note that this reflects the hypothetical conversion, not the cast in the code. Assert.Equal(ConversionKind.ImplicitNumeric, model.ClassifyConversion(literal, cast1TypeInfo.Type).Kind); CheckIsAssignableTo(model, literal); var cast2 = (CastExpressionSyntax)cast1.Parent; var cast2TypeInfo = model.GetTypeInfo(cast2); var cast2Conversion = model.GetConversion(cast2); Assert.Equal(SpecialType.System_Object, cast2TypeInfo.Type.SpecialType); Assert.Equal(SpecialType.System_Object, cast2TypeInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, cast2Conversion.Kind); Assert.Equal(ConversionKind.Boxing, model.ClassifyConversion(cast1, cast2TypeInfo.Type).Kind); CheckIsAssignableTo(model, cast1); } [WorkItem(545136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545136")] [WorkItem(538320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538320")] [Fact()] // TODO: Dev10 does not report ERR_SameFullNameAggAgg here - source wins. public void SpecialTypeInSourceAndMetadata() { var text = @" using System; namespace System { public struct Void { static void Main() { System./*<bind>*/Void/*</bind>*/.Equals(1, 1); } } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("System.Void", symbolInfo.Symbol.ToString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [Fact] public void SpeculativelyBindMethodGroup1() { var text = @" using System; class C { static void M() { int here; } } "; var compilation = (Compilation)CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" C.M"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), info.CandidateSymbols.Single()); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [Fact] public void SpeculativelyBindMethodGroup2() { var text = @" using System; class C { static void M() { int here; } static void M(int x) { } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" C.M"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); Assert.Equal(2, info.CandidateSymbols.Length); } [WorkItem(546046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546046")] [Fact] public void UnambiguousMethodGroupWithoutBoundParent1() { var text = @" using System; class C { static void M() { /*<bind>*/M/*</bind>*/ "; var compilation = (Compilation)CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, syntax.Kind()); var info = model.GetSymbolInfo(syntax); Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), info.CandidateSymbols.Single()); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); } [WorkItem(546046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546046")] [Fact] public void UnambiguousMethodGroupWithoutBoundParent2() { var text = @" using System; class C { static void M() { /*<bind>*/M/*</bind>*/[] "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.IdentifierName, syntax.Kind()); var info = model.GetSymbolInfo(syntax); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.NotATypeOrNamespace, info.CandidateReason); Assert.Equal(1, info.CandidateSymbols.Length); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [ClrOnlyFact] public void SpeculativelyBindPropertyGroup1() { var source1 = @"Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface IA Property P(o As Object) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @" using System; class C { static void M(IA a) { int here; } } "; var compilation = (Compilation)CreateCompilation(source2, new[] { reference1 }, assemblyName: "SpeculativelyBindPropertyGroup"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = source2.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" a.P"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("IA").GetMember<IPropertySymbol>("P"), info.Symbol); } [WorkItem(544651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544651")] [ClrOnlyFact] public void SpeculativelyBindPropertyGroup2() { var source1 = @"Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface IA Property P(o As Object) As Object Property P(x As Object, y As Object) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @" using System; class C { static void M(IA a) { int here; } } "; var compilation = CreateCompilation(source2, new[] { reference1 }, assemblyName: "SpeculativelyBindPropertyGroup"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = source2.IndexOf("here", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression(" a.P"); //Leading trivia was significant for triggering an assert before the fix. Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, syntax.Kind()); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); Assert.Equal(2, info.CandidateSymbols.Length); } // There is no test analogous to UnambiguousMethodGroupWithoutBoundParent1 because // a.P does not yield a bound property group - it yields a bound indexer access // (i.e. it doesn't actually hit the code path that formerly contained the assert). //[WorkItem(15177)] //[Fact] //public void UnambiguousPropertyGroupWithoutBoundParent1() [WorkItem(546117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546117")] [ClrOnlyFact] public void UnambiguousPropertyGroupWithoutBoundParent2() { var source1 = @"Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface IA Property P(o As Object) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @" using System; class C { static void M(IA a) { /*<bind>*/a.P/*</bind>*/[] "; var compilation = CreateCompilation(source2, new[] { reference1 }, assemblyName: "SpeculativelyBindPropertyGroup"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.QualifiedName, syntax.Kind()); var info = model.GetSymbolInfo(syntax); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.NotATypeOrNamespace, info.CandidateReason); Assert.Equal(1, info.CandidateSymbols.Length); } [WorkItem(544648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544648")] [Fact] public void SpeculativelyBindExtensionMethod() { var source = @" using System; using System.Collections.Generic; using System.Reflection; static class Program { static void Main() { FieldInfo[] fields = typeof(Exception).GetFields(); Console.WriteLine(/*<bind>*/fields.Any((Func<FieldInfo, bool>)(field => field.IsStatic))/*</bind>*/); } static bool Any<T>(this IEnumerable<T> s, Func<T, bool> predicate) { return false; } static bool Any<T>(this ICollection<T> s, Func<T, bool> predicate) { return true; } } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var originalSyntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); Assert.Equal(SyntaxKind.InvocationExpression, originalSyntax.Kind()); var info1 = model.GetSymbolInfo(originalSyntax); var method1 = info1.Symbol as IMethodSymbol; Assert.NotNull(method1); Assert.Equal("System.Boolean System.Collections.Generic.ICollection<System.Reflection.FieldInfo>.Any<System.Reflection.FieldInfo>(System.Func<System.Reflection.FieldInfo, System.Boolean> predicate)", method1.ToTestDisplayString()); Assert.Same(method1.ReducedFrom.TypeParameters[0], method1.TypeParameters[0].ReducedFrom); Assert.Null(method1.ReducedFrom.TypeParameters[0].ReducedFrom); Assert.Equal("System.Boolean Program.Any<T>(this System.Collections.Generic.ICollection<T> s, System.Func<T, System.Boolean> predicate)", method1.ReducedFrom.ToTestDisplayString()); Assert.Equal("System.Collections.Generic.ICollection<System.Reflection.FieldInfo>", method1.ReceiverType.ToTestDisplayString()); Assert.Equal("System.Reflection.FieldInfo", method1.GetTypeInferredDuringReduction(method1.ReducedFrom.TypeParameters[0]).ToTestDisplayString()); Assert.Throws<InvalidOperationException>(() => method1.ReducedFrom.GetTypeInferredDuringReduction(null)); Assert.Throws<ArgumentNullException>(() => method1.GetTypeInferredDuringReduction(null)); Assert.Throws<ArgumentException>(() => method1.GetTypeInferredDuringReduction( comp.Assembly.GlobalNamespace.GetMember<INamedTypeSymbol>("Program").GetMembers("Any"). Where((m) => (object)m != (object)method1.ReducedFrom).Cast<IMethodSymbol>().Single().TypeParameters[0])); Assert.Equal("Any", method1.Name); var reducedFrom1 = method1.GetSymbol().CallsiteReducedFromMethod; Assert.NotNull(reducedFrom1); Assert.Equal("System.Boolean Program.Any<System.Reflection.FieldInfo>(this System.Collections.Generic.ICollection<System.Reflection.FieldInfo> s, System.Func<System.Reflection.FieldInfo, System.Boolean> predicate)", reducedFrom1.ToTestDisplayString()); Assert.Equal("Program", reducedFrom1.ReceiverType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Collections_Generic_ICollection_T, ((TypeSymbol)reducedFrom1.Parameters[0].Type.OriginalDefinition).SpecialType); var speculativeSyntax = SyntaxFactory.ParseExpression("fields.Any((field => field.IsStatic))"); //cast removed Assert.Equal(SyntaxKind.InvocationExpression, speculativeSyntax.Kind()); var info2 = model.GetSpeculativeSymbolInfo(originalSyntax.SpanStart, speculativeSyntax, SpeculativeBindingOption.BindAsExpression); var method2 = info2.Symbol as IMethodSymbol; Assert.NotNull(method2); Assert.Equal("Any", method2.Name); var reducedFrom2 = method2.GetSymbol().CallsiteReducedFromMethod; Assert.NotNull(reducedFrom2); Assert.Equal(SpecialType.System_Collections_Generic_ICollection_T, ((TypeSymbol)reducedFrom2.Parameters[0].Type.OriginalDefinition).SpecialType); Assert.Equal(reducedFrom1, reducedFrom2); Assert.Equal(method1, method2); } /// <summary> /// This test reproduces the issue we were seeing in DevDiv #13366: LocalSymbol.SetType was asserting /// because it was set to IEnumerable&lt;int&gt; before binding the declaration of x but to an error /// type after binding the declaration of x. /// </summary> [WorkItem(545097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545097")] [Fact] public void NameConflictDuringLambdaBinding1() { var source = @" using System.Linq; class C { static void Main() { var x = 0; var q = from e in """" let x = 2 select x; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var localDecls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclarationSyntax>(); var localDecl1 = localDecls.First(); Assert.Equal("x", localDecl1.Variables.Single().Identifier.ValueText); var localDecl2 = localDecls.Last(); Assert.Equal("q", localDecl2.Variables.Single().Identifier.ValueText); var model = comp.GetSemanticModel(tree); var info0 = model.GetSymbolInfo(localDecl2.Type); Assert.Equal(SpecialType.System_Collections_Generic_IEnumerable_T, ((ITypeSymbol)info0.Symbol.OriginalDefinition).SpecialType); Assert.Equal(SpecialType.System_Int32, ((INamedTypeSymbol)info0.Symbol).TypeArguments.Single().SpecialType); var info1 = model.GetSymbolInfo(localDecl1.Type); Assert.Equal(SpecialType.System_Int32, ((ITypeSymbol)info1.Symbol).SpecialType); // This used to assert because the second binding would see the declaration of x and report CS7040, disrupting the delegate conversion. var info2 = model.GetSymbolInfo(localDecl2.Type); Assert.Equal(SpecialType.System_Collections_Generic_IEnumerable_T, ((ITypeSymbol)info2.Symbol.OriginalDefinition).SpecialType); Assert.Equal(SpecialType.System_Int32, ((INamedTypeSymbol)info2.Symbol).TypeArguments.Single().SpecialType); comp.VerifyDiagnostics( // (9,34): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // var q = from e in "" let x = 2 select x; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(9, 34), // (8,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(8, 13) ); } /// <summary> /// This test reverses the order of statement binding from NameConflictDuringLambdaBinding2 to confirm that /// the results are the same. /// </summary> [WorkItem(545097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545097")] [Fact] public void NameConflictDuringLambdaBinding2() { var source = @" using System.Linq; class C { static void Main() { var x = 0; var q = from e in """" let x = 2 select x; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var localDecls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclarationSyntax>(); var localDecl1 = localDecls.First(); Assert.Equal("x", localDecl1.Variables.Single().Identifier.ValueText); var localDecl2 = localDecls.Last(); Assert.Equal("q", localDecl2.Variables.Single().Identifier.ValueText); var model = comp.GetSemanticModel(tree); var info1 = model.GetSymbolInfo(localDecl1.Type); Assert.Equal(SpecialType.System_Int32, ((ITypeSymbol)info1.Symbol).SpecialType); // This used to assert because the second binding would see the declaration of x and report CS7040, disrupting the delegate conversion. var info2 = model.GetSymbolInfo(localDecl2.Type); Assert.Equal(SpecialType.System_Collections_Generic_IEnumerable_T, ((ITypeSymbol)info2.Symbol.OriginalDefinition).SpecialType); Assert.Equal(SpecialType.System_Int32, ((INamedTypeSymbol)info2.Symbol).TypeArguments.Single().SpecialType); comp.VerifyDiagnostics( // (9,34): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // var q = from e in "" let x = 2 select x; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(9, 34), // (8,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(8, 13) ); } [WorkItem(546263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546263")] [Fact] public void SpeculativeSymbolInfoForOmittedTypeArgumentSyntaxNode() { var text = @"namespace N2 { using N1; class Test { class N1<G1> {} static void Main() { int res = 0; N1<int> n1 = new N1<int>(); global::N1 < > .C1 c1 = null; } } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("< >", StringComparison.Ordinal); var syntax = tree.GetCompilationUnitRoot().FindToken(position).Parent.DescendantNodesAndSelf().OfType<OmittedTypeArgumentSyntax>().Single(); var info = model.GetSpeculativeSymbolInfo(syntax.SpanStart, syntax, SpeculativeBindingOption.BindAsTypeOrNamespace); Assert.Null(info.Symbol); } [WorkItem(530313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530313")] [Fact] public void SpeculativeTypeInfoForOmittedTypeArgumentSyntaxNode() { var text = @"namespace N2 { using N1; class Test { class N1<G1> {} static void Main() { int res = 0; N1<int> n1 = new N1<int>(); global::N1 < > .C1 c1 = null; } } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("< >", StringComparison.Ordinal); var syntax = tree.GetCompilationUnitRoot().FindToken(position).Parent.DescendantNodesAndSelf().OfType<OmittedTypeArgumentSyntax>().Single(); var info = model.GetSpeculativeTypeInfo(syntax.SpanStart, syntax, SpeculativeBindingOption.BindAsTypeOrNamespace); Assert.Equal(TypeInfo.None, info); } [WorkItem(546266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546266")] [Fact] public void SpeculativeTypeInfoForGenericNameSyntaxWithinTypeOfInsideAnonMethod() { var text = @" delegate void Del(); class C { public void M1() { Del d = delegate () { var v1 = typeof(S<,,,>); }; } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf("S<,,,>", StringComparison.Ordinal); var syntax = tree.GetCompilationUnitRoot().FindToken(position).Parent.DescendantNodesAndSelf().OfType<GenericNameSyntax>().Single(); var info = model.GetSpeculativeTypeInfo(syntax.SpanStart, syntax, SpeculativeBindingOption.BindAsTypeOrNamespace); Assert.NotNull(info.Type); } [WorkItem(547160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547160")] [Fact, WorkItem(531496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531496")] public void SemanticInfoForOmittedTypeArgumentInIncompleteMember() { var text = @" class Test { C<> "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<OmittedTypeArgumentSyntax>().Single(); var info = model.GetSemanticInfoSummary(syntax); Assert.Null(info.Alias); Assert.Equal(CandidateReason.None, info.CandidateReason); Assert.True(info.CandidateSymbols.IsEmpty); Assert.False(info.ConstantValue.HasValue); Assert.Null(info.ConvertedType); Assert.Equal(Conversion.Identity, info.ImplicitConversion); Assert.False(info.IsCompileTimeConstant); Assert.True(info.MemberGroup.IsEmpty); Assert.True(info.MethodGroup.IsEmpty); Assert.Null(info.Symbol); Assert.Null(info.Type); } [WorkItem(547160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547160")] [Fact, WorkItem(531496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531496")] public void CollectionInitializerSpeculativeInfo() { var text = @" class Test { } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var speculativeSyntax = SyntaxFactory.ParseExpression("new List { 1, 2 }"); var initializerSyntax = speculativeSyntax.DescendantNodesAndSelf().OfType<InitializerExpressionSyntax>().Single(); var symbolInfo = model.GetSpeculativeSymbolInfo(0, initializerSyntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); var typeInfo = model.GetSpeculativeTypeInfo(0, initializerSyntax, SpeculativeBindingOption.BindAsExpression); Assert.Equal(TypeInfo.None, typeInfo); } [WorkItem(531362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531362")] [Fact] public void DelegateElementAccess() { var text = @" class C { void M(bool b) { System.Action o = delegate { if (b) { } } [1]; } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (6,27): error CS0021: Cannot apply indexing with [] to an expression of type 'anonymous method' // System.Action o = delegate { if (b) { } } [1]; Diagnostic(ErrorCode.ERR_BadIndexLHS, "delegate { if (b) { } } [1]").WithArguments("anonymous method")); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Last(id => id.Identifier.ValueText == "b"); var info = model.GetSymbolInfo(syntax); } [Fact] public void EnumBitwiseComplement() { var text = @" using System; enum Color { Red, Green, Blue } class C { static void Main() { Func<Color, Color> f2 = x => /*<bind>*/~x/*</bind>*/; } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var info = model.GetTypeInfo(syntax); var conv = model.GetConversion(syntax); Assert.Equal(TypeKind.Enum, info.Type.TypeKind); Assert.Equal(ConversionKind.Identity, conv.Kind); } [WorkItem(531534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531534")] [Fact] public void LambdaOutsideMemberModel() { var text = @" int P { badAccessorName { M(env => env); "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Last(); var symbol = model.GetDeclaredSymbol(syntax); // Doesn't assert. Assert.Null(symbol); } [WorkItem(633340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633340")] [Fact] public void MemberOfInaccessibleType() { var text = @" class A { private class Nested { public class Another { } } } public class B : A { public Nested.Another a; } "; var compilation = (Compilation)CreateCompilation(text); var global = compilation.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var classNested = classA.GetMember<INamedTypeSymbol>("Nested"); var classAnother = classNested.GetMember<INamedTypeSymbol>("Another"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var fieldSyntax = tree.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>().Single(); var qualifiedSyntax = (QualifiedNameSyntax)fieldSyntax.Declaration.Type; var leftSyntax = qualifiedSyntax.Left; var rightSyntax = qualifiedSyntax.Right; var leftInfo = model.GetSymbolInfo(leftSyntax); Assert.Equal(CandidateReason.Inaccessible, leftInfo.CandidateReason); Assert.Equal(classNested, leftInfo.CandidateSymbols.Single()); var rightInfo = model.GetSymbolInfo(rightSyntax); Assert.Equal(CandidateReason.Inaccessible, rightInfo.CandidateReason); Assert.Equal(classAnother, rightInfo.CandidateSymbols.Single()); compilation.VerifyDiagnostics( // (12,14): error CS0060: Inconsistent accessibility: base type 'A' is less accessible than class 'B' // public class B : A Diagnostic(ErrorCode.ERR_BadVisBaseClass, "B").WithArguments("B", "A"), // (14,12): error CS0122: 'A.Nested' is inaccessible due to its protection level // public Nested.Another a; Diagnostic(ErrorCode.ERR_BadAccess, "Nested").WithArguments("A.Nested")); } [WorkItem(633340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633340")] [Fact] public void NotReferencableMemberOfInaccessibleType() { var text = @" class A { private class Nested { public int P { get; set; } } } class B : A { int Test(Nested nested) { return nested.get_P(); } } "; var compilation = (Compilation)CreateCompilation(text); var global = compilation.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var classNested = classA.GetMember<INamedTypeSymbol>("Nested"); var propertyP = classNested.GetMember<IPropertySymbol>("P"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccessSyntax = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var info = model.GetSymbolInfo(memberAccessSyntax); Assert.Equal(CandidateReason.NotReferencable, info.CandidateReason); Assert.Equal(propertyP.GetMethod, info.CandidateSymbols.Single()); compilation.VerifyDiagnostics( // (12,14): error CS0122: 'A.Nested' is inaccessible due to its protection level // int Test(Nested nested) Diagnostic(ErrorCode.ERR_BadAccess, "Nested").WithArguments("A.Nested"), // (14,23): error CS0571: 'A.Nested.P.get': cannot explicitly call operator or accessor // return nested.get_P(); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("A.Nested.P.get") ); } [WorkItem(633340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633340")] [Fact] public void AccessibleMemberOfInaccessibleType() { var text = @" public class A { private class Nested { } } public class B : A { void Test() { Nested.ReferenceEquals(null, null); // Actually object.ReferenceEquals. } } "; var compilation = (Compilation)CreateCompilation(text); var global = compilation.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var classNested = classA.GetMember<INamedTypeSymbol>("Nested"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var callSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var methodAccessSyntax = (MemberAccessExpressionSyntax)callSyntax.Expression; var nestedTypeAccessSyntax = methodAccessSyntax.Expression; var typeInfo = model.GetSymbolInfo(nestedTypeAccessSyntax); Assert.Equal(CandidateReason.Inaccessible, typeInfo.CandidateReason); Assert.Equal(classNested, typeInfo.CandidateSymbols.Single()); var methodInfo = model.GetSymbolInfo(callSyntax); Assert.Equal(compilation.GetSpecialTypeMember(SpecialMember.System_Object__ReferenceEquals), methodInfo.Symbol); compilation.VerifyDiagnostics( // (13,9): error CS0122: 'A.Nested' is inaccessible due to its protection level // Nested.ReferenceEquals(null, null); // Actually object.ReferenceEquals. Diagnostic(ErrorCode.ERR_BadAccess, "Nested").WithArguments("A.Nested")); } [WorkItem(530252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530252")] [Fact] public void MethodGroupHiddenSymbols1() { var text = @" class C { public override int GetHashCode() { return 0; } } struct S { public override int GetHashCode() { return 0; } } class Test { int M(C c) { return c.GetHashCode } int M(S s) { return s.GetHashCode } } "; var compilation = CreateCompilation(text); var global = compilation.GlobalNamespace; var classType = global.GetMember<NamedTypeSymbol>("C"); var structType = global.GetMember<NamedTypeSymbol>("S"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccesses = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().ToArray(); Assert.Equal(2, memberAccesses.Length); var classMemberAccess = memberAccesses[0]; var structMemberAccess = memberAccesses[1]; var classInfo = model.GetSymbolInfo(classMemberAccess); var structInfo = model.GetSymbolInfo(structMemberAccess); // Only one candidate. Assert.Equal(CandidateReason.OverloadResolutionFailure, classInfo.CandidateReason); Assert.Equal("System.Int32 C.GetHashCode()", classInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, structInfo.CandidateReason); Assert.Equal("System.Int32 S.GetHashCode()", structInfo.CandidateSymbols.Single().ToTestDisplayString()); } [WorkItem(530252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530252")] [Fact] public void MethodGroupHiddenSymbols2() { var text = @" class A { public virtual void M() { } } class B : A { public override void M() { } } class C : B { public override void M() { } } class Program { static void Main(string[] args) { C c = new C(); c.M } } "; var compilation = CreateCompilation(text); var classC = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccess = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var info = model.GetSymbolInfo(memberAccess); // Only one candidate. Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); Assert.Equal("void C.M()", info.CandidateSymbols.Single().ToTestDisplayString()); } [Fact] [WorkItem(645512, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645512")] public void LookupProtectedMemberOnConstrainedTypeParameter() { var source = @" class A { protected void Goo() { } } class C : A { public void Bar<T>(T t, C c) where T : C { t.Goo(); c.Goo(); } } "; var comp = (Compilation)CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var methodGoo = classA.GetMember<IMethodSymbol>("Goo"); var classC = global.GetMember<INamedTypeSymbol>("C"); var methodBar = classC.GetMember<IMethodSymbol>("Bar"); var paramType0 = methodBar.GetParameterType(0); Assert.Equal(TypeKind.TypeParameter, paramType0.TypeKind); var paramType1 = methodBar.GetParameterType(1); Assert.Equal(TypeKind.Class, paramType1.TypeKind); int position = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First().SpanStart; Assert.Contains("Goo", model.LookupNames(position, paramType0)); Assert.Contains("Goo", model.LookupNames(position, paramType1)); } [Fact] [WorkItem(645512, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645512")] public void LookupProtectedMemberOnConstrainedTypeParameter2() { var source = @" class A { protected void Goo() { } } class C : A { public void Bar<T, U>(T t, C c) where T : U where U : C { t.Goo(); c.Goo(); } } "; var comp = (Compilation)CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var classA = global.GetMember<INamedTypeSymbol>("A"); var methodGoo = classA.GetMember<IMethodSymbol>("Goo"); var classC = global.GetMember<INamedTypeSymbol>("C"); var methodBar = classC.GetMember<IMethodSymbol>("Bar"); var paramType0 = methodBar.GetParameterType(0); Assert.Equal(TypeKind.TypeParameter, paramType0.TypeKind); var paramType1 = methodBar.GetParameterType(1); Assert.Equal(TypeKind.Class, paramType1.TypeKind); int position = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First().SpanStart; Assert.Contains("Goo", model.LookupNames(position, paramType0)); Assert.Contains("Goo", model.LookupNames(position, paramType1)); } [Fact] [WorkItem(652583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/652583")] public void ParameterDefaultValueWithoutParameter() { var source = @" class A { protected void Goo(bool b, = true "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var trueLiteral = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); Assert.Equal(SyntaxKind.TrueLiteralExpression, trueLiteral.Kind()); model.GetSymbolInfo(trueLiteral); var parameterSyntax = trueLiteral.FirstAncestorOrSelf<ParameterSyntax>(); Assert.Equal(SyntaxKind.Parameter, parameterSyntax.Kind()); model.GetDeclaredSymbol(parameterSyntax); } [Fact] [WorkItem(530791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530791")] public void Repro530791() { var source = @" class Program { static void Main(string[] args) { Test test = new Test(() => { return null; }); } } class Test { } "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(lambdaSyntax); var lambda = (IMethodSymbol)symbolInfo.Symbol; Assert.False(lambda.ReturnsVoid); Assert.Equal(SymbolKind.ErrorType, lambda.ReturnType.Kind); } [Fact] public void InvocationInLocalDeclarationInLambdaInConstructorInitializer() { var source = @" using System; public class C { public int M() { return null; } } public class Test { public Test() : this(c => { int i = c.M(); return i; }) { } public Test(Func<C, int> f) { } } "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(syntax); var methodSymbol = (IMethodSymbol)symbolInfo.Symbol; Assert.False(methodSymbol.ReturnsVoid); } [Fact] [WorkItem(654753, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/654753")] public void Repro654753() { var source = @" using System; using System.Collections.Generic; using System.Linq; public class C { private readonly C Instance = new C(); bool M(IDisposable d) { using(d) { bool any = this.Instance.GetList().OfType<D>().Any(); return any; } } IEnumerable<C> GetList() { return null; } } public class D : C { } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = source.IndexOf("this", StringComparison.Ordinal); var statement = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var newSyntax = SyntaxFactory.ParseExpression("Instance.GetList().OfType<D>().Any()"); var newStatement = statement.ReplaceNode(statement.Declaration.Variables[0].Initializer.Value, newSyntax); newSyntax = newStatement.Declaration.Variables[0].Initializer.Value; SemanticModel speculativeModel; bool success = model.TryGetSpeculativeSemanticModel(position, newStatement, out speculativeModel); Assert.True(success); Assert.NotNull(speculativeModel); var newSyntaxMemberAccess = newSyntax.DescendantNodesAndSelf().OfType<MemberAccessExpressionSyntax>(). Single(e => e.ToString() == "Instance.GetList().OfType<D>"); speculativeModel.GetTypeInfo(newSyntaxMemberAccess); } [Fact] [WorkItem(750557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750557")] public void MethodGroupFromMetadata() { var source = @" class Goo { delegate int D(int i); void M() { var v = ((D)(x => x)).Equals is bool; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = source.IndexOf("Equals", StringComparison.Ordinal); var equalsToken = tree.GetRoot().FindToken(position); var equalsNode = equalsToken.Parent; var symbolInfo = model.GetSymbolInfo(equalsNode); //note that we don't guarantee what symbol will come back on a method group in an is expression. Assert.Null(symbolInfo.Symbol); Assert.True(symbolInfo.CandidateSymbols.Length > 0); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); } [Fact, WorkItem(531304, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531304")] public void GetPreprocessingSymbolInfoForDefinedSymbol() { string sourceCode = @" #define X #if X //bind #define Z #endif #if Z //bind #endif // broken code cases #define A #if A + 1 //bind #endif #define B = 0 #if B //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "X //bind"); Assert.Equal("X", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "A + 1 //bind"); Assert.Equal("A", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "B //bind"); Assert.Equal("B", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); Assert.True(symbolInfo.Symbol.Equals(symbolInfo.Symbol)); Assert.False(symbolInfo.Symbol.Equals(null)); PreprocessingSymbolInfo symbolInfo2 = GetPreprocessingSymbolInfoForTest(sourceCode, "B //bind"); Assert.NotSame(symbolInfo.Symbol, symbolInfo2.Symbol); Assert.Equal(symbolInfo.Symbol, symbolInfo2.Symbol); Assert.Equal(symbolInfo.Symbol.GetHashCode(), symbolInfo2.Symbol.GetHashCode()); } [Fact, WorkItem(531304, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531304")] public void GetPreprocessingSymbolInfoForUndefinedSymbol() { string sourceCode = @" #define X #undef X #if X //bind #endif #if x //bind #endif #if Y //bind #define Z #endif #if Z //bind #endif // Not in preprocessor trivia #define A public class T { public int Goo(int A) { return A; //bind } } "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "X //bind"); Assert.Equal("X", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "x //bind"); Assert.Equal("x", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Y //bind"); Assert.Equal("Y", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "A; //bind"); Assert.Null(symbolInfo.Symbol); } [Fact, WorkItem(531304, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531304"), WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void GetPreprocessingSymbolInfoForSymbolDefinedLaterInSource() { string sourceCode = @" #if Z //bind #endif #define Z "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_01() { string sourceCode = @" #define Z #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_02() { string sourceCode = @" #if true #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_03() { string sourceCode = @" #if false #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_04() { string sourceCode = @" #if true #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_05() { string sourceCode = @" #if false #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_06() { string sourceCode = @" #if true #else #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_07() { string sourceCode = @" #if false #else #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_08() { string sourceCode = @" #if true #define Z #else #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_09() { string sourceCode = @" #if false #define Z #else #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_10() { string sourceCode = @" #if true #elif true #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_11() { string sourceCode = @" #if false #elif true #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_12() { string sourceCode = @" #if false #elif false #define Z #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_13() { string sourceCode = @" #if true #define Z #elif false #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_14() { string sourceCode = @" #if true #define Z #elif true #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_15() { string sourceCode = @" #if false #define Z #elif true #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_16() { string sourceCode = @" #if false #define Z #elif false #if Z //bind #endif #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_17() { string sourceCode = @" #if false #else #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_18() { string sourceCode = @" #if false #elif true #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.True(symbolInfo.IsDefined, "must be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_19() { string sourceCode = @" #if true #else #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_20() { string sourceCode = @" #if true #elif true #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_21() { string sourceCode = @" #if true #elif false #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [Fact, WorkItem(720566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/720566")] public void Bug720566_22() { string sourceCode = @" #if false #elif false #define Z #endif #if Z //bind #endif "; PreprocessingSymbolInfo symbolInfo = GetPreprocessingSymbolInfoForTest(sourceCode, "Z //bind"); Assert.Equal("Z", symbolInfo.Symbol.Name); Assert.False(symbolInfo.IsDefined, "must not be defined"); } [WorkItem(835391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835391")] [Fact] public void ConstructedErrorTypeValidation() { var text = @"class C1 : E1 { } class C2<T> : E2<T> { }"; var compilation = (Compilation)CreateCompilation(text); var objectType = compilation.GetSpecialType(SpecialType.System_Object); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); // Non-generic type. var type = (INamedTypeSymbol)model.GetDeclaredSymbol(root.Members[0]); Assert.False(type.IsGenericType); Assert.False(type.IsErrorType()); Assert.Throws<InvalidOperationException>(() => type.Construct(objectType)); // non-generic type // Non-generic error type. type = type.BaseType; Assert.False(type.IsGenericType); Assert.True(type.IsErrorType()); Assert.Throws<InvalidOperationException>(() => type.Construct(objectType)); // non-generic type // Generic type. type = (INamedTypeSymbol)model.GetDeclaredSymbol(root.Members[1]); Assert.True(type.IsGenericType); Assert.False(type.IsErrorType()); Assert.Throws<ArgumentException>(() => type.Construct(new ITypeSymbol[] { null })); // null type arg Assert.Throws<ArgumentException>(() => type.Construct()); // typeArgs.Length != Arity Assert.Throws<InvalidOperationException>(() => type.Construct(objectType).Construct(objectType)); // constructed type // Generic error type. type = type.BaseType.ConstructedFrom; Assert.True(type.IsGenericType); Assert.True(type.IsErrorType()); Assert.Throws<ArgumentException>(() => type.Construct(new ITypeSymbol[] { null })); // null type arg Assert.Throws<ArgumentException>(() => type.Construct()); // typeArgs.Length != Arity Assert.Throws<InvalidOperationException>(() => type.Construct(objectType).Construct(objectType)); // constructed type } [Fact] [WorkItem(849371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849371")] public void NestedLambdaErrorRecovery() { var source = @" using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main() { Task<IEnumerable<Task<A>>> teta = null; teta.ContinueWith(tasks => { var list = tasks.Result.Select(t => X(t.Result)); // Wrong argument type for X. list.ToString(); }); } static B X(int x) { return null; } class A { } class B { } } "; for (int i = 0; i < 10; i++) // Ten runs to ensure consistency. { var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (13,51): error CS1503: Argument 1: cannot convert from 'Program.A' to 'int' // var list = tasks.Result.Select(t => X(t.Result)); // Wrong argument type for X. Diagnostic(ErrorCode.ERR_BadArgType, "t.Result").WithArguments("1", "Program.A", "int").WithLocation(13, 51), // (13,30): error CS1061: 'System.Threading.Tasks.Task' does not contain a definition for 'Result' and no extension method 'Result' accepting a first argument of type 'System.Threading.Tasks.Task' could be found (are you missing a using directive or an assembly reference?) // var list = tasks.Result.Select(t => X(t.Result)); // Wrong argument type for X. Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Result").WithArguments("System.Threading.Tasks.Task", "Result").WithLocation(13, 30)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocationSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); var invocationInfo = model.GetSymbolInfo(invocationSyntax); Assert.Equal(CandidateReason.OverloadResolutionFailure, invocationInfo.CandidateReason); Assert.Null(invocationInfo.Symbol); Assert.NotEqual(0, invocationInfo.CandidateSymbols.Length); var parameterSyntax = invocationSyntax.DescendantNodes().OfType<ParameterSyntax>().First(); var parameterSymbol = model.GetDeclaredSymbol(parameterSyntax); Assert.Equal("System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<System.Threading.Tasks.Task<Program.A>>>", parameterSymbol.Type.ToTestDisplayString()); } } [WorkItem(849371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849371")] [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [WorkItem(854548, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854548")] [Fact] public void SemanticModelLambdaErrorRecovery() { var source = @" using System; class Program { static void Main() { M(() => 1); // Neither overload wins. } static void M(Func<string> a) { } static void M(Func<char> a) { } } "; { var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var otherFuncType = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(comp.GetSpecialType(SpecialType.System_Int32)); var typeInfo = model.GetTypeInfo(lambdaSyntax); Assert.Null(typeInfo.Type); Assert.NotEqual(otherFuncType, typeInfo.ConvertedType); } { var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var otherFuncType = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(comp.GetSpecialType(SpecialType.System_Int32)); var conversion = model.ClassifyConversion(lambdaSyntax, otherFuncType); CheckIsAssignableTo(model, lambdaSyntax); var typeInfo = model.GetTypeInfo(lambdaSyntax); Assert.Null(typeInfo.Type); Assert.NotEqual(otherFuncType, typeInfo.ConvertedType); // Not affected by call to ClassifyConversion. } } [Fact] [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] public void ClassifyConversionOnNull() { var source = @" class Program { static void Main() { M(null); // Ambiguous. } static void M(A a) { } static void M(B b) { } } class A { } class B { } class C { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); // Ambiguous. Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(6, 9)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var nullSyntax = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var typeC = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); var conversion = model.ClassifyConversion(nullSyntax, typeC); CheckIsAssignableTo(model, nullSyntax); Assert.Equal(ConversionKind.ImplicitReference, conversion.Kind); } [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [Fact] public void ClassifyConversionOnLambda() { var source = @" using System; class Program { static void Main() { M(() => null); } static void M(Func<A> a) { } } class A { } class B { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var typeB = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("B"); var typeFuncB = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(typeB); var conversion = model.ClassifyConversion(lambdaSyntax, typeFuncB); CheckIsAssignableTo(model, lambdaSyntax); Assert.Equal(ConversionKind.AnonymousFunction, conversion.Kind); } [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [Fact] public void ClassifyConversionOnAmbiguousLambda() { var source = @" using System; class Program { static void Main() { M(() => null); // Ambiguous. } static void M(Func<A> a) { } static void M(Func<B> b) { } } class A { } class B { } class C { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(System.Func<A>)' and 'Program.M(System.Func<B>)' // M(() => null); // Ambiguous. Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(System.Func<A>)", "Program.M(System.Func<B>)").WithLocation(8, 9)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var lambdaSyntax = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var typeC = comp.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); var typeFuncC = comp.GetWellKnownType(WellKnownType.System_Func_T).Construct(typeC); var conversion = model.ClassifyConversion(lambdaSyntax, typeFuncC); CheckIsAssignableTo(model, lambdaSyntax); Assert.Equal(ConversionKind.AnonymousFunction, conversion.Kind); } [WorkItem(854543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854543")] [Fact] public void ClassifyConversionOnAmbiguousMethodGroup() { var source = @" using System; class Base<T> { public A N(T t) { throw null; } public B N(int t) { throw null; } } class Derived : Base<int> { void Test() { M(N); // Ambiguous. } static void M(Func<int, A> a) { } static void M(Func<int, B> b) { } } class A { } class B { } class C { } "; var comp = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Derived.M(System.Func<int, A>)' and 'Derived.M(System.Func<int, B>)' // M(N); // Ambiguous. Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Derived.M(System.Func<int, A>)", "Derived.M(System.Func<int, B>)").WithLocation(14, 9)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var methodGroupSyntax = tree.GetRoot().DescendantNodes().OfType<ArgumentSyntax>().Single().Expression; var global = comp.GlobalNamespace; var typeA = global.GetMember<INamedTypeSymbol>("A"); var typeB = global.GetMember<INamedTypeSymbol>("B"); var typeC = global.GetMember<INamedTypeSymbol>("C"); var typeInt = comp.GetSpecialType(SpecialType.System_Int32); var typeFunc = comp.GetWellKnownType(WellKnownType.System_Func_T2); var typeFuncA = typeFunc.Construct(typeInt, typeA); var typeFuncB = typeFunc.Construct(typeInt, typeB); var typeFuncC = typeFunc.Construct(typeInt, typeC); var conversionA = model.ClassifyConversion(methodGroupSyntax, typeFuncA); CheckIsAssignableTo(model, methodGroupSyntax); Assert.Equal(ConversionKind.MethodGroup, conversionA.Kind); var conversionB = model.ClassifyConversion(methodGroupSyntax, typeFuncB); Assert.Equal(ConversionKind.MethodGroup, conversionB.Kind); var conversionC = model.ClassifyConversion(methodGroupSyntax, typeFuncC); Assert.Equal(ConversionKind.NoConversion, conversionC.Kind); } [WorkItem(872064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872064")] [Fact] public void PartialMethodImplementationDiagnostics() { var file1 = @" namespace ConsoleApplication1 { class Program { static void Main(string[] args) { } } partial class MyPartialClass { partial void MyPartialMethod(MyUndefinedMethod m); } } "; var file2 = @" namespace ConsoleApplication1 { partial class MyPartialClass { partial void MyPartialMethod(MyUndefinedMethod m) { c = new MyUndefinedMethod(23, true); } } } "; var tree1 = Parse(file1); var tree2 = Parse(file2); var comp = CreateCompilation(new[] { tree1, tree2 }); var model = comp.GetSemanticModel(tree2); var errs = model.GetDiagnostics(); Assert.Equal(3, errs.Count()); errs = model.GetSyntaxDiagnostics(); Assert.Equal(0, errs.Count()); errs = model.GetDeclarationDiagnostics(); Assert.Equal(1, errs.Count()); errs = model.GetMethodBodyDiagnostics(); Assert.Equal(2, errs.Count()); } [Fact] public void PartialTypeDiagnostics_StaticConstructors() { var file1 = @" partial class C { static C() {} } "; var file2 = @" partial class C { static C() {} } "; var file3 = @" partial class C { static C() {} } "; var tree1 = Parse(file1); var tree2 = Parse(file2); var tree3 = Parse(file3); var comp = CreateCompilation(new[] { tree1, tree2, tree3 }); var model1 = comp.GetSemanticModel(tree1); var model2 = comp.GetSemanticModel(tree2); var model3 = comp.GetSemanticModel(tree3); model1.GetDeclarationDiagnostics().Verify(); model2.GetDeclarationDiagnostics().Verify( // (4,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 12)); model3.GetDeclarationDiagnostics().Verify( // (4,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 12)); Assert.Equal(3, comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").StaticConstructors.Length); } [Fact] public void PartialTypeDiagnostics_Constructors() { var file1 = @" partial class C { C() {} } "; var file2 = @" partial class C { C() {} } "; var file3 = @" partial class C { C() {} } "; var tree1 = Parse(file1); var tree2 = Parse(file2); var tree3 = Parse(file3); var comp = CreateCompilation(new[] { tree1, tree2, tree3 }); var model1 = comp.GetSemanticModel(tree1); var model2 = comp.GetSemanticModel(tree2); var model3 = comp.GetSemanticModel(tree3); model1.GetDeclarationDiagnostics().Verify(); model2.GetDeclarationDiagnostics().Verify( // (4,5): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 5)); model3.GetDeclarationDiagnostics().Verify( // (4,5): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 5)); Assert.Equal(3, comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Length); } [WorkItem(1076661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1076661")] [Fact] public void Bug1076661() { const string source = @" using X = System.Collections.Generic.List<dynamic>; class Test { void Goo(ref X. x) { } }"; var comp = CreateCompilation(source); var diag = comp.GetDiagnostics(); } [Fact] public void QueryClauseInBadStatement_Catch() { var source = @"using System; class C { static void F(object[] c) { catch (Exception) when (from o in c where true) { } } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var tokens = tree.GetCompilationUnitRoot().DescendantTokens(); var expr = tokens.Single(t => t.Kind() == SyntaxKind.TrueKeyword).Parent; Assert.Null(model.GetSymbolInfo(expr).Symbol); Assert.Equal(SpecialType.System_Boolean, model.GetTypeInfo(expr).Type.SpecialType); } [Fact] public void GetSpecialType_ThrowsOnLessThanZero() { var source = "class C1 { }"; var comp = CreateCompilation(source); var specialType = (SpecialType)(-1); var exceptionThrown = false; try { comp.GetSpecialType(specialType); } catch (ArgumentOutOfRangeException e) { exceptionThrown = true; Assert.StartsWith(expectedStartString: $"Unexpected SpecialType: '{(int)specialType}'.", actualString: e.Message); } Assert.True(exceptionThrown, $"{nameof(comp.GetSpecialType)} did not throw when it should have."); } [Fact] public void GetSpecialType_ThrowsOnGreaterThanCount() { var source = "class C1 { }"; var comp = CreateCompilation(source); var specialType = SpecialType.Count + 1; var exceptionThrown = false; try { comp.GetSpecialType(specialType); } catch (ArgumentOutOfRangeException e) { exceptionThrown = true; Assert.StartsWith(expectedStartString: $"Unexpected SpecialType: '{(int)specialType}'.", actualString: e.Message); } Assert.True(exceptionThrown, $"{nameof(comp.GetSpecialType)} did not throw when it should have."); } [Fact] [WorkItem(34984, "https://github.com/dotnet/roslyn/issues/34984")] public void ConversionIsExplicit_UnsetConversionKind() { var source = @"class C1 { } class C2 { public void M() { var c = new C1(); foreach (string item in c.Items) { } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var foreachSyntaxNode = root.DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var foreachSymbolInfo = model.GetForEachStatementInfo(foreachSyntaxNode); Assert.Equal(Conversion.UnsetConversion, foreachSymbolInfo.CurrentConversion); Assert.True(foreachSymbolInfo.CurrentConversion.Exists); Assert.False(foreachSymbolInfo.CurrentConversion.IsImplicit); } [Fact, WorkItem(29933, "https://github.com/dotnet/roslyn/issues/29933")] public void SpeculativelyBindBaseInXmlDoc() { var text = @" class C { /// <summary> </summary> static void M() { } } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = text.IndexOf(">", StringComparison.Ordinal); var syntax = SyntaxFactory.ParseExpression("base"); var info = model.GetSpeculativeSymbolInfo(position, syntax, SpeculativeBindingOption.BindAsExpression); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.NotReferencable, info.CandidateReason); } [Fact] [WorkItem(42840, "https://github.com/dotnet/roslyn/issues/42840")] public void DuplicateTypeArgument() { var source = @"class A<T> { } class B<T, U, U> where T : A<U> where U : class { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,15): error CS0692: Duplicate type parameter 'U' // class B<T, U, U> Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "U").WithArguments("U").WithLocation(4, 15), // (5,17): error CS0229: Ambiguity between 'U' and 'U' // where T : A<U> Diagnostic(ErrorCode.ERR_AmbigMember, "U").WithArguments("U", "U").WithLocation(5, 17)); comp = CreateCompilation(source); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var typeParameters = tree.GetRoot().DescendantNodes().OfType<TypeParameterSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(typeParameters[typeParameters.Length - 1]); Assert.False(symbol.IsReferenceType); symbol = model.GetDeclaredSymbol(typeParameters[typeParameters.Length - 2]); Assert.True(symbol.IsReferenceType); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Scripting/Core/Utilities/IListExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Scripting { internal static class IListExtensions { public static void AddRange<T>(this IList<T> list, ImmutableArray<T> items) { foreach (var item in items) { list.Add(item); } } public static void AddRange<T>(this IList<T> list, T[] items) { foreach (var item in items) { list.Add(item); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Scripting { internal static class IListExtensions { public static void AddRange<T>(this IList<T> list, ImmutableArray<T> items) { foreach (var item in items) { list.Add(item); } } public static void AddRange<T>(this IList<T> list, T[] items) { foreach (var item in items) { list.Add(item); } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Expressions/CastOperatorsKeywordRecommender.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions Friend Class CastOperatorsKeywordRecommender Inherits AbstractKeywordRecommender Friend Shared ReadOnly PredefinedKeywordList As SyntaxKind() = { SyntaxKind.CBoolKeyword, SyntaxKind.CByteKeyword, SyntaxKind.CCharKeyword, SyntaxKind.CDateKeyword, SyntaxKind.CDblKeyword, SyntaxKind.CDecKeyword, SyntaxKind.CIntKeyword, SyntaxKind.CLngKeyword, SyntaxKind.CObjKeyword, SyntaxKind.CSByteKeyword, SyntaxKind.CShortKeyword, SyntaxKind.CSngKeyword, SyntaxKind.CStrKeyword, SyntaxKind.CUIntKeyword, SyntaxKind.CULngKeyword, SyntaxKind.CUShortKeyword} Protected Overloads Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.IsAnyExpressionContext OrElse context.IsSingleLineStatementContext Then Dim recommendedKeywords As New List(Of RecommendedKeyword) For Each keyword In PredefinedKeywordList recommendedKeywords.Add(CreateRecommendedKeywordForIntrinsicOperator( keyword, String.Format(VBFeaturesResources._0_function, SyntaxFacts.GetText(keyword)), Glyph.MethodPublic, New PredefinedCastExpressionDocumentation(keyword, context.SemanticModel.Compilation), context.SemanticModel, context.Position)) Next recommendedKeywords.Add(CreateRecommendedKeywordForIntrinsicOperator( SyntaxKind.CTypeKeyword, VBFeaturesResources.CType_function, Glyph.MethodPublic, New CTypeCastExpressionDocumentation())) recommendedKeywords.Add(CreateRecommendedKeywordForIntrinsicOperator( SyntaxKind.DirectCastKeyword, VBFeaturesResources.DirectCast_function, Glyph.MethodPublic, New DirectCastExpressionDocumentation())) recommendedKeywords.Add(CreateRecommendedKeywordForIntrinsicOperator( SyntaxKind.TryCastKeyword, VBFeaturesResources.TryCast_function, Glyph.MethodPublic, New TryCastExpressionDocumentation())) Return recommendedKeywords.ToImmutableArray() End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions Friend Class CastOperatorsKeywordRecommender Inherits AbstractKeywordRecommender Friend Shared ReadOnly PredefinedKeywordList As SyntaxKind() = { SyntaxKind.CBoolKeyword, SyntaxKind.CByteKeyword, SyntaxKind.CCharKeyword, SyntaxKind.CDateKeyword, SyntaxKind.CDblKeyword, SyntaxKind.CDecKeyword, SyntaxKind.CIntKeyword, SyntaxKind.CLngKeyword, SyntaxKind.CObjKeyword, SyntaxKind.CSByteKeyword, SyntaxKind.CShortKeyword, SyntaxKind.CSngKeyword, SyntaxKind.CStrKeyword, SyntaxKind.CUIntKeyword, SyntaxKind.CULngKeyword, SyntaxKind.CUShortKeyword} Protected Overloads Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.IsAnyExpressionContext OrElse context.IsSingleLineStatementContext Then Dim recommendedKeywords As New List(Of RecommendedKeyword) For Each keyword In PredefinedKeywordList recommendedKeywords.Add(CreateRecommendedKeywordForIntrinsicOperator( keyword, String.Format(VBFeaturesResources._0_function, SyntaxFacts.GetText(keyword)), Glyph.MethodPublic, New PredefinedCastExpressionDocumentation(keyword, context.SemanticModel.Compilation), context.SemanticModel, context.Position)) Next recommendedKeywords.Add(CreateRecommendedKeywordForIntrinsicOperator( SyntaxKind.CTypeKeyword, VBFeaturesResources.CType_function, Glyph.MethodPublic, New CTypeCastExpressionDocumentation())) recommendedKeywords.Add(CreateRecommendedKeywordForIntrinsicOperator( SyntaxKind.DirectCastKeyword, VBFeaturesResources.DirectCast_function, Glyph.MethodPublic, New DirectCastExpressionDocumentation())) recommendedKeywords.Add(CreateRecommendedKeywordForIntrinsicOperator( SyntaxKind.TryCastKeyword, VBFeaturesResources.TryCast_function, Glyph.MethodPublic, New TryCastExpressionDocumentation())) Return recommendedKeywords.ToImmutableArray() End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Core/ModuleInitializer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; namespace Roslyn.Test.Utilities { internal static class ModuleInitializer { [ModuleInitializer] internal static void Initialize() { Trace.Listeners.Clear(); Trace.Listeners.Add(new ThrowingTraceListener()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; namespace Roslyn.Test.Utilities { internal static class ModuleInitializer { [ModuleInitializer] internal static void Initialize() { Trace.Listeners.Clear(); Trace.Listeners.Add(new ThrowingTraceListener()); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./eng/common/cross/s390x/sources.list.bionic
deb http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe deb http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe deb http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted deb http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse
deb http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe deb http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe deb http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted deb http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pl.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pl" original="../VSPackage.resx"> <body> <trans-unit id="101"> <source>Visual Basic</source> <target state="translated">Visual Basic</target> <note>Used anywhere the string is needed (that is, everywhere.)</note> </trans-unit> <trans-unit id="1012"> <source>Visual Basic Editor with Encoding</source> <target state="translated">Edytor Visual Basic z kodowaniem</target> <note /> </trans-unit> <trans-unit id="1013"> <source>Visual Basic Editor</source> <target state="translated">Edytor Visual Basic</target> <note /> </trans-unit> <trans-unit id="10160"> <source>Underline reassigned variables;Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme;Inheritance Margin;</source> <target state="needs-review-translation">Wyświetlaj wskazówki w tekście;Automatyczne wstawianie konstrukcji końcowych;Zmień ustawienia formatowania kodu;Zmień tryb konspektu;Automatyczne wstawianie składowych Interface i MustOverride;Pokaż lub ukryj separatory wierszy procedury;Włącz lub wyłącz sugestie dotyczące poprawy błędów;Włącz lub wyłącz wyróżnianie odwołań i słów kluczowych;Wyrażenie regularne;Koloruj wyrażenia regularne;Wyróżnij pokrewne składniki wskazane przez kursor;Zgłaszaj nieprawidłowe wyrażenia regularne;wyrażenie regularne;wyrażenie regularne;Użyj ulepszonych kolorów;Schemat kolorów edytora;</target> <note>Advanced options page keywords</note> </trans-unit> <trans-unit id="102"> <source>Advanced</source> <target state="translated">Zaawansowane</target> <note>"Advanced" node under Tools &gt;Options, Basic editor.</note> </trans-unit> <trans-unit id="103"> <source>Basic</source> <target state="translated">Podstawowe</target> <note>"Basic" node in profile Import/Export.</note> </trans-unit> <trans-unit id="104"> <source>Basic Editor</source> <target state="translated">Edytor podstawowy</target> <note>"Basic Editor" node in profile Import/Export.</note> </trans-unit> <trans-unit id="105"> <source>Options that control general editor features including Intellisense statement completion, line number display, and single-click URL navigation.</source> <target state="translated">Opcje obsługujące podstawowe funkcje edycji, takie jak uzupełnianie instrukcji za pomocą funkcji Intellisense, wyświetlanie numerów wierszy i nawigacja URL przy użyciu jednego kliknięcia.</target> <note>"Basic" node help text in profile Import/Export.</note> </trans-unit> <trans-unit id="106"> <source>Options that control Visual Basic editor features including automatic insertion of end constructs, procedure line separators, and automatic code formatting.</source> <target state="translated">Opcje obsługujące funkcje edycji w programie Visual Basic, takie jak wstawianie konstrukcji końcowych, separatory wierszy procedury i automatyczne formatowanie kodu.</target> <note>"Basic Editor" node help text in profile Import/Export.</note> </trans-unit> <trans-unit id="107"> <source>Optimizes the environment so you can focus on building world-class applications. This collection of settings contains customizations to the window layout, command menus and keyboard shortcuts to make common Visual Basic commands more accessible.</source> <target state="translated">Optymalizuje środowisko, dzięki czemu możesz się skupić na tworzeniu światowej klasy aplikacji. Ta kolekcja ustawień zawiera dostosowania układu okna, menu poleceń i skrótów klawiaturowych zapewniające łatwiejszy dostęp do często używanych poleceń języka Visual Basic.</target> <note>Profile description in profile Reset All Settings.</note> </trans-unit> <trans-unit id="108"> <source>Microsoft Visual Basic</source> <target state="translated">Microsoft Visual Basic</target> <note>Used for String in Tools &gt; Options, Text Editor, File Extensions</note> </trans-unit> <trans-unit id="109"> <source>Code Style</source> <target state="translated">Styl kodu</target> <note>"Code Style" category node under Tools &gt;Options, Basic editor.</note> </trans-unit> <trans-unit id="10161"> <source>Qualify with Me;Prefer intrinsic types;Style;Code Style</source> <target state="translated">Kwalifikuj w powiązaniu ze mną;Preferuj typy wewnętrzne;Styl;Styl kodu</target> <note>Code Style options page keywords</note> </trans-unit> <trans-unit id="110"> <source>Naming</source> <target state="translated">Nazewnictwo</target> <note>"Naming Style" node under Tools &gt;Options &gt; Basic editor &gt;Code Style.</note> </trans-unit> <trans-unit id="10162"> <source>Naming Style;Name Styles;Naming Rule;Naming Conventions</source> <target state="translated">Styl nazewnictwa;Style nazw;Reguła nazewnictwa;Konwencje nazewnictwa</target> <note>Naming Style options page keywords</note> </trans-unit> <trans-unit id="111"> <source>General</source> <target state="translated">Ogólne</target> <note>"General" node under Tools &gt;Options &gt;Basic editor &gt;Code Style.</note> </trans-unit> <trans-unit id="112"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="312"> <source>Change completion list settings;Pre-select most recently used member</source> <target state="translated">Zmień ustawienia listy uzupełniania;Wybierz wstępnie ostatnio używaną składową</target> <note>IntelliSense options page keywords</note> </trans-unit> <trans-unit id="114"> <source>Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.</source> <target state="translated">Składniki języka Visual Basic używane w środowisku IDE. Zależnie od typu projektu i jego ustawień może być używana inna wersja kompilatora.</target> <note>Help &gt; About</note> </trans-unit> <trans-unit id="113"> <source>Visual Basic Tools</source> <target state="translated">Narzędzia języka Visual Basic</target> <note>Help &gt; About</note> </trans-unit> <trans-unit id="An_empty_Visual_Basic_script_file"> <source>An empty Visual Basic script file.</source> <target state="translated">Pusty plik skryptu języka Visual Basic.</target> <note /> </trans-unit> <trans-unit id="Visual_Basic_Script"> <source>Visual Basic Script</source> <target state="translated">Skrypt języka Visual Basic</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pl" original="../VSPackage.resx"> <body> <trans-unit id="101"> <source>Visual Basic</source> <target state="translated">Visual Basic</target> <note>Used anywhere the string is needed (that is, everywhere.)</note> </trans-unit> <trans-unit id="1012"> <source>Visual Basic Editor with Encoding</source> <target state="translated">Edytor Visual Basic z kodowaniem</target> <note /> </trans-unit> <trans-unit id="1013"> <source>Visual Basic Editor</source> <target state="translated">Edytor Visual Basic</target> <note /> </trans-unit> <trans-unit id="10160"> <source>Underline reassigned variables;Display inline hints;Automatic insertion of end constructs;Change pretty listing settings;Change outlining mode;Automatic insertion of Interface and MustOverride members;Show or hide procedure line separators;Turn error correction suggestions on or off;Turn highlighting of references and keywords on or off;Regex;Colorize regular expressions;Highlight related components under cursor;Report invalid regular expressions;regex;regular expression;Use enhanced colors;Editor Color Scheme;Inheritance Margin;</source> <target state="needs-review-translation">Wyświetlaj wskazówki w tekście;Automatyczne wstawianie konstrukcji końcowych;Zmień ustawienia formatowania kodu;Zmień tryb konspektu;Automatyczne wstawianie składowych Interface i MustOverride;Pokaż lub ukryj separatory wierszy procedury;Włącz lub wyłącz sugestie dotyczące poprawy błędów;Włącz lub wyłącz wyróżnianie odwołań i słów kluczowych;Wyrażenie regularne;Koloruj wyrażenia regularne;Wyróżnij pokrewne składniki wskazane przez kursor;Zgłaszaj nieprawidłowe wyrażenia regularne;wyrażenie regularne;wyrażenie regularne;Użyj ulepszonych kolorów;Schemat kolorów edytora;</target> <note>Advanced options page keywords</note> </trans-unit> <trans-unit id="102"> <source>Advanced</source> <target state="translated">Zaawansowane</target> <note>"Advanced" node under Tools &gt;Options, Basic editor.</note> </trans-unit> <trans-unit id="103"> <source>Basic</source> <target state="translated">Podstawowe</target> <note>"Basic" node in profile Import/Export.</note> </trans-unit> <trans-unit id="104"> <source>Basic Editor</source> <target state="translated">Edytor podstawowy</target> <note>"Basic Editor" node in profile Import/Export.</note> </trans-unit> <trans-unit id="105"> <source>Options that control general editor features including Intellisense statement completion, line number display, and single-click URL navigation.</source> <target state="translated">Opcje obsługujące podstawowe funkcje edycji, takie jak uzupełnianie instrukcji za pomocą funkcji Intellisense, wyświetlanie numerów wierszy i nawigacja URL przy użyciu jednego kliknięcia.</target> <note>"Basic" node help text in profile Import/Export.</note> </trans-unit> <trans-unit id="106"> <source>Options that control Visual Basic editor features including automatic insertion of end constructs, procedure line separators, and automatic code formatting.</source> <target state="translated">Opcje obsługujące funkcje edycji w programie Visual Basic, takie jak wstawianie konstrukcji końcowych, separatory wierszy procedury i automatyczne formatowanie kodu.</target> <note>"Basic Editor" node help text in profile Import/Export.</note> </trans-unit> <trans-unit id="107"> <source>Optimizes the environment so you can focus on building world-class applications. This collection of settings contains customizations to the window layout, command menus and keyboard shortcuts to make common Visual Basic commands more accessible.</source> <target state="translated">Optymalizuje środowisko, dzięki czemu możesz się skupić na tworzeniu światowej klasy aplikacji. Ta kolekcja ustawień zawiera dostosowania układu okna, menu poleceń i skrótów klawiaturowych zapewniające łatwiejszy dostęp do często używanych poleceń języka Visual Basic.</target> <note>Profile description in profile Reset All Settings.</note> </trans-unit> <trans-unit id="108"> <source>Microsoft Visual Basic</source> <target state="translated">Microsoft Visual Basic</target> <note>Used for String in Tools &gt; Options, Text Editor, File Extensions</note> </trans-unit> <trans-unit id="109"> <source>Code Style</source> <target state="translated">Styl kodu</target> <note>"Code Style" category node under Tools &gt;Options, Basic editor.</note> </trans-unit> <trans-unit id="10161"> <source>Qualify with Me;Prefer intrinsic types;Style;Code Style</source> <target state="translated">Kwalifikuj w powiązaniu ze mną;Preferuj typy wewnętrzne;Styl;Styl kodu</target> <note>Code Style options page keywords</note> </trans-unit> <trans-unit id="110"> <source>Naming</source> <target state="translated">Nazewnictwo</target> <note>"Naming Style" node under Tools &gt;Options &gt; Basic editor &gt;Code Style.</note> </trans-unit> <trans-unit id="10162"> <source>Naming Style;Name Styles;Naming Rule;Naming Conventions</source> <target state="translated">Styl nazewnictwa;Style nazw;Reguła nazewnictwa;Konwencje nazewnictwa</target> <note>Naming Style options page keywords</note> </trans-unit> <trans-unit id="111"> <source>General</source> <target state="translated">Ogólne</target> <note>"General" node under Tools &gt;Options &gt;Basic editor &gt;Code Style.</note> </trans-unit> <trans-unit id="112"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="312"> <source>Change completion list settings;Pre-select most recently used member</source> <target state="translated">Zmień ustawienia listy uzupełniania;Wybierz wstępnie ostatnio używaną składową</target> <note>IntelliSense options page keywords</note> </trans-unit> <trans-unit id="114"> <source>Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.</source> <target state="translated">Składniki języka Visual Basic używane w środowisku IDE. Zależnie od typu projektu i jego ustawień może być używana inna wersja kompilatora.</target> <note>Help &gt; About</note> </trans-unit> <trans-unit id="113"> <source>Visual Basic Tools</source> <target state="translated">Narzędzia języka Visual Basic</target> <note>Help &gt; About</note> </trans-unit> <trans-unit id="An_empty_Visual_Basic_script_file"> <source>An empty Visual Basic script file.</source> <target state="translated">Pusty plik skryptu języka Visual Basic.</target> <note /> </trans-unit> <trans-unit id="Visual_Basic_Script"> <source>Visual Basic Script</source> <target state="translated">Skrypt języka Visual Basic</target> <note /> </trans-unit> </body> </file> </xliff>
-1