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<<\{2LnN&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 ( MO0HݐBKwAH!T~I$ݿ'TG~<!4;#wqu*&rFqvGJy(v*K#FD.W =ZMYbBS7ϛז
?9Lҙsbgٮ|l!USh9ibr:"y_dlD|-NR"42G%Z4˝y7 ëɂ PK ! ?w
U 1 xl/workbook.xmlUo:~O *_کڲ%RS fiRM1iC},WZ*ÈWLOa
RZȊ'k?wR T:1u캚弤DּK&UI
սkisMYEnIE;X!L0>)ye:jE{WRnjɲ;QbThxN`zU)Zfݎ+r?=+UNJhj%-si&
~IѺLKj3Oi0~0z҈ x=J!P?ﰖ7;c6Ymbh0\UsjŞP
t1+jrԨ"xMCXVJb[jѫgҥK;z0 K2
>@@鮢!'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=(̺wZ#/\8|<r|y{hs(>-n۟ PK ! Ja G xl/_rels/workbook.xml.rels ( j0ѽqP:{)0Mlc?y6У$41f9#u)(ڛε
^OW 3H./6kNOd@"8R`ÃT[4e>KAsc+EY5iQw~om4]~ɉ-i^Yy\YD>qW$KS3b2kT>:3[/%s*}+4?rV PK ! &皲 M xl/worksheets/sheet1.xmlYے6}OU $xR}V*38\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>xEMQEDKC b^[Cņ
;y<.wsyFT{Dqpy^LwH4`t0!NPpcT)ܩCSgLFsH s59F挥! w̉sҩk
SͧC!FDC87x ]^Zwjz1#se:8TkO]3ISpǧv[XrF`_qGF8L^H4)/G,K:;<
{Q0kQ
S!J2 5<kUYX4176b Sk8T{0Ɖ@8T{ᰀx͑wP gJ
XJª=+j͘@~
ZpHOLp{ q| 9gC^{OPu z|y8TD@=g|6ơYKC2|Mߪު]Զx<Kqf/AulV+ yH䟋0X^iQ5Kc7PŇw߁}\4(
֭)Dl|j@!(/m;Aʠ 8Y HC|~3U{sG7=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 ! u xl/worksheets/sheet2.xmlY[6~x6v,<z}f E'i1$`
gyM*+{uCRlLNULJm/VwV_4@8Ts߯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|ey1A(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(ҷҷCkm 7vK+`r*8P>kcT *C~FWBem 'j,֞( Q<A89<N\@xr]zLlbtyqȻaH'*'Ha3F G#zK>@=EvƘCc !%v1%ciɵu< |