repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.UIntTC.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct UIntTC : INumericTC<uint> { uint INumericTC<uint>.MinValue => uint.MinValue; uint INumericTC<uint>.MaxValue => uint.MaxValue; uint INumericTC<uint>.Zero => 0; public bool Related(BinaryOperatorKind relation, uint left, uint right) { switch (relation) { case Equal: return left == right; case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } uint INumericTC<uint>.Next(uint value) { Debug.Assert(value != uint.MaxValue); return value + 1; } public uint FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (uint)0 : constantValue.UInt32Value; public ConstantValue ToConstantValue(uint value) => ConstantValue.Create(value); string INumericTC<uint>.ToString(uint value) => value.ToString(); uint INumericTC<uint>.Prev(uint value) { Debug.Assert(value != uint.MinValue); return value - 1; } public uint Random(Random random) { return (uint)((random.Next() << 10) ^ random.Next()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct UIntTC : INumericTC<uint> { uint INumericTC<uint>.MinValue => uint.MinValue; uint INumericTC<uint>.MaxValue => uint.MaxValue; uint INumericTC<uint>.Zero => 0; public bool Related(BinaryOperatorKind relation, uint left, uint right) { switch (relation) { case Equal: return left == right; case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } uint INumericTC<uint>.Next(uint value) { Debug.Assert(value != uint.MaxValue); return value + 1; } public uint FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (uint)0 : constantValue.UInt32Value; public ConstantValue ToConstantValue(uint value) => ConstantValue.Create(value); string INumericTC<uint>.ToString(uint value) => value.ToString(); uint INumericTC<uint>.Prev(uint value) { Debug.Assert(value != uint.MinValue); return value - 1; } public uint Random(Random random) { return (uint)((random.Next() << 10) ^ random.Next()); } } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Features/Core/Portable/EditAndContinue/SourceFileSpan.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a span of text in a source code file in terms of file name, line number, and offset within line. /// An alternative for <see cref="FileLinePositionSpan"/> without <see cref="FileLinePositionSpan.HasMappedPath"/> bit. /// </summary> [DataContract] internal readonly struct SourceFileSpan : IEquatable<SourceFileSpan> { /// <summary> /// Path, or null if the span represents an invalid value. /// </summary> /// <remarks> /// Path may be <see cref="string.Empty"/> if not available. /// </remarks> [DataMember(Order = 0)] public string Path { get; } /// <summary> /// Gets the span. /// </summary> [DataMember(Order = 1)] public LinePositionSpan Span { get; } /// <summary> /// Initializes the <see cref="SourceFileSpan"/> instance. /// </summary> /// <param name="path">The file identifier - typically a relative or absolute path.</param> /// <param name="span">The span.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> public SourceFileSpan(string path, LinePositionSpan span) { Path = path ?? throw new ArgumentNullException(nameof(path)); Span = span; } public SourceFileSpan WithSpan(LinePositionSpan span) => new(Path, span); public SourceFileSpan WithPath(string path) => new(path, Span); /// <summary> /// Returns true if the span represents a valid location. /// </summary> public bool IsValid => Path != null; // invalid span can be constructed by new FileLinePositionSpan() /// <summary> /// Gets the <see cref="LinePosition"/> of the start of the span. /// </summary> public LinePosition Start => Span.Start; /// <summary> /// Gets the <see cref="LinePosition"/> of the end of the span. /// </summary> public LinePosition End => Span.End; public bool Equals(SourceFileSpan other) => Span.Equals(other.Span) && string.Equals(Path, other.Path, StringComparison.Ordinal); public override bool Equals(object? other) => other is SourceFileSpan span && Equals(span); public override int GetHashCode() => Hash.Combine(Path, Span.GetHashCode()); public override string ToString() => string.IsNullOrEmpty(Path) ? Span.ToString() : $"{Path}: {Span}"; public static implicit operator SourceFileSpan(FileLinePositionSpan span) => new(span.Path, span.Span); public static bool operator ==(SourceFileSpan left, SourceFileSpan right) => left.Equals(right); public static bool operator !=(SourceFileSpan left, SourceFileSpan right) => !(left == right); public bool Contains(SourceFileSpan span) => Span.Contains(span.Span) && string.Equals(Path, span.Path, StringComparison.Ordinal); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a span of text in a source code file in terms of file name, line number, and offset within line. /// An alternative for <see cref="FileLinePositionSpan"/> without <see cref="FileLinePositionSpan.HasMappedPath"/> bit. /// </summary> [DataContract] internal readonly struct SourceFileSpan : IEquatable<SourceFileSpan> { /// <summary> /// Path, or null if the span represents an invalid value. /// </summary> /// <remarks> /// Path may be <see cref="string.Empty"/> if not available. /// </remarks> [DataMember(Order = 0)] public string Path { get; } /// <summary> /// Gets the span. /// </summary> [DataMember(Order = 1)] public LinePositionSpan Span { get; } /// <summary> /// Initializes the <see cref="SourceFileSpan"/> instance. /// </summary> /// <param name="path">The file identifier - typically a relative or absolute path.</param> /// <param name="span">The span.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> public SourceFileSpan(string path, LinePositionSpan span) { Path = path ?? throw new ArgumentNullException(nameof(path)); Span = span; } public SourceFileSpan WithSpan(LinePositionSpan span) => new(Path, span); public SourceFileSpan WithPath(string path) => new(path, Span); /// <summary> /// Returns true if the span represents a valid location. /// </summary> public bool IsValid => Path != null; // invalid span can be constructed by new FileLinePositionSpan() /// <summary> /// Gets the <see cref="LinePosition"/> of the start of the span. /// </summary> public LinePosition Start => Span.Start; /// <summary> /// Gets the <see cref="LinePosition"/> of the end of the span. /// </summary> public LinePosition End => Span.End; public bool Equals(SourceFileSpan other) => Span.Equals(other.Span) && string.Equals(Path, other.Path, StringComparison.Ordinal); public override bool Equals(object? other) => other is SourceFileSpan span && Equals(span); public override int GetHashCode() => Hash.Combine(Path, Span.GetHashCode()); public override string ToString() => string.IsNullOrEmpty(Path) ? Span.ToString() : $"{Path}: {Span}"; public static implicit operator SourceFileSpan(FileLinePositionSpan span) => new(span.Path, span.Span); public static bool operator ==(SourceFileSpan left, SourceFileSpan right) => left.Equals(right); public static bool operator !=(SourceFileSpan left, SourceFileSpan right) => !(left == right); public bool Contains(SourceFileSpan span) => Span.Contains(span.Span) && string.Equals(Path, span.Path, StringComparison.Ordinal); } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/CSharp/Portable/Binder/BlockBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class BlockBinder : LocalScopeBinder { private readonly BlockSyntax _block; public BlockBinder(Binder enclosing, BlockSyntax block) : this(enclosing, block, enclosing.Flags) { } public BlockBinder(Binder enclosing, BlockSyntax block, BinderFlags additionalFlags) : base(enclosing, enclosing.Flags | additionalFlags) { Debug.Assert(block != null); _block = block; } protected override ImmutableArray<LocalSymbol> BuildLocals() { return BuildLocals(_block.Statements, this); } protected override ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { return BuildLocalFunctions(_block.Statements); } internal override bool IsLocalFunctionsScopeBinder { get { return true; } } protected override ImmutableArray<LabelSymbol> BuildLabels() { ArrayBuilder<LabelSymbol> labels = null; base.BuildLabels(_block.Statements, ref labels); return (labels != null) ? labels.ToImmutableAndFree() : ImmutableArray<LabelSymbol>.Empty; } internal override bool IsLabelsScopeBinder { get { return true; } } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (ScopeDesignator == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return _block; } } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { if (ScopeDesignator == scopeDesignator) { return this.LocalFunctions; } 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; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class BlockBinder : LocalScopeBinder { private readonly BlockSyntax _block; public BlockBinder(Binder enclosing, BlockSyntax block) : this(enclosing, block, enclosing.Flags) { } public BlockBinder(Binder enclosing, BlockSyntax block, BinderFlags additionalFlags) : base(enclosing, enclosing.Flags | additionalFlags) { Debug.Assert(block != null); _block = block; } protected override ImmutableArray<LocalSymbol> BuildLocals() { return BuildLocals(_block.Statements, this); } protected override ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { return BuildLocalFunctions(_block.Statements); } internal override bool IsLocalFunctionsScopeBinder { get { return true; } } protected override ImmutableArray<LabelSymbol> BuildLabels() { ArrayBuilder<LabelSymbol> labels = null; base.BuildLabels(_block.Statements, ref labels); return (labels != null) ? labels.ToImmutableAndFree() : ImmutableArray<LabelSymbol>.Empty; } internal override bool IsLabelsScopeBinder { get { return true; } } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (ScopeDesignator == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return _block; } } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { if (ScopeDesignator == scopeDesignator) { return this.LocalFunctions; } throw ExceptionUtilities.Unreachable; } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/VisualStudio/Core/Test/Snippets/CSharpSnippetCommandHandlerTests.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 Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Snippets <UseExportProvider> Public Class CSharpSnippetCommandHandlerTests <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfWord_NoActiveSession_ExpansionInserted() Dim markup = "public class$$ Goo" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal(New Span(7, 5), testState.SnippetExpansionClient.InsertExpansionSpan) Assert.Equal("public class Goo", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfPreprocessor_NoActiveSession_ExpansionInserted() Dim markup = "#if$$" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal(New Span(0, 3), testState.SnippetExpansionClient.InsertExpansionSpan) Assert.Equal("#if", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfWord_NoActiveSession_ExpansionNotInsertedCausesInsertedTab() Dim markup = "class$$" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SnippetExpansionClient.TryInsertExpansionReturnValue = False testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("class ", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfWord_ActiveSession() Dim markup = "class$$" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp, startActiveSession:=True) Using testState testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryHandleTabCalled) Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("class", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInMiddleOfWordCreatesSession() Dim markup = "cla$$ss" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("cla ss", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInWhiteSpaceDoesNotCreateSession() Dim markup = "class $$ Goo" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("class Goo", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabWithSelectionDoesNotCreateSession() Dim markup = <Markup><![CDATA[class SomeClass { {|Selection:if if$$|} }]]></Markup>.Value Dim expectedResults = <Markup><![CDATA[class SomeClass { }]]></Markup>.Value.Replace(vbLf, vbCrLf) Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal(expectedResults, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_BackTab_ActiveSession() Dim markup = " $$class Goo {}" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp, startActiveSession:=True) Using testState testState.SendBackTab() Assert.True(testState.SnippetExpansionClient.TryHandleBackTabCalled) Assert.Equal(" class Goo {}", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_BackTab_NoActiveSession() Dim markup = " $$class Goo {}" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SendBackTab() Assert.Equal("class Goo {}", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Return_ActiveSession() Dim markup = "$$ class Goo {}" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp, startActiveSession:=True) Using testState testState.SendReturn() Assert.Equal(" class Goo {}", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Return_NoActiveSession() Dim markup = "$$ class Goo {}" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SendReturn() Assert.Equal(Environment.NewLine & " class Goo {}", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Escape_ActiveSession() Dim markup = "$$ class Goo {}" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp, startActiveSession:=True) Using testState testState.SendEscape() Assert.True(testState.SnippetExpansionClient.TryHandleEscapeCalled) Assert.Equal(" class Goo {}", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Escape_NoActiveSession() Dim markup = "$$ class Goo {}" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SendEscape() Assert.Equal("EscapePassedThrough! class Goo {}", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInsideComment_NoExpansionInserted() Dim markup = <Markup><![CDATA[class C { void M() { // class$$ } } ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInsideString_NoExpansionInserted() Dim markup = <Markup><![CDATA[class C { void M() { var x = "What if$$ this fails?"; } } ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets), Trait(Traits.Feature, Traits.Features.Interactive)> Public Sub SnippetCommandHandler_Interactive_Tab() Dim markup = "for$$" Dim testState = SnippetTestState.CreateSubmissionTestState(markup, LanguageNames.CSharp) Using testState testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("for ", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets), Trait(Traits.Feature, Traits.Features.Interactive)> Public Sub SnippetCommandHandler_Interactive_InsertSnippetCommand() Dim markup = "for$$" Dim testState = SnippetTestState.CreateSubmissionTestState(markup, LanguageNames.CSharp) Using testState Dim handler = testState.SnippetCommandHandler Dim state = handler.GetCommandState(New InsertSnippetCommandArgs(testState.TextView, testState.SubjectBuffer)) Assert.True(state.IsUnspecified) testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True Assert.False(testState.SendInsertSnippetCommand(AddressOf handler.ExecuteCommand)) Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("for", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets), Trait(Traits.Feature, Traits.Features.Interactive)> Public Sub SnippetCommandHandler_Interactive_SurroundWithCommand() Dim markup = "for$$" Dim testState = SnippetTestState.CreateSubmissionTestState(markup, LanguageNames.CSharp) Using testState Dim handler = CType(testState.SnippetCommandHandler, CSharp.Snippets.SnippetCommandHandler) Dim state = handler.GetCommandState(New SurroundWithCommandArgs(testState.TextView, testState.SubjectBuffer)) Assert.True(state.IsUnspecified) testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True Assert.False(testState.SendSurroundWithCommand(AddressOf handler.ExecuteCommand)) Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("for", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Snippets <UseExportProvider> Public Class CSharpSnippetCommandHandlerTests <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfWord_NoActiveSession_ExpansionInserted() Dim markup = "public class$$ Goo" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal(New Span(7, 5), testState.SnippetExpansionClient.InsertExpansionSpan) Assert.Equal("public class Goo", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfPreprocessor_NoActiveSession_ExpansionInserted() Dim markup = "#if$$" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal(New Span(0, 3), testState.SnippetExpansionClient.InsertExpansionSpan) Assert.Equal("#if", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfWord_NoActiveSession_ExpansionNotInsertedCausesInsertedTab() Dim markup = "class$$" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SnippetExpansionClient.TryInsertExpansionReturnValue = False testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("class ", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfWord_ActiveSession() Dim markup = "class$$" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp, startActiveSession:=True) Using testState testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryHandleTabCalled) Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("class", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInMiddleOfWordCreatesSession() Dim markup = "cla$$ss" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("cla ss", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInWhiteSpaceDoesNotCreateSession() Dim markup = "class $$ Goo" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("class Goo", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabWithSelectionDoesNotCreateSession() Dim markup = <Markup><![CDATA[class SomeClass { {|Selection:if if$$|} }]]></Markup>.Value Dim expectedResults = <Markup><![CDATA[class SomeClass { }]]></Markup>.Value.Replace(vbLf, vbCrLf) Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal(expectedResults, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_BackTab_ActiveSession() Dim markup = " $$class Goo {}" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp, startActiveSession:=True) Using testState testState.SendBackTab() Assert.True(testState.SnippetExpansionClient.TryHandleBackTabCalled) Assert.Equal(" class Goo {}", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_BackTab_NoActiveSession() Dim markup = " $$class Goo {}" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SendBackTab() Assert.Equal("class Goo {}", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Return_ActiveSession() Dim markup = "$$ class Goo {}" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp, startActiveSession:=True) Using testState testState.SendReturn() Assert.Equal(" class Goo {}", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Return_NoActiveSession() Dim markup = "$$ class Goo {}" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SendReturn() Assert.Equal(Environment.NewLine & " class Goo {}", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Escape_ActiveSession() Dim markup = "$$ class Goo {}" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp, startActiveSession:=True) Using testState testState.SendEscape() Assert.True(testState.SnippetExpansionClient.TryHandleEscapeCalled) Assert.Equal(" class Goo {}", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Escape_NoActiveSession() Dim markup = "$$ class Goo {}" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SendEscape() Assert.Equal("EscapePassedThrough! class Goo {}", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInsideComment_NoExpansionInserted() Dim markup = <Markup><![CDATA[class C { void M() { // class$$ } } ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInsideString_NoExpansionInserted() Dim markup = <Markup><![CDATA[class C { void M() { var x = "What if$$ this fails?"; } } ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.CSharp) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets), Trait(Traits.Feature, Traits.Features.Interactive)> Public Sub SnippetCommandHandler_Interactive_Tab() Dim markup = "for$$" Dim testState = SnippetTestState.CreateSubmissionTestState(markup, LanguageNames.CSharp) Using testState testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("for ", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets), Trait(Traits.Feature, Traits.Features.Interactive)> Public Sub SnippetCommandHandler_Interactive_InsertSnippetCommand() Dim markup = "for$$" Dim testState = SnippetTestState.CreateSubmissionTestState(markup, LanguageNames.CSharp) Using testState Dim handler = testState.SnippetCommandHandler Dim state = handler.GetCommandState(New InsertSnippetCommandArgs(testState.TextView, testState.SubjectBuffer)) Assert.True(state.IsUnspecified) testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True Assert.False(testState.SendInsertSnippetCommand(AddressOf handler.ExecuteCommand)) Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("for", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets), Trait(Traits.Feature, Traits.Features.Interactive)> Public Sub SnippetCommandHandler_Interactive_SurroundWithCommand() Dim markup = "for$$" Dim testState = SnippetTestState.CreateSubmissionTestState(markup, LanguageNames.CSharp) Using testState Dim handler = CType(testState.SnippetCommandHandler, CSharp.Snippets.SnippetCommandHandler) Dim state = handler.GetCommandState(New SurroundWithCommandArgs(testState.TextView, testState.SubjectBuffer)) Assert.True(state.IsUnspecified) testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True Assert.False(testState.SendSurroundWithCommand(AddressOf handler.ExecuteCommand)) Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("for", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IsPatternOperator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { bool negated = node.IsNegated; BoundExpression result; if (canProduceLinearSequence(node.DecisionDag.RootNode, whenTrueLabel: node.WhenTrueLabel, whenFalseLabel: node.WhenFalseLabel)) { // If we can build a linear test sequence `(e1 && e2 && e3)` for the dag, do so. var isPatternRewriter = new IsPatternExpressionLinearLocalRewriter(node, this); result = isPatternRewriter.LowerIsPatternAsLinearTestSequence(node, whenTrueLabel: node.WhenTrueLabel, whenFalseLabel: node.WhenFalseLabel); isPatternRewriter.Free(); } else if (canProduceLinearSequence(node.DecisionDag.RootNode, whenTrueLabel: node.WhenFalseLabel, whenFalseLabel: node.WhenTrueLabel)) { // If we can build a linear test sequence with the whenTrue and whenFalse labels swapped, then negate the // result. This would typically arise when the source contains `e is not pattern`. negated = !negated; var isPatternRewriter = new IsPatternExpressionLinearLocalRewriter(node, this); result = isPatternRewriter.LowerIsPatternAsLinearTestSequence(node, whenTrueLabel: node.WhenFalseLabel, whenFalseLabel: node.WhenTrueLabel); isPatternRewriter.Free(); } else { // We need to lower a generalized dag, so we produce a label for the true and false branches and assign to a temporary containing the result. var isPatternRewriter = new IsPatternExpressionGeneralLocalRewriter(node.Syntax, this); result = isPatternRewriter.LowerGeneralIsPattern(node); isPatternRewriter.Free(); } if (negated) { result = this._factory.Not(result); } return result; // Can the given decision dag node, and its successors, be generated as a sequence of // linear tests with a single "golden" path to the true label and all other paths leading // to the false label? This occurs with an is-pattern expression that uses no "or" or "not" // pattern forms. static bool canProduceLinearSequence( BoundDecisionDagNode node, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) { while (true) { switch (node) { case BoundWhenDecisionDagNode w: Debug.Assert(w.WhenFalse is null); node = w.WhenTrue; break; case BoundLeafDecisionDagNode n: return n.Label == whenTrueLabel; case BoundEvaluationDecisionDagNode e: node = e.Next; break; case BoundTestDecisionDagNode t: bool falseFail = IsFailureNode(t.WhenFalse, whenFalseLabel); if (falseFail == IsFailureNode(t.WhenTrue, whenFalseLabel)) return false; node = falseFail ? t.WhenTrue : t.WhenFalse; break; default: throw ExceptionUtilities.UnexpectedValue(node); } } } } /// <summary> /// A local rewriter for lowering an is-pattern expression. This handles the general case by lowering /// the decision dag, and returning a "true" or "false" value as the result at the end. /// </summary> private sealed class IsPatternExpressionGeneralLocalRewriter : DecisionDagRewriter { private readonly ArrayBuilder<BoundStatement> _statements = ArrayBuilder<BoundStatement>.GetInstance(); public IsPatternExpressionGeneralLocalRewriter( SyntaxNode node, LocalRewriter localRewriter) : base(node, localRewriter, generateInstrumentation: false) { } protected override ArrayBuilder<BoundStatement> BuilderForSection(SyntaxNode section) => _statements; public new void Free() { base.Free(); _statements.Free(); } internal BoundExpression LowerGeneralIsPattern(BoundIsPatternExpression node) { _factory.Syntax = node.Syntax; var resultBuilder = ArrayBuilder<BoundStatement>.GetInstance(); var inputExpression = _localRewriter.VisitExpression(node.Expression); BoundDecisionDag decisionDag = ShareTempsIfPossibleAndEvaluateInput( node.DecisionDag, inputExpression, resultBuilder, out _); // lower the decision dag. ImmutableArray<BoundStatement> loweredDag = LowerDecisionDagCore(decisionDag); resultBuilder.Add(_factory.Block(loweredDag)); Debug.Assert(node.Type is { SpecialType: SpecialType.System_Boolean }); LocalSymbol resultTemp = _factory.SynthesizedLocal(node.Type, node.Syntax, kind: SynthesizedLocalKind.LoweringTemp); LabelSymbol afterIsPatternExpression = _factory.GenerateLabel("afterIsPatternExpression"); LabelSymbol trueLabel = node.WhenTrueLabel; LabelSymbol falseLabel = node.WhenFalseLabel; if (_statements.Count != 0) resultBuilder.Add(_factory.Block(_statements.ToArray())); resultBuilder.Add(_factory.Label(trueLabel)); resultBuilder.Add(_factory.Assignment(_factory.Local(resultTemp), _factory.Literal(true))); resultBuilder.Add(_factory.Goto(afterIsPatternExpression)); resultBuilder.Add(_factory.Label(falseLabel)); resultBuilder.Add(_factory.Assignment(_factory.Local(resultTemp), _factory.Literal(false))); resultBuilder.Add(_factory.Label(afterIsPatternExpression)); _localRewriter._needsSpilling = true; return _factory.SpillSequence(_tempAllocator.AllTemps().Add(resultTemp), resultBuilder.ToImmutableAndFree(), _factory.Local(resultTemp)); } } private static bool IsFailureNode(BoundDecisionDagNode node, LabelSymbol whenFalseLabel) { if (node is BoundWhenDecisionDagNode w) node = w.WhenTrue; return node is BoundLeafDecisionDagNode l && l.Label == whenFalseLabel; } private sealed class IsPatternExpressionLinearLocalRewriter : PatternLocalRewriter { /// <summary> /// Accumulates side-effects that come before the next conjunct. /// </summary> private readonly ArrayBuilder<BoundExpression> _sideEffectBuilder; /// <summary> /// Accumulates conjuncts (conditions that must all be true) for the translation. When a conjunct is added, /// elements of the _sideEffectBuilder, if any, should be added as part of a sequence expression for /// the conjunct being added. /// </summary> private readonly ArrayBuilder<BoundExpression> _conjunctBuilder; public IsPatternExpressionLinearLocalRewriter(BoundIsPatternExpression node, LocalRewriter localRewriter) : base(node.Syntax, localRewriter, generateInstrumentation: false) { _conjunctBuilder = ArrayBuilder<BoundExpression>.GetInstance(); _sideEffectBuilder = ArrayBuilder<BoundExpression>.GetInstance(); } public new void Free() { _conjunctBuilder.Free(); _sideEffectBuilder.Free(); base.Free(); } private void AddConjunct(BoundExpression test) { // When in error recovery, the generated code doesn't matter. if (test.Type?.IsErrorType() != false) return; Debug.Assert(test.Type.SpecialType == SpecialType.System_Boolean); if (_sideEffectBuilder.Count != 0) { test = _factory.Sequence(ImmutableArray<LocalSymbol>.Empty, _sideEffectBuilder.ToImmutable(), test); _sideEffectBuilder.Clear(); } _conjunctBuilder.Add(test); } /// <summary> /// Translate the single test into _sideEffectBuilder and _conjunctBuilder. /// </summary> private void LowerOneTest(BoundDagTest test, bool invert = false) { _factory.Syntax = test.Syntax; switch (test) { case BoundDagEvaluation eval: { var sideEffect = LowerEvaluation(eval); _sideEffectBuilder.Add(sideEffect); return; } case var _: { var testExpression = LowerTest(test); if (testExpression != null) { if (invert) testExpression = _factory.Not(testExpression); AddConjunct(testExpression); } return; } } } public BoundExpression LowerIsPatternAsLinearTestSequence( BoundIsPatternExpression isPatternExpression, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) { BoundDecisionDag decisionDag = isPatternExpression.DecisionDag; BoundExpression loweredInput = _localRewriter.VisitExpression(isPatternExpression.Expression); // The optimization of sharing pattern-matching temps with user variables can always apply to // an is-pattern expression because there is no when clause that could possibly intervene during // the execution of the pattern-matching automaton and change one of those variables. decisionDag = ShareTempsAndEvaluateInput(loweredInput, decisionDag, expr => _sideEffectBuilder.Add(expr), out _); var node = decisionDag.RootNode; return ProduceLinearTestSequence(node, whenTrueLabel, whenFalseLabel); } /// <summary> /// Translate an is-pattern expression into a sequence of tests separated by the control-flow-and operator. /// </summary> private BoundExpression ProduceLinearTestSequence( BoundDecisionDagNode node, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) { // We follow the "good" path in the decision dag. We depend on it being nicely linear in structure. // If we add "or" patterns that assumption breaks down. while (node.Kind != BoundKind.LeafDecisionDagNode && node.Kind != BoundKind.WhenDecisionDagNode) { switch (node) { case BoundEvaluationDecisionDagNode evalNode: { LowerOneTest(evalNode.Evaluation); node = evalNode.Next; } break; case BoundTestDecisionDagNode testNode: { if (testNode.WhenTrue is BoundEvaluationDecisionDagNode e && TryLowerTypeTestAndCast(testNode.Test, e.Evaluation, out BoundExpression? sideEffect, out BoundExpression? testExpression)) { _sideEffectBuilder.Add(sideEffect); AddConjunct(testExpression); node = e.Next; } else { bool invertTest = IsFailureNode(testNode.WhenTrue, whenFalseLabel); LowerOneTest(testNode.Test, invertTest); node = invertTest ? testNode.WhenFalse : testNode.WhenTrue; } } break; } } // When we get to "the end", it is a success node. switch (node) { case BoundLeafDecisionDagNode leafNode: Debug.Assert(leafNode.Label == whenTrueLabel); break; case BoundWhenDecisionDagNode whenNode: { Debug.Assert(whenNode.WhenExpression == null); Debug.Assert(whenNode.WhenTrue is BoundLeafDecisionDagNode d && d.Label == whenTrueLabel); foreach (BoundPatternBinding binding in whenNode.Bindings) { BoundExpression left = _localRewriter.VisitExpression(binding.VariableAccess); BoundExpression right = _tempAllocator.GetTemp(binding.TempContainingValue); if (left != right) { _sideEffectBuilder.Add(_factory.AssignmentExpression(left, right)); } } } break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } if (_sideEffectBuilder.Count > 0 || _conjunctBuilder.Count == 0) { AddConjunct(_factory.Literal(true)); } Debug.Assert(_sideEffectBuilder.Count == 0); BoundExpression? result = null; foreach (BoundExpression conjunct in _conjunctBuilder) { result = (result == null) ? conjunct : _factory.LogicalAnd(result, conjunct); } _conjunctBuilder.Clear(); Debug.Assert(result != null); var allTemps = _tempAllocator.AllTemps(); if (allTemps.Length > 0) { result = _factory.Sequence(allTemps, ImmutableArray<BoundExpression>.Empty, result); } return result; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { bool negated = node.IsNegated; BoundExpression result; if (canProduceLinearSequence(node.DecisionDag.RootNode, whenTrueLabel: node.WhenTrueLabel, whenFalseLabel: node.WhenFalseLabel)) { // If we can build a linear test sequence `(e1 && e2 && e3)` for the dag, do so. var isPatternRewriter = new IsPatternExpressionLinearLocalRewriter(node, this); result = isPatternRewriter.LowerIsPatternAsLinearTestSequence(node, whenTrueLabel: node.WhenTrueLabel, whenFalseLabel: node.WhenFalseLabel); isPatternRewriter.Free(); } else if (canProduceLinearSequence(node.DecisionDag.RootNode, whenTrueLabel: node.WhenFalseLabel, whenFalseLabel: node.WhenTrueLabel)) { // If we can build a linear test sequence with the whenTrue and whenFalse labels swapped, then negate the // result. This would typically arise when the source contains `e is not pattern`. negated = !negated; var isPatternRewriter = new IsPatternExpressionLinearLocalRewriter(node, this); result = isPatternRewriter.LowerIsPatternAsLinearTestSequence(node, whenTrueLabel: node.WhenFalseLabel, whenFalseLabel: node.WhenTrueLabel); isPatternRewriter.Free(); } else { // We need to lower a generalized dag, so we produce a label for the true and false branches and assign to a temporary containing the result. var isPatternRewriter = new IsPatternExpressionGeneralLocalRewriter(node.Syntax, this); result = isPatternRewriter.LowerGeneralIsPattern(node); isPatternRewriter.Free(); } if (negated) { result = this._factory.Not(result); } return result; // Can the given decision dag node, and its successors, be generated as a sequence of // linear tests with a single "golden" path to the true label and all other paths leading // to the false label? This occurs with an is-pattern expression that uses no "or" or "not" // pattern forms. static bool canProduceLinearSequence( BoundDecisionDagNode node, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) { while (true) { switch (node) { case BoundWhenDecisionDagNode w: Debug.Assert(w.WhenFalse is null); node = w.WhenTrue; break; case BoundLeafDecisionDagNode n: return n.Label == whenTrueLabel; case BoundEvaluationDecisionDagNode e: node = e.Next; break; case BoundTestDecisionDagNode t: bool falseFail = IsFailureNode(t.WhenFalse, whenFalseLabel); if (falseFail == IsFailureNode(t.WhenTrue, whenFalseLabel)) return false; node = falseFail ? t.WhenTrue : t.WhenFalse; break; default: throw ExceptionUtilities.UnexpectedValue(node); } } } } /// <summary> /// A local rewriter for lowering an is-pattern expression. This handles the general case by lowering /// the decision dag, and returning a "true" or "false" value as the result at the end. /// </summary> private sealed class IsPatternExpressionGeneralLocalRewriter : DecisionDagRewriter { private readonly ArrayBuilder<BoundStatement> _statements = ArrayBuilder<BoundStatement>.GetInstance(); public IsPatternExpressionGeneralLocalRewriter( SyntaxNode node, LocalRewriter localRewriter) : base(node, localRewriter, generateInstrumentation: false) { } protected override ArrayBuilder<BoundStatement> BuilderForSection(SyntaxNode section) => _statements; public new void Free() { base.Free(); _statements.Free(); } internal BoundExpression LowerGeneralIsPattern(BoundIsPatternExpression node) { _factory.Syntax = node.Syntax; var resultBuilder = ArrayBuilder<BoundStatement>.GetInstance(); var inputExpression = _localRewriter.VisitExpression(node.Expression); BoundDecisionDag decisionDag = ShareTempsIfPossibleAndEvaluateInput( node.DecisionDag, inputExpression, resultBuilder, out _); // lower the decision dag. ImmutableArray<BoundStatement> loweredDag = LowerDecisionDagCore(decisionDag); resultBuilder.Add(_factory.Block(loweredDag)); Debug.Assert(node.Type is { SpecialType: SpecialType.System_Boolean }); LocalSymbol resultTemp = _factory.SynthesizedLocal(node.Type, node.Syntax, kind: SynthesizedLocalKind.LoweringTemp); LabelSymbol afterIsPatternExpression = _factory.GenerateLabel("afterIsPatternExpression"); LabelSymbol trueLabel = node.WhenTrueLabel; LabelSymbol falseLabel = node.WhenFalseLabel; if (_statements.Count != 0) resultBuilder.Add(_factory.Block(_statements.ToArray())); resultBuilder.Add(_factory.Label(trueLabel)); resultBuilder.Add(_factory.Assignment(_factory.Local(resultTemp), _factory.Literal(true))); resultBuilder.Add(_factory.Goto(afterIsPatternExpression)); resultBuilder.Add(_factory.Label(falseLabel)); resultBuilder.Add(_factory.Assignment(_factory.Local(resultTemp), _factory.Literal(false))); resultBuilder.Add(_factory.Label(afterIsPatternExpression)); _localRewriter._needsSpilling = true; return _factory.SpillSequence(_tempAllocator.AllTemps().Add(resultTemp), resultBuilder.ToImmutableAndFree(), _factory.Local(resultTemp)); } } private static bool IsFailureNode(BoundDecisionDagNode node, LabelSymbol whenFalseLabel) { if (node is BoundWhenDecisionDagNode w) node = w.WhenTrue; return node is BoundLeafDecisionDagNode l && l.Label == whenFalseLabel; } private sealed class IsPatternExpressionLinearLocalRewriter : PatternLocalRewriter { /// <summary> /// Accumulates side-effects that come before the next conjunct. /// </summary> private readonly ArrayBuilder<BoundExpression> _sideEffectBuilder; /// <summary> /// Accumulates conjuncts (conditions that must all be true) for the translation. When a conjunct is added, /// elements of the _sideEffectBuilder, if any, should be added as part of a sequence expression for /// the conjunct being added. /// </summary> private readonly ArrayBuilder<BoundExpression> _conjunctBuilder; public IsPatternExpressionLinearLocalRewriter(BoundIsPatternExpression node, LocalRewriter localRewriter) : base(node.Syntax, localRewriter, generateInstrumentation: false) { _conjunctBuilder = ArrayBuilder<BoundExpression>.GetInstance(); _sideEffectBuilder = ArrayBuilder<BoundExpression>.GetInstance(); } public new void Free() { _conjunctBuilder.Free(); _sideEffectBuilder.Free(); base.Free(); } private void AddConjunct(BoundExpression test) { // When in error recovery, the generated code doesn't matter. if (test.Type?.IsErrorType() != false) return; Debug.Assert(test.Type.SpecialType == SpecialType.System_Boolean); if (_sideEffectBuilder.Count != 0) { test = _factory.Sequence(ImmutableArray<LocalSymbol>.Empty, _sideEffectBuilder.ToImmutable(), test); _sideEffectBuilder.Clear(); } _conjunctBuilder.Add(test); } /// <summary> /// Translate the single test into _sideEffectBuilder and _conjunctBuilder. /// </summary> private void LowerOneTest(BoundDagTest test, bool invert = false) { _factory.Syntax = test.Syntax; switch (test) { case BoundDagEvaluation eval: { var sideEffect = LowerEvaluation(eval); _sideEffectBuilder.Add(sideEffect); return; } case var _: { var testExpression = LowerTest(test); if (testExpression != null) { if (invert) testExpression = _factory.Not(testExpression); AddConjunct(testExpression); } return; } } } public BoundExpression LowerIsPatternAsLinearTestSequence( BoundIsPatternExpression isPatternExpression, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) { BoundDecisionDag decisionDag = isPatternExpression.DecisionDag; BoundExpression loweredInput = _localRewriter.VisitExpression(isPatternExpression.Expression); // The optimization of sharing pattern-matching temps with user variables can always apply to // an is-pattern expression because there is no when clause that could possibly intervene during // the execution of the pattern-matching automaton and change one of those variables. decisionDag = ShareTempsAndEvaluateInput(loweredInput, decisionDag, expr => _sideEffectBuilder.Add(expr), out _); var node = decisionDag.RootNode; return ProduceLinearTestSequence(node, whenTrueLabel, whenFalseLabel); } /// <summary> /// Translate an is-pattern expression into a sequence of tests separated by the control-flow-and operator. /// </summary> private BoundExpression ProduceLinearTestSequence( BoundDecisionDagNode node, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) { // We follow the "good" path in the decision dag. We depend on it being nicely linear in structure. // If we add "or" patterns that assumption breaks down. while (node.Kind != BoundKind.LeafDecisionDagNode && node.Kind != BoundKind.WhenDecisionDagNode) { switch (node) { case BoundEvaluationDecisionDagNode evalNode: { LowerOneTest(evalNode.Evaluation); node = evalNode.Next; } break; case BoundTestDecisionDagNode testNode: { if (testNode.WhenTrue is BoundEvaluationDecisionDagNode e && TryLowerTypeTestAndCast(testNode.Test, e.Evaluation, out BoundExpression? sideEffect, out BoundExpression? testExpression)) { _sideEffectBuilder.Add(sideEffect); AddConjunct(testExpression); node = e.Next; } else { bool invertTest = IsFailureNode(testNode.WhenTrue, whenFalseLabel); LowerOneTest(testNode.Test, invertTest); node = invertTest ? testNode.WhenFalse : testNode.WhenTrue; } } break; } } // When we get to "the end", it is a success node. switch (node) { case BoundLeafDecisionDagNode leafNode: Debug.Assert(leafNode.Label == whenTrueLabel); break; case BoundWhenDecisionDagNode whenNode: { Debug.Assert(whenNode.WhenExpression == null); Debug.Assert(whenNode.WhenTrue is BoundLeafDecisionDagNode d && d.Label == whenTrueLabel); foreach (BoundPatternBinding binding in whenNode.Bindings) { BoundExpression left = _localRewriter.VisitExpression(binding.VariableAccess); BoundExpression right = _tempAllocator.GetTemp(binding.TempContainingValue); if (left != right) { _sideEffectBuilder.Add(_factory.AssignmentExpression(left, right)); } } } break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } if (_sideEffectBuilder.Count > 0 || _conjunctBuilder.Count == 0) { AddConjunct(_factory.Literal(true)); } Debug.Assert(_sideEffectBuilder.Count == 0); BoundExpression? result = null; foreach (BoundExpression conjunct in _conjunctBuilder) { result = (result == null) ? conjunct : _factory.LogicalAnd(result, conjunct); } _conjunctBuilder.Clear(); Debug.Assert(result != null); var allTemps = _tempAllocator.AllTemps(); if (allTemps.Length > 0) { result = _factory.Sequence(allTemps, ImmutableArray<BoundExpression>.Empty, result); } return result; } } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/CSharp/Test/Semantic/Properties/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Workspaces/Core/Portable/FindSymbols/ReferenceLocationExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.FindSymbols { internal static class ReferenceLocationExtensions { public static async Task<Dictionary<ISymbol, List<Location>>> FindReferencingSymbolsAsync( this IEnumerable<ReferenceLocation> referenceLocations, CancellationToken cancellationToken) { var documentGroups = referenceLocations.GroupBy(loc => loc.Document); var projectGroups = documentGroups.GroupBy(g => g.Key.Project); var result = new Dictionary<ISymbol, List<Location>>(); foreach (var projectGroup in projectGroups) { cancellationToken.ThrowIfCancellationRequested(); var project = projectGroup.Key; if (project.SupportsCompilation) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); foreach (var documentGroup in projectGroup) { var document = documentGroup.Key; var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); AddSymbols(semanticModel, documentGroup, result); } // Keep compilation alive so that GetSemanticModelAsync remains cheap GC.KeepAlive(compilation); } } return result; } private static void AddSymbols( SemanticModel semanticModel, IEnumerable<ReferenceLocation> references, Dictionary<ISymbol, List<Location>> result) { foreach (var reference in references) { var containingSymbol = GetEnclosingMethodOrPropertyOrField(semanticModel, reference); if (containingSymbol != null) { if (!result.TryGetValue(containingSymbol, out var locations)) { locations = new List<Location>(); result.Add(containingSymbol, locations); } locations.Add(reference.Location); } } } private static ISymbol GetEnclosingMethodOrPropertyOrField( SemanticModel semanticModel, ReferenceLocation reference) { var enclosingSymbol = semanticModel.GetEnclosingSymbol(reference.Location.SourceSpan.Start); for (var current = enclosingSymbol; current != null; current = current.ContainingSymbol) { if (current.Kind == SymbolKind.Field) { return current; } if (current.Kind == SymbolKind.Property) { return current; } if (current.Kind == SymbolKind.Method) { var method = (IMethodSymbol)current; if (method.IsAccessor()) { return method.AssociatedSymbol; } if (method.MethodKind != MethodKind.AnonymousFunction) { return method; } } } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.FindSymbols { internal static class ReferenceLocationExtensions { public static async Task<Dictionary<ISymbol, List<Location>>> FindReferencingSymbolsAsync( this IEnumerable<ReferenceLocation> referenceLocations, CancellationToken cancellationToken) { var documentGroups = referenceLocations.GroupBy(loc => loc.Document); var projectGroups = documentGroups.GroupBy(g => g.Key.Project); var result = new Dictionary<ISymbol, List<Location>>(); foreach (var projectGroup in projectGroups) { cancellationToken.ThrowIfCancellationRequested(); var project = projectGroup.Key; if (project.SupportsCompilation) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); foreach (var documentGroup in projectGroup) { var document = documentGroup.Key; var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); AddSymbols(semanticModel, documentGroup, result); } // Keep compilation alive so that GetSemanticModelAsync remains cheap GC.KeepAlive(compilation); } } return result; } private static void AddSymbols( SemanticModel semanticModel, IEnumerable<ReferenceLocation> references, Dictionary<ISymbol, List<Location>> result) { foreach (var reference in references) { var containingSymbol = GetEnclosingMethodOrPropertyOrField(semanticModel, reference); if (containingSymbol != null) { if (!result.TryGetValue(containingSymbol, out var locations)) { locations = new List<Location>(); result.Add(containingSymbol, locations); } locations.Add(reference.Location); } } } private static ISymbol GetEnclosingMethodOrPropertyOrField( SemanticModel semanticModel, ReferenceLocation reference) { var enclosingSymbol = semanticModel.GetEnclosingSymbol(reference.Location.SourceSpan.Start); for (var current = enclosingSymbol; current != null; current = current.ContainingSymbol) { if (current.Kind == SymbolKind.Field) { return current; } if (current.Kind == SymbolKind.Property) { return current; } if (current.Kind == SymbolKind.Method) { var method = (IMethodSymbol)current; if (method.IsAccessor()) { return method.AssociatedSymbol; } if (method.MethodKind != MethodKind.AnonymousFunction) { return method; } } } return null; } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/Core/Portable/SourceGeneration/GeneratorAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { /// <summary> /// Place this attribute onto a type to cause it to be considered a source generator /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class GeneratorAttribute : Attribute { /// <summary> /// The source languages to which this generator applies. See <see cref="LanguageNames"/>. /// </summary> public string[] Languages { get; } /// <summary> /// Attribute constructor used to specify the attached class is a source generator that provides CSharp sources. /// </summary> public GeneratorAttribute() : this(LanguageNames.CSharp) { } /// <summary> /// Attribute constructor used to specify the attached class is a source generator and indicate which language(s) it supports. /// </summary> /// <param name="firstLanguage">One language to which the generator applies.</param> /// <param name="additionalLanguages">Additional languages to which the generator applies. See <see cref="LanguageNames"/>.</param> public GeneratorAttribute(string firstLanguage, params string[] additionalLanguages) { if (firstLanguage == null) { throw new ArgumentNullException(nameof(firstLanguage)); } if (additionalLanguages == null) { throw new ArgumentNullException(nameof(additionalLanguages)); } var languages = new string[additionalLanguages.Length + 1]; languages[0] = firstLanguage; for (int index = 0; index < additionalLanguages.Length; index++) { languages[index + 1] = additionalLanguages[index]; } this.Languages = languages; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { /// <summary> /// Place this attribute onto a type to cause it to be considered a source generator /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class GeneratorAttribute : Attribute { /// <summary> /// The source languages to which this generator applies. See <see cref="LanguageNames"/>. /// </summary> public string[] Languages { get; } /// <summary> /// Attribute constructor used to specify the attached class is a source generator that provides CSharp sources. /// </summary> public GeneratorAttribute() : this(LanguageNames.CSharp) { } /// <summary> /// Attribute constructor used to specify the attached class is a source generator and indicate which language(s) it supports. /// </summary> /// <param name="firstLanguage">One language to which the generator applies.</param> /// <param name="additionalLanguages">Additional languages to which the generator applies. See <see cref="LanguageNames"/>.</param> public GeneratorAttribute(string firstLanguage, params string[] additionalLanguages) { if (firstLanguage == null) { throw new ArgumentNullException(nameof(firstLanguage)); } if (additionalLanguages == null) { throw new ArgumentNullException(nameof(additionalLanguages)); } var languages = new string[additionalLanguages.Length + 1]; languages[0] = firstLanguage; for (int index = 0; index < additionalLanguages.Length; index++) { languages[index + 1] = additionalLanguages[index]; } this.Languages = languages; } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/Operations/SuppressOption.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Formatting.Rules { /// <summary> /// Options for <see cref="SuppressOperation"/>. /// /// <list type="bullet"> /// <item> /// <term><see cref="NoWrappingIfOnSingleLine"/></term> /// <description>no wrapping if given tokens are on same line</description> /// </item> /// <item> /// <term><see cref="NoWrapping"/></term> /// <description>no wrapping regardless of relative positions of two tokens</description> /// </item> /// <item> /// <term><see cref="NoSpacing"/></term> /// <description>no spacing regardless of relative positions of two tokens</description> /// </item> /// </list> /// </summary> [Flags] internal enum SuppressOption { None = 0x0, NoWrappingIfOnSingleLine = 0x1, NoWrappingIfOnMultipleLine = 0x2, NoWrapping = NoWrappingIfOnSingleLine | NoWrappingIfOnMultipleLine, NoSpacingIfOnSingleLine = 0x4, NoSpacingIfOnMultipleLine = 0x8, NoSpacing = NoSpacingIfOnSingleLine | NoSpacingIfOnMultipleLine, // a suppression operation containing elastic trivia in its start/end token will be ignored // since they can't be used to determine line alignment between two tokens. // this option will make engine to accept the operation even if start/end token has elastic trivia IgnoreElasticWrapping = 0x10, /// <summary> /// Completely disable formatting within a span. /// </summary> DisableFormatting = 0x20, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Formatting.Rules { /// <summary> /// Options for <see cref="SuppressOperation"/>. /// /// <list type="bullet"> /// <item> /// <term><see cref="NoWrappingIfOnSingleLine"/></term> /// <description>no wrapping if given tokens are on same line</description> /// </item> /// <item> /// <term><see cref="NoWrapping"/></term> /// <description>no wrapping regardless of relative positions of two tokens</description> /// </item> /// <item> /// <term><see cref="NoSpacing"/></term> /// <description>no spacing regardless of relative positions of two tokens</description> /// </item> /// </list> /// </summary> [Flags] internal enum SuppressOption { None = 0x0, NoWrappingIfOnSingleLine = 0x1, NoWrappingIfOnMultipleLine = 0x2, NoWrapping = NoWrappingIfOnSingleLine | NoWrappingIfOnMultipleLine, NoSpacingIfOnSingleLine = 0x4, NoSpacingIfOnMultipleLine = 0x8, NoSpacing = NoSpacingIfOnSingleLine | NoSpacingIfOnMultipleLine, // a suppression operation containing elastic trivia in its start/end token will be ignored // since they can't be used to determine line alignment between two tokens. // this option will make engine to accept the operation even if start/end token has elastic trivia IgnoreElasticWrapping = 0x10, /// <summary> /// Completely disable formatting within a span. /// </summary> DisableFormatting = 0x20, } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/VisualBasic/Portable/Binding/EarlyWellKnownAttributeBinder.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' This is a binder for use when early decoding of well known attributes. The binder will only bind expressions that can appear in an attribute. ''' Its purpose is to allow a symbol to safely decode any attribute without the possibility of any attribute related infinite recursion during binding. ''' If an attribute and its arguments are valid then this binder returns a BoundAttributeExpression otherwise it returns a BadExpression. ''' </summary> Friend NotInheritable Class EarlyWellKnownAttributeBinder Inherits Binder Private ReadOnly _owner As Symbol Friend Sub New(owner As Symbol, containingBinder As Binder) MyBase.New(containingBinder, isEarlyAttributeBinder:=True) Me._owner = owner End Sub Public Overrides ReadOnly Property ContainingMember As Symbol Get Return If(_owner, MyBase.ContainingMember) End Get End Property Public Overrides ReadOnly Property AdditionalContainingMembers As ImmutableArray(Of Symbol) Get Return ImmutableArray(Of Symbol).Empty End Get End Property ' This binder is only used to bind expressions in an attribute context. Public Overrides ReadOnly Property BindingLocation As BindingLocation Get Return BindingLocation.Attribute End Get End Property ' Hide the GetAttribute overload which takes a diagnostic bag. ' This ensures that diagnostics from the early bound attributes are never preserved. Friend Shadows Function GetAttribute(node As AttributeSyntax, boundAttributeType As NamedTypeSymbol, <Out> ByRef generatedDiagnostics As Boolean) As SourceAttributeData Dim diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics:=True, withDependencies:=False) Dim earlyAttribute = MyBase.GetAttribute(node, boundAttributeType, diagnostics) generatedDiagnostics = Not diagnostics.DiagnosticBag.IsEmptyWithoutResolution() diagnostics.Free() Return earlyAttribute End Function ''' <summary> ''' Check that the syntax can appear in an attribute argument. ''' </summary> Friend Shared Function CanBeValidAttributeArgument(node As ExpressionSyntax, memberAccessBinder As Binder) As Boolean Debug.Assert(node IsNot Nothing) ' 11.2 Constant Expressions ' 'A constant expression is an expression whose value can be fully evaluated at compile time. The type of a constant expression can be Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Char, Single, Double, Decimal, Date, Boolean, String, Object, or any enumeration type. The following constructs are permitted in constant expressions: ' ' Literals (including Nothing). ' References to constant type members or constant locals. ' References to members of enumeration types. ' Parenthesized subexpressions. ' Coercion expressions, provided the target type is one of the types listed above. Coercions to and from String are an exception to this rule and are only allowed on null values because String conversions are always done in the current culture of the execution environment at run time. Note that constant coercion expressions can only ever use intrinsic conversions. ' The +, – and Not unary operators, provided the operand and result is of a type listed above. ' The +, –, *, ^, Mod, /, \, <<, >>, &, And, Or, Xor, AndAlso, OrElse, =, <, >, <>, <=, and => binary operators, provided each operand and result is of a type listed above. ' The conditional operator If, provided each operand and result is of a type listed above. ' The following run-time functions: ' Microsoft.VisualBasic.Strings.ChrW ' Microsoft.VisualBasic.Strings.Chr, if the constant value is between 0 and 128 ' Microsoft.VisualBasic.Strings.AscW, if the constant string is not empty ' Microsoft.VisualBasic.Strings.Asc, if the constant string is not empty ' ' In addition, attributes allow array expressions including both array literal and array creation expressions as well as GetType expressions. Select Case node.Kind Case _ SyntaxKind.NumericLiteralExpression, SyntaxKind.StringLiteralExpression, SyntaxKind.CharacterLiteralExpression, SyntaxKind.TrueLiteralExpression, SyntaxKind.FalseLiteralExpression, SyntaxKind.NothingLiteralExpression, SyntaxKind.DateLiteralExpression ' Literals (including Nothing). Return True Case _ SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.GlobalName, SyntaxKind.IdentifierName, SyntaxKind.PredefinedType ' References to constant type members or constant locals. ' References to members of enumeration types. Return True Case SyntaxKind.ParenthesizedExpression ' Parenthesized subexpressions. Return True Case _ SyntaxKind.CTypeExpression, SyntaxKind.TryCastExpression, SyntaxKind.DirectCastExpression, SyntaxKind.PredefinedCastExpression ' Coercion expressions, provided the target type is one of the types listed above. ' Coercions to and from String are an exception to this rule and are only allowed on null values ' because String conversions are always done in the current culture of the execution environment ' at run time. Note that constant coercion expressions can only ever use intrinsic conversions. Return True Case _ SyntaxKind.UnaryPlusExpression, SyntaxKind.UnaryMinusExpression, SyntaxKind.NotExpression ' The +, – and Not unary operators, provided the operand and result is of a type listed above. Return True Case _ SyntaxKind.AddExpression, SyntaxKind.SubtractExpression, SyntaxKind.MultiplyExpression, SyntaxKind.ExponentiateExpression, SyntaxKind.DivideExpression, SyntaxKind.ModuloExpression, SyntaxKind.IntegerDivideExpression, SyntaxKind.LeftShiftExpression, SyntaxKind.RightShiftExpression, SyntaxKind.ConcatenateExpression, SyntaxKind.AndExpression, SyntaxKind.OrExpression, SyntaxKind.ExclusiveOrExpression, SyntaxKind.AndAlsoExpression, SyntaxKind.OrElseExpression, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.LessThanOrEqualExpression, SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.LessThanExpression, SyntaxKind.GreaterThanExpression ' The +, –, *, ^, Mod, /, \, <<, >>, &, And, Or, Xor, AndAlso, OrElse, =, <, >, <>, <=, and => binary operators, ' provided each operand and result is of a type listed above. Return True Case _ SyntaxKind.BinaryConditionalExpression, SyntaxKind.TernaryConditionalExpression ' The conditional operator If, provided each operand and result is of a type listed above. Return True Case SyntaxKind.InvocationExpression ' The following run-time functions may appear in constant expressions: ' Microsoft.VisualBasic.Strings.ChrW ' Microsoft.VisualBasic.Strings.Chr, if the constant value is between 0 and 128 ' Microsoft.VisualBasic.Strings.AscW, if the constant string is not empty ' Microsoft.VisualBasic.Strings.Asc, if the constant string is not empty Dim memberAccess = TryCast(DirectCast(node, InvocationExpressionSyntax).Expression, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then Dim boundExpression = memberAccessBinder.BindExpression(memberAccess, BindingDiagnosticBag.Discarded) If boundExpression.HasErrors Then Return False End If Dim boundMethodGroup = TryCast(boundExpression, BoundMethodGroup) If boundMethodGroup IsNot Nothing AndAlso boundMethodGroup.Methods.Length = 1 Then Dim method = boundMethodGroup.Methods(0) Dim compilation As VisualBasicCompilation = memberAccessBinder.Compilation If method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrWInt32Char) OrElse method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrInt32Char) OrElse method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscWCharInt32) OrElse method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscCharInt32) Then Return True End If End If End If Return False Case SyntaxKind.CollectionInitializer, SyntaxKind.ArrayCreationExpression, SyntaxKind.GetTypeExpression ' These are not constants and are special for attribute expressions. ' SyntaxKind.CollectionInitializer in this case really means ArrayLiteral, i.e.{1, 2, 3}. ' SyntaxKind.ArrayCreationExpression is array creation expression, i.e. new Char {'a'c, 'b'c}. ' SyntaxKind.GetTypeExpression is a GetType expression, i.e. GetType(System.String). Return True Case Else Return False End Select End Function Friend Overrides Function BinderSpecificLookupOptions(options As LookupOptions) As LookupOptions ' When early binding attributes, extension methods should always be ignored. Return ContainingBinder.BinderSpecificLookupOptions(options) Or LookupOptions.IgnoreExtensionMethods End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' This is a binder for use when early decoding of well known attributes. The binder will only bind expressions that can appear in an attribute. ''' Its purpose is to allow a symbol to safely decode any attribute without the possibility of any attribute related infinite recursion during binding. ''' If an attribute and its arguments are valid then this binder returns a BoundAttributeExpression otherwise it returns a BadExpression. ''' </summary> Friend NotInheritable Class EarlyWellKnownAttributeBinder Inherits Binder Private ReadOnly _owner As Symbol Friend Sub New(owner As Symbol, containingBinder As Binder) MyBase.New(containingBinder, isEarlyAttributeBinder:=True) Me._owner = owner End Sub Public Overrides ReadOnly Property ContainingMember As Symbol Get Return If(_owner, MyBase.ContainingMember) End Get End Property Public Overrides ReadOnly Property AdditionalContainingMembers As ImmutableArray(Of Symbol) Get Return ImmutableArray(Of Symbol).Empty End Get End Property ' This binder is only used to bind expressions in an attribute context. Public Overrides ReadOnly Property BindingLocation As BindingLocation Get Return BindingLocation.Attribute End Get End Property ' Hide the GetAttribute overload which takes a diagnostic bag. ' This ensures that diagnostics from the early bound attributes are never preserved. Friend Shadows Function GetAttribute(node As AttributeSyntax, boundAttributeType As NamedTypeSymbol, <Out> ByRef generatedDiagnostics As Boolean) As SourceAttributeData Dim diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics:=True, withDependencies:=False) Dim earlyAttribute = MyBase.GetAttribute(node, boundAttributeType, diagnostics) generatedDiagnostics = Not diagnostics.DiagnosticBag.IsEmptyWithoutResolution() diagnostics.Free() Return earlyAttribute End Function ''' <summary> ''' Check that the syntax can appear in an attribute argument. ''' </summary> Friend Shared Function CanBeValidAttributeArgument(node As ExpressionSyntax, memberAccessBinder As Binder) As Boolean Debug.Assert(node IsNot Nothing) ' 11.2 Constant Expressions ' 'A constant expression is an expression whose value can be fully evaluated at compile time. The type of a constant expression can be Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Char, Single, Double, Decimal, Date, Boolean, String, Object, or any enumeration type. The following constructs are permitted in constant expressions: ' ' Literals (including Nothing). ' References to constant type members or constant locals. ' References to members of enumeration types. ' Parenthesized subexpressions. ' Coercion expressions, provided the target type is one of the types listed above. Coercions to and from String are an exception to this rule and are only allowed on null values because String conversions are always done in the current culture of the execution environment at run time. Note that constant coercion expressions can only ever use intrinsic conversions. ' The +, – and Not unary operators, provided the operand and result is of a type listed above. ' The +, –, *, ^, Mod, /, \, <<, >>, &, And, Or, Xor, AndAlso, OrElse, =, <, >, <>, <=, and => binary operators, provided each operand and result is of a type listed above. ' The conditional operator If, provided each operand and result is of a type listed above. ' The following run-time functions: ' Microsoft.VisualBasic.Strings.ChrW ' Microsoft.VisualBasic.Strings.Chr, if the constant value is between 0 and 128 ' Microsoft.VisualBasic.Strings.AscW, if the constant string is not empty ' Microsoft.VisualBasic.Strings.Asc, if the constant string is not empty ' ' In addition, attributes allow array expressions including both array literal and array creation expressions as well as GetType expressions. Select Case node.Kind Case _ SyntaxKind.NumericLiteralExpression, SyntaxKind.StringLiteralExpression, SyntaxKind.CharacterLiteralExpression, SyntaxKind.TrueLiteralExpression, SyntaxKind.FalseLiteralExpression, SyntaxKind.NothingLiteralExpression, SyntaxKind.DateLiteralExpression ' Literals (including Nothing). Return True Case _ SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.GlobalName, SyntaxKind.IdentifierName, SyntaxKind.PredefinedType ' References to constant type members or constant locals. ' References to members of enumeration types. Return True Case SyntaxKind.ParenthesizedExpression ' Parenthesized subexpressions. Return True Case _ SyntaxKind.CTypeExpression, SyntaxKind.TryCastExpression, SyntaxKind.DirectCastExpression, SyntaxKind.PredefinedCastExpression ' Coercion expressions, provided the target type is one of the types listed above. ' Coercions to and from String are an exception to this rule and are only allowed on null values ' because String conversions are always done in the current culture of the execution environment ' at run time. Note that constant coercion expressions can only ever use intrinsic conversions. Return True Case _ SyntaxKind.UnaryPlusExpression, SyntaxKind.UnaryMinusExpression, SyntaxKind.NotExpression ' The +, – and Not unary operators, provided the operand and result is of a type listed above. Return True Case _ SyntaxKind.AddExpression, SyntaxKind.SubtractExpression, SyntaxKind.MultiplyExpression, SyntaxKind.ExponentiateExpression, SyntaxKind.DivideExpression, SyntaxKind.ModuloExpression, SyntaxKind.IntegerDivideExpression, SyntaxKind.LeftShiftExpression, SyntaxKind.RightShiftExpression, SyntaxKind.ConcatenateExpression, SyntaxKind.AndExpression, SyntaxKind.OrExpression, SyntaxKind.ExclusiveOrExpression, SyntaxKind.AndAlsoExpression, SyntaxKind.OrElseExpression, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.LessThanOrEqualExpression, SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.LessThanExpression, SyntaxKind.GreaterThanExpression ' The +, –, *, ^, Mod, /, \, <<, >>, &, And, Or, Xor, AndAlso, OrElse, =, <, >, <>, <=, and => binary operators, ' provided each operand and result is of a type listed above. Return True Case _ SyntaxKind.BinaryConditionalExpression, SyntaxKind.TernaryConditionalExpression ' The conditional operator If, provided each operand and result is of a type listed above. Return True Case SyntaxKind.InvocationExpression ' The following run-time functions may appear in constant expressions: ' Microsoft.VisualBasic.Strings.ChrW ' Microsoft.VisualBasic.Strings.Chr, if the constant value is between 0 and 128 ' Microsoft.VisualBasic.Strings.AscW, if the constant string is not empty ' Microsoft.VisualBasic.Strings.Asc, if the constant string is not empty Dim memberAccess = TryCast(DirectCast(node, InvocationExpressionSyntax).Expression, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then Dim boundExpression = memberAccessBinder.BindExpression(memberAccess, BindingDiagnosticBag.Discarded) If boundExpression.HasErrors Then Return False End If Dim boundMethodGroup = TryCast(boundExpression, BoundMethodGroup) If boundMethodGroup IsNot Nothing AndAlso boundMethodGroup.Methods.Length = 1 Then Dim method = boundMethodGroup.Methods(0) Dim compilation As VisualBasicCompilation = memberAccessBinder.Compilation If method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrWInt32Char) OrElse method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrInt32Char) OrElse method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscWCharInt32) OrElse method Is compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscCharInt32) Then Return True End If End If End If Return False Case SyntaxKind.CollectionInitializer, SyntaxKind.ArrayCreationExpression, SyntaxKind.GetTypeExpression ' These are not constants and are special for attribute expressions. ' SyntaxKind.CollectionInitializer in this case really means ArrayLiteral, i.e.{1, 2, 3}. ' SyntaxKind.ArrayCreationExpression is array creation expression, i.e. new Char {'a'c, 'b'c}. ' SyntaxKind.GetTypeExpression is a GetType expression, i.e. GetType(System.String). Return True Case Else Return False End Select End Function Friend Overrides Function BinderSpecificLookupOptions(options As LookupOptions) As LookupOptions ' When early binding attributes, extension methods should always be ignored. Return ContainingBinder.BinderSpecificLookupOptions(options) Or LookupOptions.IgnoreExtensionMethods End Function End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/ModifierKeywordRecommenderTests.InsideClassDeclaration.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations.ModifierKeywordRecommenderTests Public Class InsideClassDeclaration #Region "Scope Keywords" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PublicExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Public") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ProtectedExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Protected") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PrivateExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Private") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FriendExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Friend") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ProtectedFriendExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Protected Friend") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PublicNotAfterPublicTest() VerifyRecommendationsMissing(<ClassDeclaration>Public |</ClassDeclaration>, "Public") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ProtectedNotAfterPublicTest() VerifyRecommendationsMissing(<ClassDeclaration>Public |</ClassDeclaration>, "Protected") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PrivateNotAfterPublicTest() VerifyRecommendationsMissing(<ClassDeclaration>Public |</ClassDeclaration>, "Private") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FriendNotAfterPublicTest() VerifyRecommendationsMissing(<ClassDeclaration>Public |</ClassDeclaration>, "Friend") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ProtectedFriendNotAfterPublicTest() VerifyRecommendationsMissing(<ClassDeclaration>Public |</ClassDeclaration>, "Protected Friend") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FriendAfterProtectedTest() VerifyRecommendationsContain(<ClassDeclaration>Protected |</ClassDeclaration>, "Friend") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FriendNotAfterProtectedFriendTest() VerifyRecommendationsMissing(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Friend") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ProtectedAfterFriendTest() VerifyRecommendationsContain(<ClassDeclaration>Friend |</ClassDeclaration>, "Protected") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ProtectedNotAfterProtectedFriendTest() VerifyRecommendationsMissing(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Protected") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterOverridesTest() VerifyRecommendationsContain(<ClassDeclaration>Overrides |</ClassDeclaration>, "Public", "Protected", "Friend", "Protected Friend", "Private") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OnlyPublicAfterWideningTest() VerifyRecommendationsContain(<ClassDeclaration>Shared Widening |</ClassDeclaration>, "Public") VerifyRecommendationsMissing(<ClassDeclaration>Shared Widening |</ClassDeclaration>, "Protected", "Friend", "Protected Friend", "Private") End Sub <WorkItem(545037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545037")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PrivateNotAfterDefaultTest() VerifyRecommendationsMissing(<ClassDeclaration>Default |</ClassDeclaration>, "Private") End Sub <WorkItem(545037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545037")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub DefaultNotAfterPrivateTest() VerifyRecommendationsMissing(<ClassDeclaration>Private |</ClassDeclaration>, "Default") End Sub <WorkItem(530330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530330")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterDefaultTest() VerifyRecommendationsContain(<ClassDeclaration>Default |</ClassDeclaration>, "Protected", "Protected Friend") End Sub <WorkItem(547254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547254")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterAsyncTest() VerifyRecommendationsContain(<ClassDeclaration>Async |</ClassDeclaration>, "Public", "Protected", "Protected Friend", "Friend", "Private") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterIteratorTest() VerifyRecommendationsContain(<ClassDeclaration>Iterator |</ClassDeclaration>, "Public", "Protected", "Protected Friend", "Friend", "Private") End Sub <WorkItem(20837, "https://github.com/dotnet/roslyn/issues/20837")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExtensionAttribute() VerifyRecommendationsContain(<ClassDeclaration>&lt;Extension&gt; |</ClassDeclaration>, "Public", "Protected", "Protected Friend", "Friend", "Private") End Sub #End Region #Region "Narrowing and Widening Keywords" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterWideningTest() VerifyRecommendationsMissing(<ClassDeclaration>Widening |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterProtectedTest() VerifyRecommendationsMissing(<ClassDeclaration>Protected |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterProtectedTest() VerifyRecommendationsMissing(<ClassDeclaration>Protected |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterPrivateTest() VerifyRecommendationsMissing(<ClassDeclaration>Private |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterPrivateTest() VerifyRecommendationsMissing(<ClassDeclaration>Private |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterProtectedFriendTest() VerifyRecommendationsMissing(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterProtectedFriendTest() VerifyRecommendationsMissing(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterNotInheritableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterNotInheritableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterPartialTest() VerifyRecommendationsMissing(<ClassDeclaration>Partial |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterPartialTest() VerifyRecommendationsMissing(<ClassDeclaration>Partial |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingAfterSharedTest() VerifyRecommendationsContain(<ClassDeclaration>Shared |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningAfterSharedTest() VerifyRecommendationsContain(<ClassDeclaration>Shared |</ClassDeclaration>, "Widening") End Sub #End Region #Region "MustInherit and NotInheritable Keywords" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterNotInheritableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterWideningTest() VerifyRecommendationsMissing(<ClassDeclaration>Widening |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterWideningTest() VerifyRecommendationsMissing(<ClassDeclaration>Widening |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritAfterPartialTest() VerifyRecommendationsContain(<ClassDeclaration>Partial |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableAfterPartialTest() VerifyRecommendationsContain(<ClassDeclaration>Partial |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterReadOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterReadOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterSharedTest() VerifyRecommendationsMissing(<ClassDeclaration>Shared |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterSharedTest() VerifyRecommendationsMissing(<ClassDeclaration>Shared |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "NotInheritable") End Sub #End Region #Region "Overrides and Overridable Set of Keywords" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Overrides") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "Overrides") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesAfterMustOverrideTest() VerifyRecommendationsContain(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Overrides") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Overrides") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesAfterNotOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Overrides") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesNotAfterShadowsTest() VerifyRecommendationsMissing(<ClassDeclaration>Shadows |</ClassDeclaration>, "Overrides") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "Overrides") End Sub ' --------- <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustOverrideExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "MustOverride") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustOverrideAfterOverridesTest() VerifyRecommendationsContain(<ClassDeclaration>Overrides |</ClassDeclaration>, "MustOverride") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustOverrideNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "MustOverride") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustOverrideNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "MustOverride") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustOverrideNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "MustOverride") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustOverrideAfterShadowsTest() VerifyRecommendationsContain(<ClassDeclaration>Shadows |</ClassDeclaration>, "MustOverride") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustOverrideAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "MustOverride") End Sub ' --------- <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Overridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "Overridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Overridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Overridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Overridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableAfterShadowsTest() VerifyRecommendationsContain(<ClassDeclaration>Shadows |</ClassDeclaration>, "Overridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "Overridable") End Sub ' --------- <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotOverridableExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "NotOverridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotOverridableAfterOverridesTest() VerifyRecommendationsContain(<ClassDeclaration>Overrides |</ClassDeclaration>, "NotOverridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotOverridableNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "NotOverridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotOverridableNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "NotOverridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotOverridableNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "NotOverridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotOverridableNotAfterShadowsTest() VerifyRecommendationsMissing(<ClassDeclaration>Shadows |</ClassDeclaration>, "NotOverridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotOverridableAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "NotOverridable") End Sub ' --------- <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Overloads") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsAfterOverridesTest() VerifyRecommendationsContain(<ClassDeclaration>Overrides |</ClassDeclaration>, "Overloads") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsAfterMustOverrideTest() VerifyRecommendationsContain(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Overloads") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsAfterOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>Overridable |</ClassDeclaration>, "Overloads") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsAfterNotOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Overloads") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsNotAfterShadowsTest() VerifyRecommendationsMissing(<ClassDeclaration>Shadows |</ClassDeclaration>, "Overloads") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsNotAfterOverloadsTest() VerifyRecommendationsMissing(<ClassDeclaration>Overloads |</ClassDeclaration>, "Overloads") End Sub <WorkItem(530330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530330")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableAfterDefaultTest() VerifyRecommendationsContain(<ClassDeclaration>Default |</ClassDeclaration>, "Overridable", "NotOverridable", "MustOverride") End Sub #End Region #Region "ReadOnly and WriteOnly Keywords" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyAfterSharedTest() VerifyRecommendationsContain(<ClassDeclaration>Shared |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterSharedTest() VerifyRecommendationsContain(<ClassDeclaration>Shared |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyAfterDefaultTest() VerifyRecommendationsContain(<ClassDeclaration>Default |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterDefaultTest() VerifyRecommendationsContain(<ClassDeclaration>Default |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyAfterOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>Overridable |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>Overridable |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyAfterNotOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterNotOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyAfterMustOverrideTest() VerifyRecommendationsContain(<ClassDeclaration>MustOverride |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterMustOverrideTest() VerifyRecommendationsContain(<ClassDeclaration>MustOverride |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyNotAfterPartialTest() VerifyRecommendationsMissing(<ClassDeclaration>Partial |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyNotAfterPartialTest() VerifyRecommendationsMissing(<ClassDeclaration>Partial |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyAfterOverridesTest() VerifyRecommendationsContain(<ClassDeclaration>Overrides |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterOverridesTest() VerifyRecommendationsContain(<ClassDeclaration>Overrides |</ClassDeclaration>, "WriteOnly") End Sub #End Region #Region "Partial Keyword" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterPartialTest() VerifyRecommendationsMissing(<ClassDeclaration>Partial |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialAfterMustInheritTest() VerifyRecommendationsContain(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialAfterNotInheritableTest() VerifyRecommendationsContain(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterOverloadsTest() VerifyRecommendationsMissing(<ClassDeclaration>Overloads |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterReadOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterWriteOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>WriteOnly |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterWideningTest() VerifyRecommendationsMissing(<ClassDeclaration>Widening |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterShadowsTest() VerifyRecommendationsMissing(<ClassDeclaration>Shadows |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterDefaultTest() VerifyRecommendationsMissing(<ClassDeclaration>Default |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub KeywordsAfterPartialTest() VerifyRecommendationsAreExactly( <ClassDeclaration>Partial |</ClassDeclaration>, "Class", "Interface", "MustInherit", "NotInheritable", "Overloads", "Private", "Shadows", "Structure", "Sub") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub KeywordsAfterPartialPrivateTest() VerifyRecommendationsAreExactly( <ClassDeclaration>Partial Private |</ClassDeclaration>, "Class", "Interface", "MustInherit", "NotInheritable", "Overloads", "Shadows", "Structure", "Sub") End Sub #End Region #Region "Shadows Keyword" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterMustOverrideTest() VerifyRecommendationsContain(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsNotAfterNotInheritableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsNotAfterOverloadsTest() VerifyRecommendationsMissing(<ClassDeclaration>Overloads |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>Overridable |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterReadOnlyTest() VerifyRecommendationsContain(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterWriteOnlyTest() VerifyRecommendationsContain(<ClassDeclaration>WriteOnly |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterNarrowingTest() VerifyRecommendationsContain(<ClassDeclaration>Narrowing |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterWideningTest() VerifyRecommendationsContain(<ClassDeclaration>Widening |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsNotAfterShadowsTest() VerifyRecommendationsMissing(<ClassDeclaration>Shadows |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterDefaultTest() VerifyRecommendationsContain(<ClassDeclaration>Default |</ClassDeclaration>, "Shadows") End Sub #End Region #Region "Shared Keyword" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SharedDoesExistTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Shared") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SharedDoesNotExistAfterSharedTest() VerifyRecommendationsMissing(<ClassDeclaration>Shared |</ClassDeclaration>, "Shared") End Sub <WorkItem(545039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545039")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SharedAfterShadowsTest() VerifyRecommendationsContain(<ClassDeclaration>Shadows |</ClassDeclaration>, "Shared") End Sub <WorkItem(545039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545039")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesDoesNotExistAfterSharedTest() VerifyRecommendationsMissing(<ClassDeclaration>Shared |</ClassDeclaration>, "Overrides") End Sub <WorkItem(545039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545039")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterSharedTest() VerifyRecommendationsContain(<ClassDeclaration>Shared |</ClassDeclaration>, "Shadows") End Sub #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations.ModifierKeywordRecommenderTests Public Class InsideClassDeclaration #Region "Scope Keywords" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PublicExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Public") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ProtectedExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Protected") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PrivateExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Private") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FriendExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Friend") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ProtectedFriendExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Protected Friend") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PublicNotAfterPublicTest() VerifyRecommendationsMissing(<ClassDeclaration>Public |</ClassDeclaration>, "Public") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ProtectedNotAfterPublicTest() VerifyRecommendationsMissing(<ClassDeclaration>Public |</ClassDeclaration>, "Protected") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PrivateNotAfterPublicTest() VerifyRecommendationsMissing(<ClassDeclaration>Public |</ClassDeclaration>, "Private") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FriendNotAfterPublicTest() VerifyRecommendationsMissing(<ClassDeclaration>Public |</ClassDeclaration>, "Friend") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ProtectedFriendNotAfterPublicTest() VerifyRecommendationsMissing(<ClassDeclaration>Public |</ClassDeclaration>, "Protected Friend") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FriendAfterProtectedTest() VerifyRecommendationsContain(<ClassDeclaration>Protected |</ClassDeclaration>, "Friend") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FriendNotAfterProtectedFriendTest() VerifyRecommendationsMissing(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Friend") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ProtectedAfterFriendTest() VerifyRecommendationsContain(<ClassDeclaration>Friend |</ClassDeclaration>, "Protected") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ProtectedNotAfterProtectedFriendTest() VerifyRecommendationsMissing(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Protected") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterOverridesTest() VerifyRecommendationsContain(<ClassDeclaration>Overrides |</ClassDeclaration>, "Public", "Protected", "Friend", "Protected Friend", "Private") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OnlyPublicAfterWideningTest() VerifyRecommendationsContain(<ClassDeclaration>Shared Widening |</ClassDeclaration>, "Public") VerifyRecommendationsMissing(<ClassDeclaration>Shared Widening |</ClassDeclaration>, "Protected", "Friend", "Protected Friend", "Private") End Sub <WorkItem(545037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545037")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PrivateNotAfterDefaultTest() VerifyRecommendationsMissing(<ClassDeclaration>Default |</ClassDeclaration>, "Private") End Sub <WorkItem(545037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545037")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub DefaultNotAfterPrivateTest() VerifyRecommendationsMissing(<ClassDeclaration>Private |</ClassDeclaration>, "Default") End Sub <WorkItem(530330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530330")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterDefaultTest() VerifyRecommendationsContain(<ClassDeclaration>Default |</ClassDeclaration>, "Protected", "Protected Friend") End Sub <WorkItem(547254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547254")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterAsyncTest() VerifyRecommendationsContain(<ClassDeclaration>Async |</ClassDeclaration>, "Public", "Protected", "Protected Friend", "Friend", "Private") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterIteratorTest() VerifyRecommendationsContain(<ClassDeclaration>Iterator |</ClassDeclaration>, "Public", "Protected", "Protected Friend", "Friend", "Private") End Sub <WorkItem(20837, "https://github.com/dotnet/roslyn/issues/20837")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExtensionAttribute() VerifyRecommendationsContain(<ClassDeclaration>&lt;Extension&gt; |</ClassDeclaration>, "Public", "Protected", "Protected Friend", "Friend", "Private") End Sub #End Region #Region "Narrowing and Widening Keywords" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterWideningTest() VerifyRecommendationsMissing(<ClassDeclaration>Widening |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterProtectedTest() VerifyRecommendationsMissing(<ClassDeclaration>Protected |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterProtectedTest() VerifyRecommendationsMissing(<ClassDeclaration>Protected |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterPrivateTest() VerifyRecommendationsMissing(<ClassDeclaration>Private |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterPrivateTest() VerifyRecommendationsMissing(<ClassDeclaration>Private |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterProtectedFriendTest() VerifyRecommendationsMissing(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterProtectedFriendTest() VerifyRecommendationsMissing(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterNotInheritableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterNotInheritableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotAfterPartialTest() VerifyRecommendationsMissing(<ClassDeclaration>Partial |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotAfterPartialTest() VerifyRecommendationsMissing(<ClassDeclaration>Partial |</ClassDeclaration>, "Widening") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingAfterSharedTest() VerifyRecommendationsContain(<ClassDeclaration>Shared |</ClassDeclaration>, "Narrowing") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningAfterSharedTest() VerifyRecommendationsContain(<ClassDeclaration>Shared |</ClassDeclaration>, "Widening") End Sub #End Region #Region "MustInherit and NotInheritable Keywords" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterNotInheritableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterWideningTest() VerifyRecommendationsMissing(<ClassDeclaration>Widening |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterWideningTest() VerifyRecommendationsMissing(<ClassDeclaration>Widening |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritAfterPartialTest() VerifyRecommendationsContain(<ClassDeclaration>Partial |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableAfterPartialTest() VerifyRecommendationsContain(<ClassDeclaration>Partial |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterReadOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterReadOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterSharedTest() VerifyRecommendationsMissing(<ClassDeclaration>Shared |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterSharedTest() VerifyRecommendationsMissing(<ClassDeclaration>Shared |</ClassDeclaration>, "NotInheritable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustInheritNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "MustInherit") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInheritableNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "NotInheritable") End Sub #End Region #Region "Overrides and Overridable Set of Keywords" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Overrides") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "Overrides") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesAfterMustOverrideTest() VerifyRecommendationsContain(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Overrides") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Overrides") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesAfterNotOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Overrides") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesNotAfterShadowsTest() VerifyRecommendationsMissing(<ClassDeclaration>Shadows |</ClassDeclaration>, "Overrides") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "Overrides") End Sub ' --------- <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustOverrideExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "MustOverride") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustOverrideAfterOverridesTest() VerifyRecommendationsContain(<ClassDeclaration>Overrides |</ClassDeclaration>, "MustOverride") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustOverrideNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "MustOverride") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustOverrideNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "MustOverride") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustOverrideNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "MustOverride") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustOverrideAfterShadowsTest() VerifyRecommendationsContain(<ClassDeclaration>Shadows |</ClassDeclaration>, "MustOverride") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub MustOverrideAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "MustOverride") End Sub ' --------- <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Overridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "Overridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Overridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Overridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Overridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableAfterShadowsTest() VerifyRecommendationsContain(<ClassDeclaration>Shadows |</ClassDeclaration>, "Overridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "Overridable") End Sub ' --------- <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotOverridableExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "NotOverridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotOverridableAfterOverridesTest() VerifyRecommendationsContain(<ClassDeclaration>Overrides |</ClassDeclaration>, "NotOverridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotOverridableNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "NotOverridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotOverridableNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "NotOverridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotOverridableNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "NotOverridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotOverridableNotAfterShadowsTest() VerifyRecommendationsMissing(<ClassDeclaration>Shadows |</ClassDeclaration>, "NotOverridable") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotOverridableAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "NotOverridable") End Sub ' --------- <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Overloads") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsAfterOverridesTest() VerifyRecommendationsContain(<ClassDeclaration>Overrides |</ClassDeclaration>, "Overloads") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsAfterMustOverrideTest() VerifyRecommendationsContain(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Overloads") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsAfterOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>Overridable |</ClassDeclaration>, "Overloads") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsAfterNotOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Overloads") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsNotAfterShadowsTest() VerifyRecommendationsMissing(<ClassDeclaration>Shadows |</ClassDeclaration>, "Overloads") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsNotAfterOverloadsTest() VerifyRecommendationsMissing(<ClassDeclaration>Overloads |</ClassDeclaration>, "Overloads") End Sub <WorkItem(530330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530330")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridableAfterDefaultTest() VerifyRecommendationsContain(<ClassDeclaration>Default |</ClassDeclaration>, "Overridable", "NotOverridable", "MustOverride") End Sub #End Region #Region "ReadOnly and WriteOnly Keywords" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyAfterSharedTest() VerifyRecommendationsContain(<ClassDeclaration>Shared |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterSharedTest() VerifyRecommendationsContain(<ClassDeclaration>Shared |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyAfterDefaultTest() VerifyRecommendationsContain(<ClassDeclaration>Default |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterDefaultTest() VerifyRecommendationsContain(<ClassDeclaration>Default |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyAfterOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>Overridable |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>Overridable |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyAfterNotOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterNotOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterOverloadsTest() VerifyRecommendationsContain(<ClassDeclaration>Overloads |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyAfterMustOverrideTest() VerifyRecommendationsContain(<ClassDeclaration>MustOverride |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterMustOverrideTest() VerifyRecommendationsContain(<ClassDeclaration>MustOverride |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyNotAfterPartialTest() VerifyRecommendationsMissing(<ClassDeclaration>Partial |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyNotAfterPartialTest() VerifyRecommendationsMissing(<ClassDeclaration>Partial |</ClassDeclaration>, "WriteOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReadOnlyAfterOverridesTest() VerifyRecommendationsContain(<ClassDeclaration>Overrides |</ClassDeclaration>, "ReadOnly") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WriteOnlyAfterOverridesTest() VerifyRecommendationsContain(<ClassDeclaration>Overrides |</ClassDeclaration>, "WriteOnly") End Sub #End Region #Region "Partial Keyword" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterPartialTest() VerifyRecommendationsMissing(<ClassDeclaration>Partial |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialAfterMustInheritTest() VerifyRecommendationsContain(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialAfterNotInheritableTest() VerifyRecommendationsContain(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterOverloadsTest() VerifyRecommendationsMissing(<ClassDeclaration>Overloads |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterReadOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterWriteOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>WriteOnly |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterWideningTest() VerifyRecommendationsMissing(<ClassDeclaration>Widening |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterShadowsTest() VerifyRecommendationsMissing(<ClassDeclaration>Shadows |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialNotAfterDefaultTest() VerifyRecommendationsMissing(<ClassDeclaration>Default |</ClassDeclaration>, "Partial") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub KeywordsAfterPartialTest() VerifyRecommendationsAreExactly( <ClassDeclaration>Partial |</ClassDeclaration>, "Class", "Interface", "MustInherit", "NotInheritable", "Overloads", "Private", "Shadows", "Structure", "Sub") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub KeywordsAfterPartialPrivateTest() VerifyRecommendationsAreExactly( <ClassDeclaration>Partial Private |</ClassDeclaration>, "Class", "Interface", "MustInherit", "NotInheritable", "Overloads", "Shadows", "Structure", "Sub") End Sub #End Region #Region "Shadows Keyword" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsExistsTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterMustOverrideTest() VerifyRecommendationsContain(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsNotAfterNotInheritableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsNotAfterOverloadsTest() VerifyRecommendationsMissing(<ClassDeclaration>Overloads |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterOverridableTest() VerifyRecommendationsContain(<ClassDeclaration>Overridable |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterReadOnlyTest() VerifyRecommendationsContain(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterWriteOnlyTest() VerifyRecommendationsContain(<ClassDeclaration>WriteOnly |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterNarrowingTest() VerifyRecommendationsContain(<ClassDeclaration>Narrowing |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterWideningTest() VerifyRecommendationsContain(<ClassDeclaration>Widening |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsNotAfterShadowsTest() VerifyRecommendationsMissing(<ClassDeclaration>Shadows |</ClassDeclaration>, "Shadows") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterDefaultTest() VerifyRecommendationsContain(<ClassDeclaration>Default |</ClassDeclaration>, "Shadows") End Sub #End Region #Region "Shared Keyword" <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SharedDoesExistTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Shared") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SharedDoesNotExistAfterSharedTest() VerifyRecommendationsMissing(<ClassDeclaration>Shared |</ClassDeclaration>, "Shared") End Sub <WorkItem(545039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545039")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SharedAfterShadowsTest() VerifyRecommendationsContain(<ClassDeclaration>Shadows |</ClassDeclaration>, "Shared") End Sub <WorkItem(545039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545039")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesDoesNotExistAfterSharedTest() VerifyRecommendationsMissing(<ClassDeclaration>Shared |</ClassDeclaration>, "Overrides") End Sub <WorkItem(545039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545039")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsAfterSharedTest() VerifyRecommendationsContain(<ClassDeclaration>Shared |</ClassDeclaration>, "Shadows") End Sub #End Region End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/VisualBasic/Portable/Scanner/Blender.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. '----------------------------------------------------------------------------- ' Contains the definition of the Scanner, which produces tokens from text '----------------------------------------------------------------------------- Option Compare Binary Option Strict On Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend NotInheritable Class Blender Inherits Scanner ''' <summary> ''' Candidate nodes that may be reused. ''' </summary> Private ReadOnly _nodeStack As New Stack(Of GreenNode) ''' <summary> ''' The text changes combined into a single region. ''' </summary> Private ReadOnly _change As TextChangeRange ''' <summary> ''' The range from which we cannot reuse nodes. ''' </summary> Private ReadOnly _affectedRange As TextChangeRange ''' <summary> ''' Current node. Not necessarily reusable or even a NonTerminal. ''' Can be null if we are out of nodes. ''' </summary> Private _currentNode As VisualBasicSyntaxNode Private _curNodeStart As Integer Private _curNodeLength As Integer Private ReadOnly _baseTreeRoot As VisualBasic.VisualBasicSyntaxNode ''' <summary> ''' preprocessor state before _currentNode ''' </summary> Private _currentPreprocessorState As PreprocessorState ''' <summary> ''' preprocessor state getter after _currentNode ''' </summary> Private _nextPreprocessorStateGetter As NextPreprocessorStateGetter Private Shared Sub PushReverseNonterminal(stack As Stack(Of GreenNode), nonterminal As GreenNode) Dim cnt = nonterminal.SlotCount For i As Integer = 1 To cnt Dim child = nonterminal.GetSlot(cnt - i) PushChildReverse(stack, child) Next End Sub Private Shared Sub PushReverseTerminal(stack As Stack(Of GreenNode), tk As SyntaxToken) Dim trivia = tk.GetTrailingTrivia If trivia IsNot Nothing Then PushChildReverse(stack, trivia) End If PushChildReverse(stack, DirectCast(tk.WithLeadingTrivia(Nothing).WithTrailingTrivia(Nothing), SyntaxToken)) trivia = tk.GetLeadingTrivia If trivia IsNot Nothing Then PushChildReverse(stack, trivia) End If End Sub Private Shared Sub PushChildReverse(stack As Stack(Of GreenNode), child As GreenNode) If child IsNot Nothing Then If child.IsList Then PushReverseNonterminal(stack, child) Else stack.Push(child) End If End If End Sub ''' <summary> ''' Expand the span in the tree to encompass the ''' nearest statements that the span overlaps. ''' </summary> Private Shared Function ExpandToNearestStatements(root As VisualBasic.VisualBasicSyntaxNode, span As TextSpan) As TextSpan Dim fullSpan = New TextSpan(0, root.FullWidth) Dim start = NearestStatementThatContainsPosition(root, span.Start, fullSpan) Debug.Assert(start.Start <= span.Start) If span.Length = 0 Then Return start Else Dim [end] = NearestStatementThatContainsPosition(root, span.End - 1, fullSpan) Debug.Assert([end].End >= span.End) Return TextSpan.FromBounds(start.Start, [end].End) End If End Function ''' <remarks> ''' Not guaranteed to return the span of a StatementSyntax. ''' </remarks> Private Shared Function NearestStatementThatContainsPosition( node As SyntaxNode, position As Integer, rootFullSpan As TextSpan) As TextSpan If Not node.FullSpan.Contains(position) Then Debug.Assert(node.FullSpan.End = position) Return New TextSpan(position, 0) End If If node.Kind = SyntaxKind.CompilationUnit OrElse IsStatementLike(node) Then Do Dim child = node.ChildThatContainsPosition(position).AsNode() If child Is Nothing OrElse Not IsStatementLike(child) Then Return node.FullSpan End If node = child Loop End If Return rootFullSpan End Function Private Shared Function IsStatementLike(node As SyntaxNode) As Boolean Select Case node.Kind Case SyntaxKind.ElseIfBlock, SyntaxKind.ElseBlock, SyntaxKind.CatchBlock, SyntaxKind.FinallyBlock Return node.GetTrailingTrivia().Any(SyntaxKind.EndOfLineTrivia) Case SyntaxKind.SingleLineIfStatement, SyntaxKind.SingleLineElseClause ' Steer clear of single-line if's because they have custom handling of statement ' terminators that may make it difficult to reuse sub-statements. Return False Case Else Return TypeOf node Is Syntax.StatementSyntax End Select End Function ''' <summary> ''' Expand the span in the tree by the maximum number ''' of tokens required for look ahead and the maximum ''' number of characters for look behind. ''' </summary> Private Shared Function ExpandByLookAheadAndBehind(root As VisualBasic.VisualBasicSyntaxNode, span As TextSpan) As TextSpan Dim fullWidth = root.FullWidth Dim start = Math.Min(span.Start, Math.Max(0, fullWidth - 1)) Dim [end] = span.End If start > 0 Then ' Move to the left by the look ahead required by the Scanner. For i As Integer = 0 To Scanner.MaxTokensLookAheadBeyondEOL Dim node = root.FindTokenInternal(start) If node.Kind = SyntaxKind.None Then Exit For Else start = node.Position If start = 0 Then Exit For Else start -= 1 End If End If Next End If ' Allow for look behind of some number of characters. If [end] < fullWidth Then [end] += Scanner.MaxCharsLookBehind End If Return TextSpan.FromBounds(start, [end]) End Function Friend Sub New(newText As SourceText, changes As TextChangeRange(), baseTreeRoot As SyntaxTree, options As VisualBasicParseOptions) MyBase.New(newText, options) ' initially blend state and scanner state are same _currentPreprocessorState = _scannerPreprocessorState _nextPreprocessorStateGetter = Nothing _baseTreeRoot = baseTreeRoot.GetVisualBasicRoot() _currentNode = _baseTreeRoot.VbGreen _curNodeStart = 0 _curNodeLength = 0 TryCrumbleOnce() If _currentNode Is Nothing Then Return ' tree seems to be empty End If _change = TextChangeRange.Collapse(changes) #If DEBUG Then Dim start = _change.Span.Start Dim [end] = _change.Span.End Debug.Assert(start >= 0) Debug.Assert(start <= [end]) Debug.Assert([end] <= _baseTreeRoot.FullWidth) #End If ' Parser requires look ahead of some number of tokens ' beyond EOL and some number of characters back. ' Expand the change range to accommodate look ahead/behind. Dim span = ExpandToNearestStatements( _baseTreeRoot, ExpandByLookAheadAndBehind(_baseTreeRoot, _change.Span)) _affectedRange = New TextChangeRange(span, span.Length - _change.Span.Length + _change.NewLength) End Sub Private Function MapNewPositionToOldTree(position As Integer) As Integer If position < _change.Span.Start Then Return position End If If position >= _change.Span.Start + _change.NewLength Then Return position - _change.NewLength + _change.Span.Length End If Return -1 End Function ''' <summary> ''' Moving to the next node on the stack. ''' returns false if we are out of nodes. ''' </summary> Private Function TryPopNode() As Boolean If _nodeStack.Count > 0 Then Dim node = _nodeStack.Pop _currentNode = DirectCast(node, VisualBasicSyntaxNode) _curNodeStart = _curNodeStart + _curNodeLength _curNodeLength = node.FullWidth ' move blender preprocessor state forward if possible If _nextPreprocessorStateGetter.Valid Then _currentPreprocessorState = _nextPreprocessorStateGetter.State() End If _nextPreprocessorStateGetter = New NextPreprocessorStateGetter(_currentPreprocessorState, DirectCast(node, VisualBasicSyntaxNode)) Return True Else _currentNode = Nothing Return False End If End Function ''' <summary> ''' Crumbles current node onto the stack and pops one node into current. ''' Returns false if current node cannot be crumbled. ''' </summary> Friend Overrides Function TryCrumbleOnce() As Boolean If _currentNode Is Nothing Then Return False End If If _currentNode.SlotCount = 0 Then If Not _currentNode.ContainsStructuredTrivia Then ' terminal with no structured trivia is not interesting Return False End If ' try reusing structured trivia (in particular XML) PushReverseTerminal(_nodeStack, DirectCast(_currentNode, SyntaxToken)) Else If Not ShouldCrumble(_currentNode) Then Return False End If PushReverseNonterminal(_nodeStack, _currentNode) End If ' crumbling does not affect start, but length is set to 0 until we see a node _curNodeLength = 0 ' crumbling doesn't move things forward. discard next preprocessor state we calculated before _nextPreprocessorStateGetter = Nothing Return TryPopNode() End Function ''' <summary> ''' Certain syntax node kinds should not be crumbled since ''' re-using individual child nodes may complicate parsing. ''' </summary> Private Shared Function ShouldCrumble(node As VisualBasicSyntaxNode) As Boolean If TypeOf node Is StructuredTriviaSyntax Then ' Do not crumble into structured trivia content. ' we will not use any of the parts anyways and ' evaluation of directives may go out of sync. Return False End If Select Case node.Kind Case SyntaxKind.SingleLineIfStatement, SyntaxKind.SingleLineElseClause ' Parsing of single line If is particularly complicated ' since the statement may contain colon separated or ' multi-line statements. Avoid re-using child nodes. Return False Case SyntaxKind.EnumBlock ' Interpretation of other nodes within Enum block ' may depend on the kind of this node. Return False Case Else Return True End Select End Function ''' <summary> ''' Advances to given position if needed (note: no way back) ''' Gets a nonterminal that can be used for incremental. ''' May return Nothing if such node is not available. ''' Typically it is _currentNode. ''' </summary> Private Function GetCurrentNode(position As Integer) As VisualBasicSyntaxNode Debug.Assert(_currentNode IsNot Nothing) Dim mappedPosition = MapNewPositionToOldTree(position) If mappedPosition = -1 Then Return Nothing End If Do ' too far ahead If _curNodeStart > mappedPosition Then Return Nothing End If ' node ends before or on the mappedPosition ' whole node is unusable, move to the next node If (_curNodeStart + _curNodeLength) <= mappedPosition Then If TryPopNode() Then Continue Do Else Return Nothing End If End If If _curNodeStart = mappedPosition AndAlso CanReuseNode(_currentNode) Then ' have some node Exit Do End If ' current node spans the position or node is not usable ' try crumbling and look through children If Not TryCrumbleOnce() Then Return Nothing End If Loop ' zero-length nodes are ambiguous when given a particular position ' also the vast majority of such nodes are synthesized Debug.Assert(_currentNode.FullWidth > 0, "reusing zero-length nodes?") Return _currentNode End Function ''' <summary> ''' Returns current candidate for reuse if there is one. ''' </summary> Friend Overrides Function GetCurrentSyntaxNode() As VisualBasicSyntaxNode ' not going to get any nodes if there is no current node. If _currentNode Is Nothing Then Return Nothing End If ' node must start where the current token starts. Dim start = _currentToken.Position ' position is in affected range - no point trying. Dim range = New TextSpan(_affectedRange.Span.Start, _affectedRange.NewLength) If range.Contains(start) Then Return Nothing End If Dim nonterminal = GetCurrentNode(start) Return nonterminal End Function ''' <summary> ''' Checks if node is reusable. ''' The reasons for it not be usable are typically that it intersects affected range. ''' </summary> Private Function CanReuseNode(node As VisualBasicSyntaxNode) As Boolean If node Is Nothing Then Return False End If If node.SlotCount = 0 Then Return False End If ' TODO: This is a temporary measure to get around contextual errors. ' The problem is that some errors are contextual, but get attached to inner nodes. ' as a result in a case when an edit changes the context the error may be invalidated ' but since the node with actual error did not change the error will stay. If node.ContainsDiagnostics Then Return False End If ' As of 2013/03/14, the compiler never attempts to incrementally parse a tree containing ' annotations. Our goal in instituting this restriction is to prevent API clients from ' taking a dependency on the survival of annotations. If node.ContainsAnnotations Then Return False End If ' If the node is an If statement, we need to determine whether it is a ' single-line or multi-line If. That requires the scanner to be positioned ' correctly relative to the end of line terminator if any, and currently we ' do not guarantee that. (See bug #16557.) For now, for simplicity, we ' do not reuse If statements. If node.Kind = SyntaxKind.IfStatement Then Return False End If Dim _curNodeSpan = New TextSpan(_curNodeStart, _curNodeLength) ' TextSpan.OverlapsWith does not handle empty spans so ' empty spans need to be handled explicitly. Debug.Assert(_curNodeSpan.Length > 0) If _affectedRange.Span.Length = 0 Then If _curNodeSpan.Contains(_affectedRange.Span.Start) Then Return False End If Else If _curNodeSpan.OverlapsWith(_affectedRange.Span) Then Return False End If End If ' we cannot use nodes that contain directives since we need to process ' directives individually. ' We however can use individual directives. If node.ContainsDirectives AndAlso Not TypeOf node Is DirectiveTriviaSyntax Then Return _scannerPreprocessorState.IsEquivalentTo(_currentPreprocessorState) End If ' sometimes nodes contain linebreaks in leading trivia ' if we are in VBAllowLeadingMultilineTrivia state (common case), it is ok. ' otherwise nodes with leading trivia containing linebreaks should be rejected. If Not Me._currentToken.State = ScannerState.VBAllowLeadingMultilineTrivia AndAlso ContainsLeadingLineBreaks(node) Then Return False End If If _currentNode.IsMissing Then Return Nothing End If Return True End Function Private Function ContainsLeadingLineBreaks(node As VisualBasicSyntaxNode) As Boolean Dim lt = node.GetLeadingTrivia If lt IsNot Nothing Then If lt.RawKind = SyntaxKind.EndOfLineTrivia Then Return True End If Dim asList = TryCast(lt, SyntaxList) If asList IsNot Nothing Then For i As Integer = 0 To asList.SlotCount - 1 If lt.GetSlot(i).RawKind = SyntaxKind.EndOfLineTrivia Then Return True End If Next End If End If Return False End Function Friend Overrides Sub MoveToNextSyntaxNode() If _currentNode Is Nothing Then Return End If Debug.Assert(CanReuseNode(_currentNode), "this node could not have been used.") Debug.Assert(_nextPreprocessorStateGetter.Valid, "we should have _nextPreprocessorState") Dim nextPreprocessorState = _nextPreprocessorStateGetter.State() Debug.Assert(nextPreprocessorState.ConditionalStack.Count = 0 OrElse nextPreprocessorState.ConditionalStack.Peek.BranchTaken = ConditionalState.BranchTakenState.Taken, "how could a parser in taken PP state?") ' update buffer offset relative to current token _lineBufferOffset = _currentToken.Position + _curNodeLength ' sync current token's preprocessor state to blender preprocessor state ' it is safe to do so here since if we are here, it means we can reuse information in old tree up to this point ' including preprocessor state ' *NOTE* we are using _nextPreprocessorState instead of _currentPreprocessorState because ' we are actually moving things forward here. _nextPreprocessorState will become _currentPreprocessorState ' at the "TryPopNode" below. If _currentNode.ContainsDirectives Then _currentToken = _currentToken.With(nextPreprocessorState) End If ' this will discard any prefetched tokens, including current. ' We do not need them since we moved to completely new node. MyBase.MoveToNextSyntaxNode() TryPopNode() ' at this point, all three pointers (position in old tree, position in text, position in parser) ' and all preprocessor state (_currentPreprocessorState, _scannerPreprocessorState, _currentToken.PreprocessorState) ' should point to same position (in sync) End Sub Friend Overrides Sub MoveToNextSyntaxNodeInTrivia() If _currentNode Is Nothing Then Return End If Debug.Assert(CanReuseNode(_currentNode), "this node could not have been used.") ' just move forward _lineBufferOffset = _lineBufferOffset + _curNodeLength ' this will just verify that we do not have any prefetched tokens, including current. ' otherwise advancing line buffer offset could go out of sync with token stream. MyBase.MoveToNextSyntaxNodeInTrivia() TryPopNode() End Sub Private Structure NextPreprocessorStateGetter Private ReadOnly _state As PreprocessorState Private ReadOnly _node As VisualBasicSyntaxNode Private _nextState As PreprocessorState Public Sub New(state As PreprocessorState, node As VisualBasicSyntaxNode) Me._state = state Me._node = node Me._nextState = Nothing End Sub Public ReadOnly Property Valid As Boolean Get Return _node IsNot Nothing End Get End Property Public Function State() As PreprocessorState If _nextState Is Nothing Then _nextState = ApplyDirectives(Me._state, Me._node) End If Return _nextState End Function End Structure 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. '----------------------------------------------------------------------------- ' Contains the definition of the Scanner, which produces tokens from text '----------------------------------------------------------------------------- Option Compare Binary Option Strict On Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend NotInheritable Class Blender Inherits Scanner ''' <summary> ''' Candidate nodes that may be reused. ''' </summary> Private ReadOnly _nodeStack As New Stack(Of GreenNode) ''' <summary> ''' The text changes combined into a single region. ''' </summary> Private ReadOnly _change As TextChangeRange ''' <summary> ''' The range from which we cannot reuse nodes. ''' </summary> Private ReadOnly _affectedRange As TextChangeRange ''' <summary> ''' Current node. Not necessarily reusable or even a NonTerminal. ''' Can be null if we are out of nodes. ''' </summary> Private _currentNode As VisualBasicSyntaxNode Private _curNodeStart As Integer Private _curNodeLength As Integer Private ReadOnly _baseTreeRoot As VisualBasic.VisualBasicSyntaxNode ''' <summary> ''' preprocessor state before _currentNode ''' </summary> Private _currentPreprocessorState As PreprocessorState ''' <summary> ''' preprocessor state getter after _currentNode ''' </summary> Private _nextPreprocessorStateGetter As NextPreprocessorStateGetter Private Shared Sub PushReverseNonterminal(stack As Stack(Of GreenNode), nonterminal As GreenNode) Dim cnt = nonterminal.SlotCount For i As Integer = 1 To cnt Dim child = nonterminal.GetSlot(cnt - i) PushChildReverse(stack, child) Next End Sub Private Shared Sub PushReverseTerminal(stack As Stack(Of GreenNode), tk As SyntaxToken) Dim trivia = tk.GetTrailingTrivia If trivia IsNot Nothing Then PushChildReverse(stack, trivia) End If PushChildReverse(stack, DirectCast(tk.WithLeadingTrivia(Nothing).WithTrailingTrivia(Nothing), SyntaxToken)) trivia = tk.GetLeadingTrivia If trivia IsNot Nothing Then PushChildReverse(stack, trivia) End If End Sub Private Shared Sub PushChildReverse(stack As Stack(Of GreenNode), child As GreenNode) If child IsNot Nothing Then If child.IsList Then PushReverseNonterminal(stack, child) Else stack.Push(child) End If End If End Sub ''' <summary> ''' Expand the span in the tree to encompass the ''' nearest statements that the span overlaps. ''' </summary> Private Shared Function ExpandToNearestStatements(root As VisualBasic.VisualBasicSyntaxNode, span As TextSpan) As TextSpan Dim fullSpan = New TextSpan(0, root.FullWidth) Dim start = NearestStatementThatContainsPosition(root, span.Start, fullSpan) Debug.Assert(start.Start <= span.Start) If span.Length = 0 Then Return start Else Dim [end] = NearestStatementThatContainsPosition(root, span.End - 1, fullSpan) Debug.Assert([end].End >= span.End) Return TextSpan.FromBounds(start.Start, [end].End) End If End Function ''' <remarks> ''' Not guaranteed to return the span of a StatementSyntax. ''' </remarks> Private Shared Function NearestStatementThatContainsPosition( node As SyntaxNode, position As Integer, rootFullSpan As TextSpan) As TextSpan If Not node.FullSpan.Contains(position) Then Debug.Assert(node.FullSpan.End = position) Return New TextSpan(position, 0) End If If node.Kind = SyntaxKind.CompilationUnit OrElse IsStatementLike(node) Then Do Dim child = node.ChildThatContainsPosition(position).AsNode() If child Is Nothing OrElse Not IsStatementLike(child) Then Return node.FullSpan End If node = child Loop End If Return rootFullSpan End Function Private Shared Function IsStatementLike(node As SyntaxNode) As Boolean Select Case node.Kind Case SyntaxKind.ElseIfBlock, SyntaxKind.ElseBlock, SyntaxKind.CatchBlock, SyntaxKind.FinallyBlock Return node.GetTrailingTrivia().Any(SyntaxKind.EndOfLineTrivia) Case SyntaxKind.SingleLineIfStatement, SyntaxKind.SingleLineElseClause ' Steer clear of single-line if's because they have custom handling of statement ' terminators that may make it difficult to reuse sub-statements. Return False Case Else Return TypeOf node Is Syntax.StatementSyntax End Select End Function ''' <summary> ''' Expand the span in the tree by the maximum number ''' of tokens required for look ahead and the maximum ''' number of characters for look behind. ''' </summary> Private Shared Function ExpandByLookAheadAndBehind(root As VisualBasic.VisualBasicSyntaxNode, span As TextSpan) As TextSpan Dim fullWidth = root.FullWidth Dim start = Math.Min(span.Start, Math.Max(0, fullWidth - 1)) Dim [end] = span.End If start > 0 Then ' Move to the left by the look ahead required by the Scanner. For i As Integer = 0 To Scanner.MaxTokensLookAheadBeyondEOL Dim node = root.FindTokenInternal(start) If node.Kind = SyntaxKind.None Then Exit For Else start = node.Position If start = 0 Then Exit For Else start -= 1 End If End If Next End If ' Allow for look behind of some number of characters. If [end] < fullWidth Then [end] += Scanner.MaxCharsLookBehind End If Return TextSpan.FromBounds(start, [end]) End Function Friend Sub New(newText As SourceText, changes As TextChangeRange(), baseTreeRoot As SyntaxTree, options As VisualBasicParseOptions) MyBase.New(newText, options) ' initially blend state and scanner state are same _currentPreprocessorState = _scannerPreprocessorState _nextPreprocessorStateGetter = Nothing _baseTreeRoot = baseTreeRoot.GetVisualBasicRoot() _currentNode = _baseTreeRoot.VbGreen _curNodeStart = 0 _curNodeLength = 0 TryCrumbleOnce() If _currentNode Is Nothing Then Return ' tree seems to be empty End If _change = TextChangeRange.Collapse(changes) #If DEBUG Then Dim start = _change.Span.Start Dim [end] = _change.Span.End Debug.Assert(start >= 0) Debug.Assert(start <= [end]) Debug.Assert([end] <= _baseTreeRoot.FullWidth) #End If ' Parser requires look ahead of some number of tokens ' beyond EOL and some number of characters back. ' Expand the change range to accommodate look ahead/behind. Dim span = ExpandToNearestStatements( _baseTreeRoot, ExpandByLookAheadAndBehind(_baseTreeRoot, _change.Span)) _affectedRange = New TextChangeRange(span, span.Length - _change.Span.Length + _change.NewLength) End Sub Private Function MapNewPositionToOldTree(position As Integer) As Integer If position < _change.Span.Start Then Return position End If If position >= _change.Span.Start + _change.NewLength Then Return position - _change.NewLength + _change.Span.Length End If Return -1 End Function ''' <summary> ''' Moving to the next node on the stack. ''' returns false if we are out of nodes. ''' </summary> Private Function TryPopNode() As Boolean If _nodeStack.Count > 0 Then Dim node = _nodeStack.Pop _currentNode = DirectCast(node, VisualBasicSyntaxNode) _curNodeStart = _curNodeStart + _curNodeLength _curNodeLength = node.FullWidth ' move blender preprocessor state forward if possible If _nextPreprocessorStateGetter.Valid Then _currentPreprocessorState = _nextPreprocessorStateGetter.State() End If _nextPreprocessorStateGetter = New NextPreprocessorStateGetter(_currentPreprocessorState, DirectCast(node, VisualBasicSyntaxNode)) Return True Else _currentNode = Nothing Return False End If End Function ''' <summary> ''' Crumbles current node onto the stack and pops one node into current. ''' Returns false if current node cannot be crumbled. ''' </summary> Friend Overrides Function TryCrumbleOnce() As Boolean If _currentNode Is Nothing Then Return False End If If _currentNode.SlotCount = 0 Then If Not _currentNode.ContainsStructuredTrivia Then ' terminal with no structured trivia is not interesting Return False End If ' try reusing structured trivia (in particular XML) PushReverseTerminal(_nodeStack, DirectCast(_currentNode, SyntaxToken)) Else If Not ShouldCrumble(_currentNode) Then Return False End If PushReverseNonterminal(_nodeStack, _currentNode) End If ' crumbling does not affect start, but length is set to 0 until we see a node _curNodeLength = 0 ' crumbling doesn't move things forward. discard next preprocessor state we calculated before _nextPreprocessorStateGetter = Nothing Return TryPopNode() End Function ''' <summary> ''' Certain syntax node kinds should not be crumbled since ''' re-using individual child nodes may complicate parsing. ''' </summary> Private Shared Function ShouldCrumble(node As VisualBasicSyntaxNode) As Boolean If TypeOf node Is StructuredTriviaSyntax Then ' Do not crumble into structured trivia content. ' we will not use any of the parts anyways and ' evaluation of directives may go out of sync. Return False End If Select Case node.Kind Case SyntaxKind.SingleLineIfStatement, SyntaxKind.SingleLineElseClause ' Parsing of single line If is particularly complicated ' since the statement may contain colon separated or ' multi-line statements. Avoid re-using child nodes. Return False Case SyntaxKind.EnumBlock ' Interpretation of other nodes within Enum block ' may depend on the kind of this node. Return False Case Else Return True End Select End Function ''' <summary> ''' Advances to given position if needed (note: no way back) ''' Gets a nonterminal that can be used for incremental. ''' May return Nothing if such node is not available. ''' Typically it is _currentNode. ''' </summary> Private Function GetCurrentNode(position As Integer) As VisualBasicSyntaxNode Debug.Assert(_currentNode IsNot Nothing) Dim mappedPosition = MapNewPositionToOldTree(position) If mappedPosition = -1 Then Return Nothing End If Do ' too far ahead If _curNodeStart > mappedPosition Then Return Nothing End If ' node ends before or on the mappedPosition ' whole node is unusable, move to the next node If (_curNodeStart + _curNodeLength) <= mappedPosition Then If TryPopNode() Then Continue Do Else Return Nothing End If End If If _curNodeStart = mappedPosition AndAlso CanReuseNode(_currentNode) Then ' have some node Exit Do End If ' current node spans the position or node is not usable ' try crumbling and look through children If Not TryCrumbleOnce() Then Return Nothing End If Loop ' zero-length nodes are ambiguous when given a particular position ' also the vast majority of such nodes are synthesized Debug.Assert(_currentNode.FullWidth > 0, "reusing zero-length nodes?") Return _currentNode End Function ''' <summary> ''' Returns current candidate for reuse if there is one. ''' </summary> Friend Overrides Function GetCurrentSyntaxNode() As VisualBasicSyntaxNode ' not going to get any nodes if there is no current node. If _currentNode Is Nothing Then Return Nothing End If ' node must start where the current token starts. Dim start = _currentToken.Position ' position is in affected range - no point trying. Dim range = New TextSpan(_affectedRange.Span.Start, _affectedRange.NewLength) If range.Contains(start) Then Return Nothing End If Dim nonterminal = GetCurrentNode(start) Return nonterminal End Function ''' <summary> ''' Checks if node is reusable. ''' The reasons for it not be usable are typically that it intersects affected range. ''' </summary> Private Function CanReuseNode(node As VisualBasicSyntaxNode) As Boolean If node Is Nothing Then Return False End If If node.SlotCount = 0 Then Return False End If ' TODO: This is a temporary measure to get around contextual errors. ' The problem is that some errors are contextual, but get attached to inner nodes. ' as a result in a case when an edit changes the context the error may be invalidated ' but since the node with actual error did not change the error will stay. If node.ContainsDiagnostics Then Return False End If ' As of 2013/03/14, the compiler never attempts to incrementally parse a tree containing ' annotations. Our goal in instituting this restriction is to prevent API clients from ' taking a dependency on the survival of annotations. If node.ContainsAnnotations Then Return False End If ' If the node is an If statement, we need to determine whether it is a ' single-line or multi-line If. That requires the scanner to be positioned ' correctly relative to the end of line terminator if any, and currently we ' do not guarantee that. (See bug #16557.) For now, for simplicity, we ' do not reuse If statements. If node.Kind = SyntaxKind.IfStatement Then Return False End If Dim _curNodeSpan = New TextSpan(_curNodeStart, _curNodeLength) ' TextSpan.OverlapsWith does not handle empty spans so ' empty spans need to be handled explicitly. Debug.Assert(_curNodeSpan.Length > 0) If _affectedRange.Span.Length = 0 Then If _curNodeSpan.Contains(_affectedRange.Span.Start) Then Return False End If Else If _curNodeSpan.OverlapsWith(_affectedRange.Span) Then Return False End If End If ' we cannot use nodes that contain directives since we need to process ' directives individually. ' We however can use individual directives. If node.ContainsDirectives AndAlso Not TypeOf node Is DirectiveTriviaSyntax Then Return _scannerPreprocessorState.IsEquivalentTo(_currentPreprocessorState) End If ' sometimes nodes contain linebreaks in leading trivia ' if we are in VBAllowLeadingMultilineTrivia state (common case), it is ok. ' otherwise nodes with leading trivia containing linebreaks should be rejected. If Not Me._currentToken.State = ScannerState.VBAllowLeadingMultilineTrivia AndAlso ContainsLeadingLineBreaks(node) Then Return False End If If _currentNode.IsMissing Then Return Nothing End If Return True End Function Private Function ContainsLeadingLineBreaks(node As VisualBasicSyntaxNode) As Boolean Dim lt = node.GetLeadingTrivia If lt IsNot Nothing Then If lt.RawKind = SyntaxKind.EndOfLineTrivia Then Return True End If Dim asList = TryCast(lt, SyntaxList) If asList IsNot Nothing Then For i As Integer = 0 To asList.SlotCount - 1 If lt.GetSlot(i).RawKind = SyntaxKind.EndOfLineTrivia Then Return True End If Next End If End If Return False End Function Friend Overrides Sub MoveToNextSyntaxNode() If _currentNode Is Nothing Then Return End If Debug.Assert(CanReuseNode(_currentNode), "this node could not have been used.") Debug.Assert(_nextPreprocessorStateGetter.Valid, "we should have _nextPreprocessorState") Dim nextPreprocessorState = _nextPreprocessorStateGetter.State() Debug.Assert(nextPreprocessorState.ConditionalStack.Count = 0 OrElse nextPreprocessorState.ConditionalStack.Peek.BranchTaken = ConditionalState.BranchTakenState.Taken, "how could a parser in taken PP state?") ' update buffer offset relative to current token _lineBufferOffset = _currentToken.Position + _curNodeLength ' sync current token's preprocessor state to blender preprocessor state ' it is safe to do so here since if we are here, it means we can reuse information in old tree up to this point ' including preprocessor state ' *NOTE* we are using _nextPreprocessorState instead of _currentPreprocessorState because ' we are actually moving things forward here. _nextPreprocessorState will become _currentPreprocessorState ' at the "TryPopNode" below. If _currentNode.ContainsDirectives Then _currentToken = _currentToken.With(nextPreprocessorState) End If ' this will discard any prefetched tokens, including current. ' We do not need them since we moved to completely new node. MyBase.MoveToNextSyntaxNode() TryPopNode() ' at this point, all three pointers (position in old tree, position in text, position in parser) ' and all preprocessor state (_currentPreprocessorState, _scannerPreprocessorState, _currentToken.PreprocessorState) ' should point to same position (in sync) End Sub Friend Overrides Sub MoveToNextSyntaxNodeInTrivia() If _currentNode Is Nothing Then Return End If Debug.Assert(CanReuseNode(_currentNode), "this node could not have been used.") ' just move forward _lineBufferOffset = _lineBufferOffset + _curNodeLength ' this will just verify that we do not have any prefetched tokens, including current. ' otherwise advancing line buffer offset could go out of sync with token stream. MyBase.MoveToNextSyntaxNodeInTrivia() TryPopNode() End Sub Private Structure NextPreprocessorStateGetter Private ReadOnly _state As PreprocessorState Private ReadOnly _node As VisualBasicSyntaxNode Private _nextState As PreprocessorState Public Sub New(state As PreprocessorState, node As VisualBasicSyntaxNode) Me._state = state Me._node = node Me._nextState = Nothing End Sub Public ReadOnly Property Valid As Boolean Get Return _node IsNot Nothing End Get End Property Public Function State() As PreprocessorState If _nextState Is Nothing Then _nextState = ApplyDirectives(Me._state, Me._node) End If Return _nextState End Function End Structure End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/CSharp/Portable/Symbols/Attributes/WellKnownAttributeData/ParameterWellKnownAttributeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Information decoded from well-known custom attributes applied on a parameter. /// </summary> internal sealed class ParameterWellKnownAttributeData : CommonParameterWellKnownAttributeData { private bool _hasAllowNullAttribute; public bool HasAllowNullAttribute { get { VerifySealed(expected: true); return _hasAllowNullAttribute; } set { VerifySealed(expected: false); _hasAllowNullAttribute = value; SetDataStored(); } } private bool _hasDisallowNullAttribute; public bool HasDisallowNullAttribute { get { VerifySealed(expected: true); return _hasDisallowNullAttribute; } set { VerifySealed(expected: false); _hasDisallowNullAttribute = value; SetDataStored(); } } private bool _hasMaybeNullAttribute; public bool HasMaybeNullAttribute { get { VerifySealed(expected: true); return _hasMaybeNullAttribute; } set { VerifySealed(expected: false); _hasMaybeNullAttribute = value; SetDataStored(); } } private bool? _maybeNullWhenAttribute; public bool? MaybeNullWhenAttribute { get { VerifySealed(expected: true); return _maybeNullWhenAttribute; } set { VerifySealed(expected: false); _maybeNullWhenAttribute = value; SetDataStored(); } } private bool _hasNotNullAttribute; public bool HasNotNullAttribute { get { VerifySealed(expected: true); return _hasNotNullAttribute; } set { VerifySealed(expected: false); _hasNotNullAttribute = value; SetDataStored(); } } private bool? _notNullWhenAttribute; public bool? NotNullWhenAttribute { get { VerifySealed(expected: true); return _notNullWhenAttribute; } set { VerifySealed(expected: false); _notNullWhenAttribute = value; SetDataStored(); } } private bool? _doesNotReturnIfAttribute; public bool? DoesNotReturnIfAttribute { get { VerifySealed(expected: true); return _doesNotReturnIfAttribute; } set { VerifySealed(expected: false); _doesNotReturnIfAttribute = value; SetDataStored(); } } private bool _hasEnumeratorCancellationAttribute; public bool HasEnumeratorCancellationAttribute { get { VerifySealed(expected: true); return _hasEnumeratorCancellationAttribute; } set { VerifySealed(expected: false); _hasEnumeratorCancellationAttribute = value; SetDataStored(); } } private ImmutableHashSet<string> _notNullIfParameterNotNull = ImmutableHashSet<string>.Empty; public ImmutableHashSet<string> NotNullIfParameterNotNull { get { VerifySealed(expected: true); return _notNullIfParameterNotNull; } } public void AddNotNullIfParameterNotNull(string parameterName) { VerifySealed(expected: false); // The common case is zero or one attribute _notNullIfParameterNotNull = _notNullIfParameterNotNull.Add(parameterName); SetDataStored(); } private ImmutableArray<int> _interpolatedStringHandlerArguments = ImmutableArray<int>.Empty; public ImmutableArray<int> InterpolatedStringHandlerArguments { get { VerifySealed(expected: true); return _interpolatedStringHandlerArguments; } set { VerifySealed(expected: false); _interpolatedStringHandlerArguments = value; SetDataStored(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Information decoded from well-known custom attributes applied on a parameter. /// </summary> internal sealed class ParameterWellKnownAttributeData : CommonParameterWellKnownAttributeData { private bool _hasAllowNullAttribute; public bool HasAllowNullAttribute { get { VerifySealed(expected: true); return _hasAllowNullAttribute; } set { VerifySealed(expected: false); _hasAllowNullAttribute = value; SetDataStored(); } } private bool _hasDisallowNullAttribute; public bool HasDisallowNullAttribute { get { VerifySealed(expected: true); return _hasDisallowNullAttribute; } set { VerifySealed(expected: false); _hasDisallowNullAttribute = value; SetDataStored(); } } private bool _hasMaybeNullAttribute; public bool HasMaybeNullAttribute { get { VerifySealed(expected: true); return _hasMaybeNullAttribute; } set { VerifySealed(expected: false); _hasMaybeNullAttribute = value; SetDataStored(); } } private bool? _maybeNullWhenAttribute; public bool? MaybeNullWhenAttribute { get { VerifySealed(expected: true); return _maybeNullWhenAttribute; } set { VerifySealed(expected: false); _maybeNullWhenAttribute = value; SetDataStored(); } } private bool _hasNotNullAttribute; public bool HasNotNullAttribute { get { VerifySealed(expected: true); return _hasNotNullAttribute; } set { VerifySealed(expected: false); _hasNotNullAttribute = value; SetDataStored(); } } private bool? _notNullWhenAttribute; public bool? NotNullWhenAttribute { get { VerifySealed(expected: true); return _notNullWhenAttribute; } set { VerifySealed(expected: false); _notNullWhenAttribute = value; SetDataStored(); } } private bool? _doesNotReturnIfAttribute; public bool? DoesNotReturnIfAttribute { get { VerifySealed(expected: true); return _doesNotReturnIfAttribute; } set { VerifySealed(expected: false); _doesNotReturnIfAttribute = value; SetDataStored(); } } private bool _hasEnumeratorCancellationAttribute; public bool HasEnumeratorCancellationAttribute { get { VerifySealed(expected: true); return _hasEnumeratorCancellationAttribute; } set { VerifySealed(expected: false); _hasEnumeratorCancellationAttribute = value; SetDataStored(); } } private ImmutableHashSet<string> _notNullIfParameterNotNull = ImmutableHashSet<string>.Empty; public ImmutableHashSet<string> NotNullIfParameterNotNull { get { VerifySealed(expected: true); return _notNullIfParameterNotNull; } } public void AddNotNullIfParameterNotNull(string parameterName) { VerifySealed(expected: false); // The common case is zero or one attribute _notNullIfParameterNotNull = _notNullIfParameterNotNull.Add(parameterName); SetDataStored(); } private ImmutableArray<int> _interpolatedStringHandlerArguments = ImmutableArray<int>.Empty; public ImmutableArray<int> InterpolatedStringHandlerArguments { get { VerifySealed(expected: true); return _interpolatedStringHandlerArguments; } set { VerifySealed(expected: false); _interpolatedStringHandlerArguments = value; SetDataStored(); } } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/VisualBasic/Portable/Symbols/NonMissingAssemblySymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Concurrent Imports System.Collections.ObjectModel Imports System.Reflection Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' A <see cref="NonMissingAssemblySymbol"/> is a special kind of <see cref="AssemblySymbol"/> that represents ''' an assembly that is not missing, i.e. the "real" thing. ''' </summary> Friend MustInherit Class NonMissingAssemblySymbol Inherits AssemblySymbol ''' <summary> ''' This is a cache similar to the one used by MetaImport::GetTypeByName ''' in native compiler. The difference is that native compiler pre-populates ''' the cache when it loads types. Here we are populating the cache only ''' with things we looked for, so that next time we are looking for the same ''' thing, the lookup is fast. This cache also takes care of TypeForwarders. ''' Gives about 8% win on subsequent lookups in some scenarios. ''' </summary> ''' <remarks></remarks> Private ReadOnly _emittedNameToTypeMap As New ConcurrentDictionary(Of MetadataTypeName.Key, NamedTypeSymbol)() ''' <summary> ''' The global namespace symbol. Lazily populated on first access. ''' </summary> Private _lazyGlobalNamespace As NamespaceSymbol ''' <summary> ''' Does this symbol represent a missing assembly. ''' </summary> Friend NotOverridable Overrides ReadOnly Property IsMissing As Boolean Get Return False End Get End Property ''' <summary> ''' Gets the merged root namespace that contains all namespaces and types defined in the modules ''' of this assembly. If there is just one module in this assembly, this property just returns the ''' GlobalNamespace of that module. ''' </summary> Public NotOverridable Overrides ReadOnly Property GlobalNamespace As NamespaceSymbol Get If _lazyGlobalNamespace Is Nothing Then Interlocked.CompareExchange(_lazyGlobalNamespace, MergedNamespaceSymbol.CreateGlobalNamespace(Me), Nothing) End If Return _lazyGlobalNamespace End Get End Property ''' <summary> ''' Lookup a top level type referenced from metadata, names should be ''' compared case-sensitively. Detect cycles during lookup. ''' </summary> ''' <param name="emittedName"> ''' Full type name, possibly with generic name mangling. ''' </param> ''' <param name="visitedAssemblies"> ''' List of assemblies lookup has already visited (since type forwarding can introduce cycles). ''' </param> ''' <param name="digThroughForwardedTypes"> ''' Take forwarded types into account. ''' </param> Friend NotOverridable Overrides Function LookupTopLevelMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), digThroughForwardedTypes As Boolean) As NamedTypeSymbol Dim result As NamedTypeSymbol = Nothing ' This is a cache similar to the one used by MetaImport::GetTypeByName ' in native compiler. The difference is that native compiler pre-populates ' the cache when it loads types. Here we are populating the cache only ' with things we looked for, so that next time we are looking for the same ' thing, the lookup is fast. This cache also takes care of TypeForwarders. ' Gives about 8% win on subsequent lookups in some scenarios. ' ' CONSIDER !!! ' ' However, it is questionable how often subsequent lookup by name is going to happen. ' Currently it doesn't happen for TypeDef tokens at all, for TypeRef tokens, the lookup by name ' is done once and the result is cached. So, multiple lookups by name for the same type ' are going to happen only in these cases: ' 1) Resolving GetType() in attribute application, type is encoded by name. ' 2) TypeRef token isn't reused within the same module, i.e. multiple TypeRefs point to the same type. ' 3) Different Module refers to the same type, lookup once per Module (with exception of #2). ' 4) Multitargeting - retargeting the type to a different version of assembly result = LookupTopLevelMetadataTypeInCache(emittedName) If result IsNot Nothing Then ' We only cache result equivalent to digging through type forwarders, which ' might produce a forwarder specific ErrorTypeSymbol. We don't want to ' return that error symbol, unless digThroughForwardedTypes Is true. If digThroughForwardedTypes OrElse (Not result.IsErrorType() AndAlso result.ContainingAssembly Is Me) Then Return result End If ' According to the cache, the type wasn't found, or isn't declared in this assembly (forwarded). Return New MissingMetadataTypeSymbol.TopLevel(Me.Modules(0), emittedName) End If ' Now we will look for the type in each module of the assembly and pick the ' first type we find, this is what native VB compiler does. Dim modules = Me.Modules Dim count As Integer = modules.Length Dim i As Integer = 0 result = modules(i).LookupTopLevelMetadataType(emittedName) If TypeOf result Is MissingMetadataTypeSymbol Then For i = 1 To count - 1 Step 1 Dim newResult = modules(i).LookupTopLevelMetadataType(emittedName) ' Hold on to the first missing type result, unless we found the type. If Not (TypeOf newResult Is MissingMetadataTypeSymbol) Then result = newResult Exit For End If Next End If Dim foundMatchInThisAssembly As Boolean = (i < count) Debug.Assert(Not foundMatchInThisAssembly OrElse result.ContainingAssembly Is Me) If Not foundMatchInThisAssembly AndAlso digThroughForwardedTypes Then ' We didn't find the type Debug.Assert(TypeOf result Is MissingMetadataTypeSymbol) Dim forwarded As NamedTypeSymbol = TryLookupForwardedMetadataTypeWithCycleDetection(emittedName, visitedAssemblies, ignoreCase:=False) If forwarded IsNot Nothing Then result = forwarded End If End If Debug.Assert(result IsNot Nothing) ' Add result of the lookup into the cache If digThroughForwardedTypes OrElse foundMatchInThisAssembly Then CacheTopLevelMetadataType(emittedName, result) End If Return result End Function Friend MustOverride Overrides Function TryLookupForwardedMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), ignoreCase As Boolean) As NamedTypeSymbol ''' <summary> ''' For test purposes only. ''' </summary> Friend Function CachedTypeByEmittedName(emittedname As String) As NamedTypeSymbol Dim mdName = MetadataTypeName.FromFullName(emittedname) Return _emittedNameToTypeMap(mdName.ToKey()) End Function ''' <summary> ''' For test purposes only. ''' </summary> Friend ReadOnly Property EmittedNameToTypeMapCount As Integer Get Return _emittedNameToTypeMap.Count End Get End Property Private Function LookupTopLevelMetadataTypeInCache( ByRef emittedName As MetadataTypeName ) As NamedTypeSymbol Dim result As NamedTypeSymbol = Nothing If Me._emittedNameToTypeMap.TryGetValue(emittedName.ToKey(), result) Then Return result End If Return Nothing End Function Private Sub CacheTopLevelMetadataType( ByRef emittedName As MetadataTypeName, result As NamedTypeSymbol ) Dim result1 As NamedTypeSymbol = Nothing result1 = Me._emittedNameToTypeMap.GetOrAdd(emittedName.ToKey(), result) Debug.Assert(result1.Equals(result)) ' object identity may differ in error cases End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Concurrent Imports System.Collections.ObjectModel Imports System.Reflection Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' A <see cref="NonMissingAssemblySymbol"/> is a special kind of <see cref="AssemblySymbol"/> that represents ''' an assembly that is not missing, i.e. the "real" thing. ''' </summary> Friend MustInherit Class NonMissingAssemblySymbol Inherits AssemblySymbol ''' <summary> ''' This is a cache similar to the one used by MetaImport::GetTypeByName ''' in native compiler. The difference is that native compiler pre-populates ''' the cache when it loads types. Here we are populating the cache only ''' with things we looked for, so that next time we are looking for the same ''' thing, the lookup is fast. This cache also takes care of TypeForwarders. ''' Gives about 8% win on subsequent lookups in some scenarios. ''' </summary> ''' <remarks></remarks> Private ReadOnly _emittedNameToTypeMap As New ConcurrentDictionary(Of MetadataTypeName.Key, NamedTypeSymbol)() ''' <summary> ''' The global namespace symbol. Lazily populated on first access. ''' </summary> Private _lazyGlobalNamespace As NamespaceSymbol ''' <summary> ''' Does this symbol represent a missing assembly. ''' </summary> Friend NotOverridable Overrides ReadOnly Property IsMissing As Boolean Get Return False End Get End Property ''' <summary> ''' Gets the merged root namespace that contains all namespaces and types defined in the modules ''' of this assembly. If there is just one module in this assembly, this property just returns the ''' GlobalNamespace of that module. ''' </summary> Public NotOverridable Overrides ReadOnly Property GlobalNamespace As NamespaceSymbol Get If _lazyGlobalNamespace Is Nothing Then Interlocked.CompareExchange(_lazyGlobalNamespace, MergedNamespaceSymbol.CreateGlobalNamespace(Me), Nothing) End If Return _lazyGlobalNamespace End Get End Property ''' <summary> ''' Lookup a top level type referenced from metadata, names should be ''' compared case-sensitively. Detect cycles during lookup. ''' </summary> ''' <param name="emittedName"> ''' Full type name, possibly with generic name mangling. ''' </param> ''' <param name="visitedAssemblies"> ''' List of assemblies lookup has already visited (since type forwarding can introduce cycles). ''' </param> ''' <param name="digThroughForwardedTypes"> ''' Take forwarded types into account. ''' </param> Friend NotOverridable Overrides Function LookupTopLevelMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), digThroughForwardedTypes As Boolean) As NamedTypeSymbol Dim result As NamedTypeSymbol = Nothing ' This is a cache similar to the one used by MetaImport::GetTypeByName ' in native compiler. The difference is that native compiler pre-populates ' the cache when it loads types. Here we are populating the cache only ' with things we looked for, so that next time we are looking for the same ' thing, the lookup is fast. This cache also takes care of TypeForwarders. ' Gives about 8% win on subsequent lookups in some scenarios. ' ' CONSIDER !!! ' ' However, it is questionable how often subsequent lookup by name is going to happen. ' Currently it doesn't happen for TypeDef tokens at all, for TypeRef tokens, the lookup by name ' is done once and the result is cached. So, multiple lookups by name for the same type ' are going to happen only in these cases: ' 1) Resolving GetType() in attribute application, type is encoded by name. ' 2) TypeRef token isn't reused within the same module, i.e. multiple TypeRefs point to the same type. ' 3) Different Module refers to the same type, lookup once per Module (with exception of #2). ' 4) Multitargeting - retargeting the type to a different version of assembly result = LookupTopLevelMetadataTypeInCache(emittedName) If result IsNot Nothing Then ' We only cache result equivalent to digging through type forwarders, which ' might produce a forwarder specific ErrorTypeSymbol. We don't want to ' return that error symbol, unless digThroughForwardedTypes Is true. If digThroughForwardedTypes OrElse (Not result.IsErrorType() AndAlso result.ContainingAssembly Is Me) Then Return result End If ' According to the cache, the type wasn't found, or isn't declared in this assembly (forwarded). Return New MissingMetadataTypeSymbol.TopLevel(Me.Modules(0), emittedName) End If ' Now we will look for the type in each module of the assembly and pick the ' first type we find, this is what native VB compiler does. Dim modules = Me.Modules Dim count As Integer = modules.Length Dim i As Integer = 0 result = modules(i).LookupTopLevelMetadataType(emittedName) If TypeOf result Is MissingMetadataTypeSymbol Then For i = 1 To count - 1 Step 1 Dim newResult = modules(i).LookupTopLevelMetadataType(emittedName) ' Hold on to the first missing type result, unless we found the type. If Not (TypeOf newResult Is MissingMetadataTypeSymbol) Then result = newResult Exit For End If Next End If Dim foundMatchInThisAssembly As Boolean = (i < count) Debug.Assert(Not foundMatchInThisAssembly OrElse result.ContainingAssembly Is Me) If Not foundMatchInThisAssembly AndAlso digThroughForwardedTypes Then ' We didn't find the type Debug.Assert(TypeOf result Is MissingMetadataTypeSymbol) Dim forwarded As NamedTypeSymbol = TryLookupForwardedMetadataTypeWithCycleDetection(emittedName, visitedAssemblies, ignoreCase:=False) If forwarded IsNot Nothing Then result = forwarded End If End If Debug.Assert(result IsNot Nothing) ' Add result of the lookup into the cache If digThroughForwardedTypes OrElse foundMatchInThisAssembly Then CacheTopLevelMetadataType(emittedName, result) End If Return result End Function Friend MustOverride Overrides Function TryLookupForwardedMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), ignoreCase As Boolean) As NamedTypeSymbol ''' <summary> ''' For test purposes only. ''' </summary> Friend Function CachedTypeByEmittedName(emittedname As String) As NamedTypeSymbol Dim mdName = MetadataTypeName.FromFullName(emittedname) Return _emittedNameToTypeMap(mdName.ToKey()) End Function ''' <summary> ''' For test purposes only. ''' </summary> Friend ReadOnly Property EmittedNameToTypeMapCount As Integer Get Return _emittedNameToTypeMap.Count End Get End Property Private Function LookupTopLevelMetadataTypeInCache( ByRef emittedName As MetadataTypeName ) As NamedTypeSymbol Dim result As NamedTypeSymbol = Nothing If Me._emittedNameToTypeMap.TryGetValue(emittedName.ToKey(), result) Then Return result End If Return Nothing End Function Private Sub CacheTopLevelMetadataType( ByRef emittedName As MetadataTypeName, result As NamedTypeSymbol ) Dim result1 As NamedTypeSymbol = Nothing result1 = Me._emittedNameToTypeMap.GetOrAdd(emittedName.ToKey(), result) Debug.Assert(result1.Equals(result)) ' object identity may differ in error cases End Sub End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/EditorFeatures/CSharp/xlf/CSharpEditorResources.it.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="it" original="../CSharpEditorResources.resx"> <body> <trans-unit id="Add_Missing_Usings_on_Paste"> <source>Add Missing Usings on Paste</source> <target state="translated">Aggiungi using mancanti dopo operazione Incolla</target> <note>"usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Adding_missing_usings"> <source>Adding missing usings...</source> <target state="translated">Aggiunta di using mancanti...</target> <note>Shown in a thread await dialog. "usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value"> <source>Avoid expression statements that implicitly ignore value</source> <target state="translated">Evita le istruzioni di espressione che ignorano il valore in modo implicito</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_value_assignments"> <source>Avoid unused value assignments</source> <target state="translated">Evita le assegnazioni di valori inutilizzati</target> <note /> </trans-unit> <trans-unit id="Chosen_version_0"> <source>Chosen version: '{0}'</source> <target state="translated">Versione selezionata: '{0}'</target> <note /> </trans-unit> <trans-unit id="Complete_statement_on_semicolon"> <source>Complete statement on ;</source> <target state="translated">Completa l'istruzione in corrispondenza di ;</target> <note /> </trans-unit> <trans-unit id="Could_not_find_by_name_0"> <source>Could not find by name: '{0}'</source> <target state="translated">Non è stato possibile eseguire la ricerca per nome: '{0}'</target> <note /> </trans-unit> <trans-unit id="Decompilation_log"> <source>Decompilation log</source> <target state="translated">Log di decompilazione</target> <note /> </trans-unit> <trans-unit id="Discard"> <source>Discard</source> <target state="translated">Scarta</target> <note /> </trans-unit> <trans-unit id="Elsewhere"> <source>Elsewhere</source> <target state="translated">Altrove</target> <note /> </trans-unit> <trans-unit id="Fix_interpolated_verbatim_string"> <source>Fix interpolated verbatim string</source> <target state="translated">Correggi stringa verbatim interpolata</target> <note /> </trans-unit> <trans-unit id="For_built_in_types"> <source>For built-in types</source> <target state="translated">Per tipi predefiniti</target> <note /> </trans-unit> <trans-unit id="Found_0_assemblies_for_1"> <source>Found '{0}' assemblies for '{1}':</source> <target state="translated">Sono stati trovati '{0}' assembly per '{1}':</target> <note /> </trans-unit> <trans-unit id="Found_exact_match_0"> <source>Found exact match: '{0}'</source> <target state="translated">È stata trovata una corrispondenza esatta: '{0}'</target> <note /> </trans-unit> <trans-unit id="Found_higher_version_match_0"> <source>Found higher version match: '{0}'</source> <target state="translated">È stata trovata una versione corrispondente successiva: '{0}'</target> <note /> </trans-unit> <trans-unit id="Found_single_assembly_0"> <source>Found single assembly: '{0}'</source> <target state="translated">È stato trovato un solo assembly: '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_Event_Subscription"> <source>Generate Event Subscription</source> <target state="translated">Genera sottoscrizione di eventi</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_in_declaration_statements"> <source>Ignore spaces in declaration statements</source> <target state="translated">Ignora gli spazi nelle istruzioni di dichiarazione</target> <note /> </trans-unit> <trans-unit id="Indent_block_contents"> <source>Indent block contents</source> <target state="translated">Rientra contenuto blocco</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents"> <source>Indent case contents</source> <target state="translated">Rientra contenuto case</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents_when_block"> <source>Indent case contents (when block)</source> <target state="translated">Imposta rientro per contenuto case (quando è un blocco)</target> <note /> </trans-unit> <trans-unit id="Indent_case_labels"> <source>Indent case labels</source> <target state="translated">Rientra etichette case</target> <note /> </trans-unit> <trans-unit id="Indent_open_and_close_braces"> <source>Indent open and close braces</source> <target state="translated">Rientra parentesi graffe di apertura e chiusura</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_cast"> <source>Insert space after cast</source> <target state="translated">Inserisci spazio dopo il cast</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration"> <source>Insert space after colon for base or interface in type declaration</source> <target state="translated">Inserisci spazio dopo i due punti per base o interfaccia nella dichiarazione di tipo</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_comma"> <source>Insert space after comma</source> <target state="translated">Inserisci spazio dopo la virgola</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_dot"> <source>Insert space after dot</source> <target state="translated">Inserisci spazio dopo il punto</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_keywords_in_control_flow_statements"> <source>Insert space after keywords in control flow statements</source> <target state="translated">Inserisci spazio dopo le parole chiave nelle istruzioni del flusso di controllo</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_semicolon_in_for_statement"> <source>Insert space after semicolon in "for" statement</source> <target state="translated">Inserisci spazio dopo il punto e virgola nell'istruzione "for"</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration"> <source>Insert space before colon for base or interface in type declaration</source> <target state="translated">Inserisci spazio prima dei due punti per base o interfaccia nella dichiarazione di tipo</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_comma"> <source>Insert space before comma</source> <target state="translated">Inserisci spazio prima della virgola</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_dot"> <source>Insert space before dot</source> <target state="translated">Inserisci spazio prima del punto</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_open_square_bracket"> <source>Insert space before open square bracket</source> <target state="translated">Inserisci spazio prima della parentesi quadra di apertura</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_semicolon_in_for_statement"> <source>Insert space before semicolon in "for" statement</source> <target state="translated">Inserisci spazio prima del punto e virgola nell'istruzione "for"</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Inserisci spazio tra il nome del metodo e la parentesi di apertura corrispondente</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Inserisci spazio tra il nome del metodo e la parentesi di apertura corrispondente</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_argument_list_parentheses"> <source>Insert space within argument list parentheses</source> <target state="translated">Inserisci spazio tra le parentesi dell'elenco di argomenti</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_argument_list_parentheses"> <source>Insert space within empty argument list parentheses</source> <target state="translated">Inserisci spazio tra le parentesi dell'elenco di argomenti vuoto</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_parameter_list_parentheses"> <source>Insert space within empty parameter list parentheses</source> <target state="translated">Inserisci spazio tra le parentesi dell'elenco di parametri vuoto</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_square_brackets"> <source>Insert space within empty square brackets</source> <target state="translated">Inserisci spazio tra parentesi quadre vuote</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parameter_list_parentheses"> <source>Insert space within parameter list parentheses</source> <target state="translated">Inserisci spazio tra le parentesi dell'elenco di parametri</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_expressions"> <source>Insert space within parentheses of expressions</source> <target state="translated">Inserisci spazio tra le parentesi delle espressioni</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_type_casts"> <source>Insert space within parentheses of type casts</source> <target state="translated">Inserisci spazio tra le parentesi dei cast di tipo</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements"> <source>Insert spaces within parentheses of control flow statements</source> <target state="translated">Inserisci spazi all'interno delle parentesi delle istruzioni del flusso di controllo</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_square_brackets"> <source>Insert spaces within square brackets</source> <target state="translated">Inserisci spazi tra parentesi quadre</target> <note /> </trans-unit> <trans-unit id="Inside_namespace"> <source>Inside namespace</source> <target state="translated">All'interno di namespace</target> <note /> </trans-unit> <trans-unit id="Label_Indentation"> <source>Label Indentation</source> <target state="translated">Rientro etichetta</target> <note /> </trans-unit> <trans-unit id="Leave_block_on_single_line"> <source>Leave block on single line</source> <target state="translated">Lascia blocco su una sola riga</target> <note /> </trans-unit> <trans-unit id="Leave_statements_and_member_declarations_on_the_same_line"> <source>Leave statements and member declarations on the same line</source> <target state="translated">Lascia istruzioni e dichiarazioni di membri sulla stessa riga</target> <note /> </trans-unit> <trans-unit id="Load_from_0"> <source>Load from: '{0}'</source> <target state="translated">Carica da: '{0}'</target> <note /> </trans-unit> <trans-unit id="Module_not_found"> <source>Module not found!</source> <target state="translated">Modulo non trovato.</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">Mai</target> <note /> </trans-unit> <trans-unit id="Outside_namespace"> <source>Outside namespace</source> <target state="translated">All'esterno di namespace</target> <note /> </trans-unit> <trans-unit id="Place_catch_on_new_line"> <source>Place "catch" on new line</source> <target state="translated">Inserisci "catch" in una nuova riga</target> <note /> </trans-unit> <trans-unit id="Place_else_on_new_line"> <source>Place "else" on new line</source> <target state="translated">Inserisci "else" in una nuova riga</target> <note /> </trans-unit> <trans-unit id="Place_finally_on_new_line"> <source>Place "finally" on new line</source> <target state="translated">Inserisci "finally" in una nuova riga</target> <note /> </trans-unit> <trans-unit id="Place_members_in_anonymous_types_on_new_line"> <source>Place members in anonymous types on new line</source> <target state="translated">Inserisci membri di tipi anonimi in una nuova riga</target> <note /> </trans-unit> <trans-unit id="Place_members_in_object_initializers_on_new_line"> <source>Place members in object initializers on new line</source> <target state="translated">Inserisci membri di inizializzatori di oggetto in una nuova riga</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods"> <source>Place open brace on new line for anonymous methods</source> <target state="translated">Inserisci parentesi graffa di apertura in una nuova riga per i metodi anonimi</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_types"> <source>Place open brace on new line for anonymous types</source> <target state="translated">Inserisci parentesi graffa di apertura in una nuova riga per i tipi anonimi</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_control_blocks"> <source>Place open brace on new line for control blocks</source> <target state="translated">Inserisci parentesi graffa di apertura su nuova riga per i blocchi di controllo</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_lambda_expression"> <source>Place open brace on new line for lambda expression</source> <target state="translated">Inserisci parentesi graffa di apertura in una nuova riga per espressioni lambda</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions"> <source>Place open brace on new line for methods and local functions</source> <target state="translated">Inserisci parentesi graffa di apertura su nuova riga per metodi e funzioni locali</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers"> <source>Place open brace on new line for object, collection, array, and with initializers</source> <target state="translated">Inserisci parentesi graffa di apertura in una nuova riga per oggetto, raccolta, matrice e inizializzatori with</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events"> <source>Place open brace on new line for properties, indexers, and events</source> <target state="translated">Inserisci parentesi graffa di apertura in una nuova riga per proprietà, indicizzatori ed eventi</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors"> <source>Place open brace on new line for property, indexer, and event accessors</source> <target state="translated">Inserisci parentesi graffa di apertura in una nuova riga per funzioni di accesso a proprietà, indicizzatori ed eventi</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_types"> <source>Place open brace on new line for types</source> <target state="translated">Inserisci parentesi graffa di apertura in una nuova riga per i tipi</target> <note /> </trans-unit> <trans-unit id="Place_query_expression_clauses_on_new_line"> <source>Place query expression clauses on new line</source> <target state="translated">Inserisci clausole di espressione di query in una nuova riga</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_delegate_call"> <source>Prefer conditional delegate call</source> <target state="translated">Preferisci la chiamata al delegato condizionale</target> <note /> </trans-unit> <trans-unit id="Prefer_deconstructed_variable_declaration"> <source>Prefer deconstructed variable declaration</source> <target state="translated">Preferisci dichiarazione di variabile decostruita</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_type"> <source>Prefer explicit type</source> <target state="translated">Preferisci tipo esplicito</target> <note /> </trans-unit> <trans-unit id="Prefer_index_operator"> <source>Prefer index operator</source> <target state="translated">Preferisci operatore di indice</target> <note /> </trans-unit> <trans-unit id="Prefer_inlined_variable_declaration"> <source>Prefer inlined variable declaration</source> <target state="translated">Preferisci dichiarazione di variabile inline</target> <note /> </trans-unit> <trans-unit id="Prefer_local_function_over_anonymous_function"> <source>Prefer local function over anonymous function</source> <target state="translated">Preferisci la funzione locale a quella anonima</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching"> <source>Prefer pattern matching</source> <target state="translated">Preferisci i criteri di ricerca</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_as_with_null_check"> <source>Prefer pattern matching over 'as' with 'null' check</source> <target state="translated">Preferisci criteri di ricerca a 'as' con controllo 'null'</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_is_with_cast_check"> <source>Prefer pattern matching over 'is' with 'cast' check</source> <target state="translated">Preferisci criteri di ricerca a 'is' con controllo 'cast'</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_mixed_type_check"> <source>Prefer pattern matching over mixed type check</source> <target state="translated">Preferisci criteri di ricerca al controllo dei tipi misti</target> <note /> </trans-unit> <trans-unit id="Prefer_range_operator"> <source>Prefer range operator</source> <target state="translated">Preferisci operatore di intervallo</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_default_expression"> <source>Prefer simple 'default' expression</source> <target state="translated">Preferisci l'espressione 'default' semplice</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_using_statement"> <source>Prefer simple 'using' statement</source> <target state="translated">Preferisci l'istruzione 'using' semplice</target> <note /> </trans-unit> <trans-unit id="Prefer_static_local_functions"> <source>Prefer static local functions</source> <target state="translated">Preferisci funzioni locali statiche</target> <note /> </trans-unit> <trans-unit id="Prefer_switch_expression"> <source>Prefer switch expression</source> <target state="translated">Preferisci espressione switch</target> <note /> </trans-unit> <trans-unit id="Prefer_throw_expression"> <source>Prefer throw-expression</source> <target state="translated">Preferisci l'espressione throw</target> <note /> </trans-unit> <trans-unit id="Prefer_var"> <source>Prefer 'var'</source> <target state="translated">Preferisci 'var'</target> <note /> </trans-unit> <trans-unit id="Preferred_using_directive_placement"> <source>Preferred 'using' directive placement</source> <target state="translated">Posizione preferita della direttiva 'using'</target> <note /> </trans-unit> <trans-unit id="Press_TAB_to_insert"> <source> (Press TAB to insert)</source> <target state="translated"> (Premere TAB per inserire)</target> <note /> </trans-unit> <trans-unit id="Resolve_0"> <source>Resolve: '{0}'</source> <target state="translated">Risolvi: '{0}'</target> <note /> </trans-unit> <trans-unit id="Resolve_module_0_of_1"> <source>Resolve module: '{0}' of '{1}'</source> <target state="translated">Risolvi il modulo: '{0}' di '{1}'</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_operators"> <source>Set spacing for operators</source> <target state="translated">Imposta spaziatura per operatori</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">Rientro automatico</target> <note /> </trans-unit> <trans-unit id="Split_string"> <source>Split string</source> <target state="translated">Dividi stringa</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">Variabile locale inutilizzata</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Usa il corpo dell'espressione per le funzioni di accesso</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Usa il corpo dell'espressione per i costruttori</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Usa il corpo dell'espressione per gli indicizzatori</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambdas"> <source>Use expression body for lambdas</source> <target state="translated">Usa il corpo dell'espressione per le espressioni lambda</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Usa corpo dell'espressione per funzioni locali</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Usa il corpo dell'espressione per i metodi</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Usa il corpo dell'espressione per gli operatori</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Usa il corpo dell'espressione per le proprietà</target> <note /> </trans-unit> <trans-unit id="WARN_Version_mismatch_Expected_0_Got_1"> <source>WARN: Version mismatch. Expected: '{0}', Got: '{1}'</source> <target state="translated">AVVISO: versione non corrispondente. Prevista: '{0}'. Ottenuta: '{1}'</target> <note /> </trans-unit> <trans-unit id="When_on_single_line"> <source>When on single line</source> <target state="translated">Se su riga singola</target> <note /> </trans-unit> <trans-unit id="When_possible"> <source>When possible</source> <target state="translated">Quando possibile</target> <note /> </trans-unit> <trans-unit id="When_variable_type_is_apparent"> <source>When variable type is apparent</source> <target state="translated">Quando il tipo della variabile è apparente</target> <note /> </trans-unit> <trans-unit id="_0_items_in_cache"> <source>'{0}' items in cache</source> <target state="translated">'{0}' elementi nella cache</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="it" original="../CSharpEditorResources.resx"> <body> <trans-unit id="Add_Missing_Usings_on_Paste"> <source>Add Missing Usings on Paste</source> <target state="translated">Aggiungi using mancanti dopo operazione Incolla</target> <note>"usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Adding_missing_usings"> <source>Adding missing usings...</source> <target state="translated">Aggiunta di using mancanti...</target> <note>Shown in a thread await dialog. "usings" is a language specific term and should not be localized</note> </trans-unit> <trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value"> <source>Avoid expression statements that implicitly ignore value</source> <target state="translated">Evita le istruzioni di espressione che ignorano il valore in modo implicito</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_value_assignments"> <source>Avoid unused value assignments</source> <target state="translated">Evita le assegnazioni di valori inutilizzati</target> <note /> </trans-unit> <trans-unit id="Chosen_version_0"> <source>Chosen version: '{0}'</source> <target state="translated">Versione selezionata: '{0}'</target> <note /> </trans-unit> <trans-unit id="Complete_statement_on_semicolon"> <source>Complete statement on ;</source> <target state="translated">Completa l'istruzione in corrispondenza di ;</target> <note /> </trans-unit> <trans-unit id="Could_not_find_by_name_0"> <source>Could not find by name: '{0}'</source> <target state="translated">Non è stato possibile eseguire la ricerca per nome: '{0}'</target> <note /> </trans-unit> <trans-unit id="Decompilation_log"> <source>Decompilation log</source> <target state="translated">Log di decompilazione</target> <note /> </trans-unit> <trans-unit id="Discard"> <source>Discard</source> <target state="translated">Scarta</target> <note /> </trans-unit> <trans-unit id="Elsewhere"> <source>Elsewhere</source> <target state="translated">Altrove</target> <note /> </trans-unit> <trans-unit id="Fix_interpolated_verbatim_string"> <source>Fix interpolated verbatim string</source> <target state="translated">Correggi stringa verbatim interpolata</target> <note /> </trans-unit> <trans-unit id="For_built_in_types"> <source>For built-in types</source> <target state="translated">Per tipi predefiniti</target> <note /> </trans-unit> <trans-unit id="Found_0_assemblies_for_1"> <source>Found '{0}' assemblies for '{1}':</source> <target state="translated">Sono stati trovati '{0}' assembly per '{1}':</target> <note /> </trans-unit> <trans-unit id="Found_exact_match_0"> <source>Found exact match: '{0}'</source> <target state="translated">È stata trovata una corrispondenza esatta: '{0}'</target> <note /> </trans-unit> <trans-unit id="Found_higher_version_match_0"> <source>Found higher version match: '{0}'</source> <target state="translated">È stata trovata una versione corrispondente successiva: '{0}'</target> <note /> </trans-unit> <trans-unit id="Found_single_assembly_0"> <source>Found single assembly: '{0}'</source> <target state="translated">È stato trovato un solo assembly: '{0}'</target> <note /> </trans-unit> <trans-unit id="Generate_Event_Subscription"> <source>Generate Event Subscription</source> <target state="translated">Genera sottoscrizione di eventi</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_in_declaration_statements"> <source>Ignore spaces in declaration statements</source> <target state="translated">Ignora gli spazi nelle istruzioni di dichiarazione</target> <note /> </trans-unit> <trans-unit id="Indent_block_contents"> <source>Indent block contents</source> <target state="translated">Rientra contenuto blocco</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents"> <source>Indent case contents</source> <target state="translated">Rientra contenuto case</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents_when_block"> <source>Indent case contents (when block)</source> <target state="translated">Imposta rientro per contenuto case (quando è un blocco)</target> <note /> </trans-unit> <trans-unit id="Indent_case_labels"> <source>Indent case labels</source> <target state="translated">Rientra etichette case</target> <note /> </trans-unit> <trans-unit id="Indent_open_and_close_braces"> <source>Indent open and close braces</source> <target state="translated">Rientra parentesi graffe di apertura e chiusura</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_cast"> <source>Insert space after cast</source> <target state="translated">Inserisci spazio dopo il cast</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration"> <source>Insert space after colon for base or interface in type declaration</source> <target state="translated">Inserisci spazio dopo i due punti per base o interfaccia nella dichiarazione di tipo</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_comma"> <source>Insert space after comma</source> <target state="translated">Inserisci spazio dopo la virgola</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_dot"> <source>Insert space after dot</source> <target state="translated">Inserisci spazio dopo il punto</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_keywords_in_control_flow_statements"> <source>Insert space after keywords in control flow statements</source> <target state="translated">Inserisci spazio dopo le parole chiave nelle istruzioni del flusso di controllo</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_semicolon_in_for_statement"> <source>Insert space after semicolon in "for" statement</source> <target state="translated">Inserisci spazio dopo il punto e virgola nell'istruzione "for"</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration"> <source>Insert space before colon for base or interface in type declaration</source> <target state="translated">Inserisci spazio prima dei due punti per base o interfaccia nella dichiarazione di tipo</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_comma"> <source>Insert space before comma</source> <target state="translated">Inserisci spazio prima della virgola</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_dot"> <source>Insert space before dot</source> <target state="translated">Inserisci spazio prima del punto</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_open_square_bracket"> <source>Insert space before open square bracket</source> <target state="translated">Inserisci spazio prima della parentesi quadra di apertura</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_semicolon_in_for_statement"> <source>Insert space before semicolon in "for" statement</source> <target state="translated">Inserisci spazio prima del punto e virgola nell'istruzione "for"</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Inserisci spazio tra il nome del metodo e la parentesi di apertura corrispondente</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Inserisci spazio tra il nome del metodo e la parentesi di apertura corrispondente</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_argument_list_parentheses"> <source>Insert space within argument list parentheses</source> <target state="translated">Inserisci spazio tra le parentesi dell'elenco di argomenti</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_argument_list_parentheses"> <source>Insert space within empty argument list parentheses</source> <target state="translated">Inserisci spazio tra le parentesi dell'elenco di argomenti vuoto</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_parameter_list_parentheses"> <source>Insert space within empty parameter list parentheses</source> <target state="translated">Inserisci spazio tra le parentesi dell'elenco di parametri vuoto</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_square_brackets"> <source>Insert space within empty square brackets</source> <target state="translated">Inserisci spazio tra parentesi quadre vuote</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parameter_list_parentheses"> <source>Insert space within parameter list parentheses</source> <target state="translated">Inserisci spazio tra le parentesi dell'elenco di parametri</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_expressions"> <source>Insert space within parentheses of expressions</source> <target state="translated">Inserisci spazio tra le parentesi delle espressioni</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_type_casts"> <source>Insert space within parentheses of type casts</source> <target state="translated">Inserisci spazio tra le parentesi dei cast di tipo</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements"> <source>Insert spaces within parentheses of control flow statements</source> <target state="translated">Inserisci spazi all'interno delle parentesi delle istruzioni del flusso di controllo</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_square_brackets"> <source>Insert spaces within square brackets</source> <target state="translated">Inserisci spazi tra parentesi quadre</target> <note /> </trans-unit> <trans-unit id="Inside_namespace"> <source>Inside namespace</source> <target state="translated">All'interno di namespace</target> <note /> </trans-unit> <trans-unit id="Label_Indentation"> <source>Label Indentation</source> <target state="translated">Rientro etichetta</target> <note /> </trans-unit> <trans-unit id="Leave_block_on_single_line"> <source>Leave block on single line</source> <target state="translated">Lascia blocco su una sola riga</target> <note /> </trans-unit> <trans-unit id="Leave_statements_and_member_declarations_on_the_same_line"> <source>Leave statements and member declarations on the same line</source> <target state="translated">Lascia istruzioni e dichiarazioni di membri sulla stessa riga</target> <note /> </trans-unit> <trans-unit id="Load_from_0"> <source>Load from: '{0}'</source> <target state="translated">Carica da: '{0}'</target> <note /> </trans-unit> <trans-unit id="Module_not_found"> <source>Module not found!</source> <target state="translated">Modulo non trovato.</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">Mai</target> <note /> </trans-unit> <trans-unit id="Outside_namespace"> <source>Outside namespace</source> <target state="translated">All'esterno di namespace</target> <note /> </trans-unit> <trans-unit id="Place_catch_on_new_line"> <source>Place "catch" on new line</source> <target state="translated">Inserisci "catch" in una nuova riga</target> <note /> </trans-unit> <trans-unit id="Place_else_on_new_line"> <source>Place "else" on new line</source> <target state="translated">Inserisci "else" in una nuova riga</target> <note /> </trans-unit> <trans-unit id="Place_finally_on_new_line"> <source>Place "finally" on new line</source> <target state="translated">Inserisci "finally" in una nuova riga</target> <note /> </trans-unit> <trans-unit id="Place_members_in_anonymous_types_on_new_line"> <source>Place members in anonymous types on new line</source> <target state="translated">Inserisci membri di tipi anonimi in una nuova riga</target> <note /> </trans-unit> <trans-unit id="Place_members_in_object_initializers_on_new_line"> <source>Place members in object initializers on new line</source> <target state="translated">Inserisci membri di inizializzatori di oggetto in una nuova riga</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods"> <source>Place open brace on new line for anonymous methods</source> <target state="translated">Inserisci parentesi graffa di apertura in una nuova riga per i metodi anonimi</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_types"> <source>Place open brace on new line for anonymous types</source> <target state="translated">Inserisci parentesi graffa di apertura in una nuova riga per i tipi anonimi</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_control_blocks"> <source>Place open brace on new line for control blocks</source> <target state="translated">Inserisci parentesi graffa di apertura su nuova riga per i blocchi di controllo</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_lambda_expression"> <source>Place open brace on new line for lambda expression</source> <target state="translated">Inserisci parentesi graffa di apertura in una nuova riga per espressioni lambda</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions"> <source>Place open brace on new line for methods and local functions</source> <target state="translated">Inserisci parentesi graffa di apertura su nuova riga per metodi e funzioni locali</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers"> <source>Place open brace on new line for object, collection, array, and with initializers</source> <target state="translated">Inserisci parentesi graffa di apertura in una nuova riga per oggetto, raccolta, matrice e inizializzatori with</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events"> <source>Place open brace on new line for properties, indexers, and events</source> <target state="translated">Inserisci parentesi graffa di apertura in una nuova riga per proprietà, indicizzatori ed eventi</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors"> <source>Place open brace on new line for property, indexer, and event accessors</source> <target state="translated">Inserisci parentesi graffa di apertura in una nuova riga per funzioni di accesso a proprietà, indicizzatori ed eventi</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_types"> <source>Place open brace on new line for types</source> <target state="translated">Inserisci parentesi graffa di apertura in una nuova riga per i tipi</target> <note /> </trans-unit> <trans-unit id="Place_query_expression_clauses_on_new_line"> <source>Place query expression clauses on new line</source> <target state="translated">Inserisci clausole di espressione di query in una nuova riga</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_delegate_call"> <source>Prefer conditional delegate call</source> <target state="translated">Preferisci la chiamata al delegato condizionale</target> <note /> </trans-unit> <trans-unit id="Prefer_deconstructed_variable_declaration"> <source>Prefer deconstructed variable declaration</source> <target state="translated">Preferisci dichiarazione di variabile decostruita</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_type"> <source>Prefer explicit type</source> <target state="translated">Preferisci tipo esplicito</target> <note /> </trans-unit> <trans-unit id="Prefer_index_operator"> <source>Prefer index operator</source> <target state="translated">Preferisci operatore di indice</target> <note /> </trans-unit> <trans-unit id="Prefer_inlined_variable_declaration"> <source>Prefer inlined variable declaration</source> <target state="translated">Preferisci dichiarazione di variabile inline</target> <note /> </trans-unit> <trans-unit id="Prefer_local_function_over_anonymous_function"> <source>Prefer local function over anonymous function</source> <target state="translated">Preferisci la funzione locale a quella anonima</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching"> <source>Prefer pattern matching</source> <target state="translated">Preferisci i criteri di ricerca</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_as_with_null_check"> <source>Prefer pattern matching over 'as' with 'null' check</source> <target state="translated">Preferisci criteri di ricerca a 'as' con controllo 'null'</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_is_with_cast_check"> <source>Prefer pattern matching over 'is' with 'cast' check</source> <target state="translated">Preferisci criteri di ricerca a 'is' con controllo 'cast'</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_mixed_type_check"> <source>Prefer pattern matching over mixed type check</source> <target state="translated">Preferisci criteri di ricerca al controllo dei tipi misti</target> <note /> </trans-unit> <trans-unit id="Prefer_range_operator"> <source>Prefer range operator</source> <target state="translated">Preferisci operatore di intervallo</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_default_expression"> <source>Prefer simple 'default' expression</source> <target state="translated">Preferisci l'espressione 'default' semplice</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_using_statement"> <source>Prefer simple 'using' statement</source> <target state="translated">Preferisci l'istruzione 'using' semplice</target> <note /> </trans-unit> <trans-unit id="Prefer_static_local_functions"> <source>Prefer static local functions</source> <target state="translated">Preferisci funzioni locali statiche</target> <note /> </trans-unit> <trans-unit id="Prefer_switch_expression"> <source>Prefer switch expression</source> <target state="translated">Preferisci espressione switch</target> <note /> </trans-unit> <trans-unit id="Prefer_throw_expression"> <source>Prefer throw-expression</source> <target state="translated">Preferisci l'espressione throw</target> <note /> </trans-unit> <trans-unit id="Prefer_var"> <source>Prefer 'var'</source> <target state="translated">Preferisci 'var'</target> <note /> </trans-unit> <trans-unit id="Preferred_using_directive_placement"> <source>Preferred 'using' directive placement</source> <target state="translated">Posizione preferita della direttiva 'using'</target> <note /> </trans-unit> <trans-unit id="Press_TAB_to_insert"> <source> (Press TAB to insert)</source> <target state="translated"> (Premere TAB per inserire)</target> <note /> </trans-unit> <trans-unit id="Resolve_0"> <source>Resolve: '{0}'</source> <target state="translated">Risolvi: '{0}'</target> <note /> </trans-unit> <trans-unit id="Resolve_module_0_of_1"> <source>Resolve module: '{0}' of '{1}'</source> <target state="translated">Risolvi il modulo: '{0}' di '{1}'</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_operators"> <source>Set spacing for operators</source> <target state="translated">Imposta spaziatura per operatori</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">Rientro automatico</target> <note /> </trans-unit> <trans-unit id="Split_string"> <source>Split string</source> <target state="translated">Dividi stringa</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">Variabile locale inutilizzata</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Usa il corpo dell'espressione per le funzioni di accesso</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Usa il corpo dell'espressione per i costruttori</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Usa il corpo dell'espressione per gli indicizzatori</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambdas"> <source>Use expression body for lambdas</source> <target state="translated">Usa il corpo dell'espressione per le espressioni lambda</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Usa corpo dell'espressione per funzioni locali</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Usa il corpo dell'espressione per i metodi</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Usa il corpo dell'espressione per gli operatori</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Usa il corpo dell'espressione per le proprietà</target> <note /> </trans-unit> <trans-unit id="WARN_Version_mismatch_Expected_0_Got_1"> <source>WARN: Version mismatch. Expected: '{0}', Got: '{1}'</source> <target state="translated">AVVISO: versione non corrispondente. Prevista: '{0}'. Ottenuta: '{1}'</target> <note /> </trans-unit> <trans-unit id="When_on_single_line"> <source>When on single line</source> <target state="translated">Se su riga singola</target> <note /> </trans-unit> <trans-unit id="When_possible"> <source>When possible</source> <target state="translated">Quando possibile</target> <note /> </trans-unit> <trans-unit id="When_variable_type_is_apparent"> <source>When variable type is apparent</source> <target state="translated">Quando il tipo della variabile è apparente</target> <note /> </trans-unit> <trans-unit id="_0_items_in_cache"> <source>'{0}' items in cache</source> <target state="translated">'{0}' elementi nella cache</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/EditorFeatures/CSharpTest/TodoComment/NoCompilationTodoCommentTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Implementation.TodoComments; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities.TodoComments; using Microsoft.CodeAnalysis.TodoComments; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TodoComment { [UseExportProvider] public class NoCompilationTodoCommentTests : AbstractTodoCommentTests { protected override TestWorkspace CreateWorkspace(string codeWithMarker) { var workspace = TestWorkspace.CreateWorkspace(XElement.Parse( $@"<Workspace> <Project Language=""NoCompilation""> <Document>{codeWithMarker}</Document> </Project> </Workspace>"), composition: EditorTestCompositions.EditorFeatures.AddParts( typeof(NoCompilationContentTypeDefinitions), typeof(NoCompilationContentTypeLanguageService), typeof(NoCompilationTodoCommentService))); workspace.SetOptions(workspace.Options.WithChangedOption(TodoCommentOptions.TokenList, DefaultTokenList)); return workspace; } [Fact, WorkItem(1192024, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1192024")] public async Task TodoCommentInNoCompilationProject() { var code = @"(* [|Message|] *)"; await TestAsync(code); } } [PartNotDiscoverable] [ExportLanguageService(typeof(ITodoCommentService), language: NoCompilationConstants.LanguageName), Shared] internal class NoCompilationTodoCommentService : ITodoCommentService { [ImportingConstructor] [System.Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NoCompilationTodoCommentService() { } public Task<ImmutableArray<CodeAnalysis.TodoComments.TodoComment>> GetTodoCommentsAsync(Document document, ImmutableArray<TodoCommentDescriptor> commentDescriptors, CancellationToken cancellationToken) { return Task.FromResult(ImmutableArray.Create(new CodeAnalysis.TodoComments.TodoComment(commentDescriptors.First(), "Message", 3))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Implementation.TodoComments; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities.TodoComments; using Microsoft.CodeAnalysis.TodoComments; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TodoComment { [UseExportProvider] public class NoCompilationTodoCommentTests : AbstractTodoCommentTests { protected override TestWorkspace CreateWorkspace(string codeWithMarker) { var workspace = TestWorkspace.CreateWorkspace(XElement.Parse( $@"<Workspace> <Project Language=""NoCompilation""> <Document>{codeWithMarker}</Document> </Project> </Workspace>"), composition: EditorTestCompositions.EditorFeatures.AddParts( typeof(NoCompilationContentTypeDefinitions), typeof(NoCompilationContentTypeLanguageService), typeof(NoCompilationTodoCommentService))); workspace.SetOptions(workspace.Options.WithChangedOption(TodoCommentOptions.TokenList, DefaultTokenList)); return workspace; } [Fact, WorkItem(1192024, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1192024")] public async Task TodoCommentInNoCompilationProject() { var code = @"(* [|Message|] *)"; await TestAsync(code); } } [PartNotDiscoverable] [ExportLanguageService(typeof(ITodoCommentService), language: NoCompilationConstants.LanguageName), Shared] internal class NoCompilationTodoCommentService : ITodoCommentService { [ImportingConstructor] [System.Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NoCompilationTodoCommentService() { } public Task<ImmutableArray<CodeAnalysis.TodoComments.TodoComment>> GetTodoCommentsAsync(Document document, ImmutableArray<TodoCommentDescriptor> commentDescriptors, CancellationToken cancellationToken) { return Task.FromResult(ImmutableArray.Create(new CodeAnalysis.TodoComments.TodoComment(commentDescriptors.First(), "Message", 3))); } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Features/Core/Portable/Navigation/DefaultDocumentNavigationServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Navigation { [ExportWorkspaceServiceFactory(typeof(IDocumentNavigationService), ServiceLayer.Default), Shared] internal sealed class DefaultDocumentNavigationServiceFactory : IWorkspaceServiceFactory { private IDocumentNavigationService _singleton; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultDocumentNavigationServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { if (_singleton == null) { _singleton = new DefaultDocumentNavigationService(); } return _singleton; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Navigation { [ExportWorkspaceServiceFactory(typeof(IDocumentNavigationService), ServiceLayer.Default), Shared] internal sealed class DefaultDocumentNavigationServiceFactory : IWorkspaceServiceFactory { private IDocumentNavigationService _singleton; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultDocumentNavigationServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { if (_singleton == null) { _singleton = new DefaultDocumentNavigationService(); } return _singleton; } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.NamespaceSymbolKey.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class NamespaceSymbolKey { // The containing symbol can be one of many things. // 1) Null when this is the global namespace for a compilation. // 2) The SymbolId for an assembly symbol if this is the global namespace for an // assembly. // 3) The SymbolId for a module symbol if this is the global namespace for a module. // 4) The SymbolId for the containing namespace symbol if this is not a global // namespace. public static void Create(INamespaceSymbol symbol, SymbolKeyWriter visitor) { visitor.WriteString(symbol.MetadataName); if (symbol.ContainingNamespace != null) { visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingNamespace); } else { // A global namespace can either belong to a module or to a compilation. Debug.Assert(symbol.IsGlobalNamespace); switch (symbol.NamespaceKind) { case NamespaceKind.Module: visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingModule); break; case NamespaceKind.Assembly: visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingAssembly); break; case NamespaceKind.Compilation: visitor.WriteBoolean(true); visitor.WriteSymbolKey(null); break; default: throw new NotImplementedException(); } } } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var metadataName = reader.ReadString()!; var isCompilationGlobalNamespace = reader.ReadBoolean(); var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason); if (containingSymbolFailureReason != null) { failureReason = $"({nameof(EventSymbolKey)} {nameof(containingSymbolResolution)} failed -> {containingSymbolFailureReason})"; return default; } if (isCompilationGlobalNamespace) { failureReason = null; return new SymbolKeyResolution(reader.Compilation.GlobalNamespace); } using var result = PooledArrayBuilder<INamespaceSymbol>.GetInstance(); foreach (var container in containingSymbolResolution) { switch (container) { case IAssemblySymbol assembly: Debug.Assert(metadataName == string.Empty); result.AddIfNotNull(assembly.GlobalNamespace); break; case IModuleSymbol module: Debug.Assert(metadataName == string.Empty); result.AddIfNotNull(module.GlobalNamespace); break; case INamespaceSymbol namespaceSymbol: foreach (var member in namespaceSymbol.GetMembers(metadataName)) { if (member is INamespaceSymbol childNamespace) { result.AddIfNotNull(childNamespace); } } break; } } return CreateResolution(result, $"({nameof(NamespaceSymbolKey)} '{metadataName}' not found)", out failureReason); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class NamespaceSymbolKey { // The containing symbol can be one of many things. // 1) Null when this is the global namespace for a compilation. // 2) The SymbolId for an assembly symbol if this is the global namespace for an // assembly. // 3) The SymbolId for a module symbol if this is the global namespace for a module. // 4) The SymbolId for the containing namespace symbol if this is not a global // namespace. public static void Create(INamespaceSymbol symbol, SymbolKeyWriter visitor) { visitor.WriteString(symbol.MetadataName); if (symbol.ContainingNamespace != null) { visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingNamespace); } else { // A global namespace can either belong to a module or to a compilation. Debug.Assert(symbol.IsGlobalNamespace); switch (symbol.NamespaceKind) { case NamespaceKind.Module: visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingModule); break; case NamespaceKind.Assembly: visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingAssembly); break; case NamespaceKind.Compilation: visitor.WriteBoolean(true); visitor.WriteSymbolKey(null); break; default: throw new NotImplementedException(); } } } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var metadataName = reader.ReadString()!; var isCompilationGlobalNamespace = reader.ReadBoolean(); var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason); if (containingSymbolFailureReason != null) { failureReason = $"({nameof(EventSymbolKey)} {nameof(containingSymbolResolution)} failed -> {containingSymbolFailureReason})"; return default; } if (isCompilationGlobalNamespace) { failureReason = null; return new SymbolKeyResolution(reader.Compilation.GlobalNamespace); } using var result = PooledArrayBuilder<INamespaceSymbol>.GetInstance(); foreach (var container in containingSymbolResolution) { switch (container) { case IAssemblySymbol assembly: Debug.Assert(metadataName == string.Empty); result.AddIfNotNull(assembly.GlobalNamespace); break; case IModuleSymbol module: Debug.Assert(metadataName == string.Empty); result.AddIfNotNull(module.GlobalNamespace); break; case INamespaceSymbol namespaceSymbol: foreach (var member in namespaceSymbol.GetMembers(metadataName)) { if (member is INamespaceSymbol childNamespace) { result.AddIfNotNull(childNamespace); } } break; } } return CreateResolution(result, $"({nameof(NamespaceSymbolKey)} '{metadataName}' not found)", out failureReason); } } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.MultipleStatementsCodeGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private partial class CSharpCodeGenerator { public class MultipleStatementsCodeGenerator : CSharpCodeGenerator { public MultipleStatementsCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) : base(insertionPoint, selectionResult, analyzerResult, options, localFunction) { } public static bool IsExtractMethodOnMultipleStatements(SelectionResult code) { var result = (CSharpSelectionResult)code; var first = result.GetFirstStatement(); var last = result.GetLastStatement(); if (first != last) { var firstUnderContainer = result.GetFirstStatementUnderContainer(); var lastUnderContainer = result.GetLastStatementUnderContainer(); Contract.ThrowIfFalse(firstUnderContainer.Parent == lastUnderContainer.Parent); return true; } return false; } protected override SyntaxToken CreateMethodName() => GenerateMethodNameForStatementGenerators(); protected override ImmutableArray<StatementSyntax> GetInitialStatementsForMethodDefinitions() { var firstSeen = false; var firstStatementUnderContainer = CSharpSelectionResult.GetFirstStatementUnderContainer(); var lastStatementUnderContainer = CSharpSelectionResult.GetLastStatementUnderContainer(); using var _ = ArrayBuilder<StatementSyntax>.GetInstance(out var list); foreach (var statement in GetStatementsFromContainer(firstStatementUnderContainer.Parent)) { // reset first seen if (!firstSeen) { firstSeen = statement == firstStatementUnderContainer; } // continue until we see the first statement if (!firstSeen) { continue; } list.Add(statement); // exit if we see last statement if (statement == lastStatementUnderContainer) { break; } } return list.ToImmutable(); } protected override SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken) { var callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken); if (callSiteContainer != null) { return callSiteContainer; } else { var firstStatement = CSharpSelectionResult.GetFirstStatementUnderContainer(); return firstStatement.Parent; } } private static SyntaxList<StatementSyntax> GetStatementsFromContainer(SyntaxNode node) { Contract.ThrowIfNull(node); Contract.ThrowIfFalse(node.IsStatementContainerNode()); return node switch { BlockSyntax blockNode => blockNode.Statements, SwitchSectionSyntax switchSectionNode => switchSectionNode.Statements, _ => throw ExceptionUtilities.UnexpectedValue(node), }; } protected override SyntaxNode GetFirstStatementOrInitializerSelectedAtCallSite() => CSharpSelectionResult.GetFirstStatementUnderContainer(); protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite() => CSharpSelectionResult.GetLastStatementUnderContainer(); protected override Task<SyntaxNode> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken) { var statement = GetStatementContainingInvocationToExtractedMethodWorker(); return Task.FromResult<SyntaxNode>(statement.WithAdditionalAnnotations(CallSiteAnnotation)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private partial class CSharpCodeGenerator { public class MultipleStatementsCodeGenerator : CSharpCodeGenerator { public MultipleStatementsCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) : base(insertionPoint, selectionResult, analyzerResult, options, localFunction) { } public static bool IsExtractMethodOnMultipleStatements(SelectionResult code) { var result = (CSharpSelectionResult)code; var first = result.GetFirstStatement(); var last = result.GetLastStatement(); if (first != last) { var firstUnderContainer = result.GetFirstStatementUnderContainer(); var lastUnderContainer = result.GetLastStatementUnderContainer(); Contract.ThrowIfFalse(firstUnderContainer.Parent == lastUnderContainer.Parent); return true; } return false; } protected override SyntaxToken CreateMethodName() => GenerateMethodNameForStatementGenerators(); protected override ImmutableArray<StatementSyntax> GetInitialStatementsForMethodDefinitions() { var firstSeen = false; var firstStatementUnderContainer = CSharpSelectionResult.GetFirstStatementUnderContainer(); var lastStatementUnderContainer = CSharpSelectionResult.GetLastStatementUnderContainer(); using var _ = ArrayBuilder<StatementSyntax>.GetInstance(out var list); foreach (var statement in GetStatementsFromContainer(firstStatementUnderContainer.Parent)) { // reset first seen if (!firstSeen) { firstSeen = statement == firstStatementUnderContainer; } // continue until we see the first statement if (!firstSeen) { continue; } list.Add(statement); // exit if we see last statement if (statement == lastStatementUnderContainer) { break; } } return list.ToImmutable(); } protected override SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken) { var callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken); if (callSiteContainer != null) { return callSiteContainer; } else { var firstStatement = CSharpSelectionResult.GetFirstStatementUnderContainer(); return firstStatement.Parent; } } private static SyntaxList<StatementSyntax> GetStatementsFromContainer(SyntaxNode node) { Contract.ThrowIfNull(node); Contract.ThrowIfFalse(node.IsStatementContainerNode()); return node switch { BlockSyntax blockNode => blockNode.Statements, SwitchSectionSyntax switchSectionNode => switchSectionNode.Statements, _ => throw ExceptionUtilities.UnexpectedValue(node), }; } protected override SyntaxNode GetFirstStatementOrInitializerSelectedAtCallSite() => CSharpSelectionResult.GetFirstStatementUnderContainer(); protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite() => CSharpSelectionResult.GetLastStatementUnderContainer(); protected override Task<SyntaxNode> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken) { var statement = GetStatementContainingInvocationToExtractedMethodWorker(); return Task.FromResult<SyntaxNode>(statement.WithAdditionalAnnotations(CallSiteAnnotation)); } } } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/VisualStudio/Core/Impl/CodeModel/MethodXml/AbstractMethodXmlBuilder.AttributeInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal abstract partial class AbstractMethodXmlBuilder { private struct AttributeInfo { public static readonly AttributeInfo Empty = new AttributeInfo(); public readonly string Name; public readonly string Value; public AttributeInfo(string name, string value) { this.Name = name; this.Value = value; } public bool IsEmpty { get { return this.Name == null && this.Value == 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.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal abstract partial class AbstractMethodXmlBuilder { private struct AttributeInfo { public static readonly AttributeInfo Empty = new AttributeInfo(); public readonly string Name; public readonly string Value; public AttributeInfo(string name, string value) { this.Name = name; this.Value = value; } public bool IsEmpty { get { return this.Name == null && this.Value == null; } } } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/VisualBasic/Test/Emit/PDB/VisualBasicDeterministicBuildCompilationTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Reflection.Metadata Imports System.Reflection.PortableExecutable Imports System.Text Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.PDB Public Class VisualBasicDeterministicBuildCompilationTests Inherits BasicTestBase Implements IEnumerable(Of Object()) Private Sub VerifyCompilationOptions(originalOptions As VisualBasicCompilationOptions, compilationOptionsBlobReader As BlobReader, emitOptions As EmitOptions, compilation As VisualBasicCompilation) Dim pdbOptions = DeterministicBuildCompilationTestHelpers.ParseCompilationOptions(compilationOptionsBlobReader) DeterministicBuildCompilationTestHelpers.AssertCommonOptions(emitOptions, originalOptions, compilation, pdbOptions) ' See VisualBasicCompilation.SerializeForPdb for options that are added pdbOptions.VerifyPdbOption("checked", originalOptions.CheckOverflow) pdbOptions.VerifyPdbOption("strict", originalOptions.OptionStrict) Assert.Equal(originalOptions.ParseOptions.LanguageVersion.MapSpecifiedToEffectiveVersion().ToDisplayString(), pdbOptions("language-version")) pdbOptions.VerifyPdbOption( "define", originalOptions.ParseOptions.PreprocessorSymbols, isDefault:=Function(v) v.IsEmpty, toString:=Function(v) String.Join(",", v.Select(Function(p) If(p.Value IsNot Nothing, $"{p.Key}=""{p.Value}""", p.Key)))) End Sub Private Sub TestDeterministicCompilationVB(syntaxTrees As SyntaxTree(), compilationOptions As VisualBasicCompilationOptions, emitOptions As EmitOptions, ParamArray metadataReferences() As TestMetadataReferenceInfo) Dim tf = TargetFramework.NetStandard20 Dim originalCompilation = CreateCompilation( syntaxTrees, references:=metadataReferences.SelectAsArray(Of MetadataReference)(Function(r) r.MetadataReference), options:=compilationOptions, targetFramework:=tf) Dim peBlob = originalCompilation.EmitToArray(emitOptions) Using peReader As PEReader = New PEReader(peBlob) Dim entries = peReader.ReadDebugDirectory() AssertEx.Equal({DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.Reproducible, DebugDirectoryEntryType.EmbeddedPortablePdb}, entries.Select(Of DebugDirectoryEntryType)(Function(e) e.Type)) Dim codeView = entries(0) Dim checksum = entries(1) Dim reproducible = entries(2) Dim embedded = entries(3) Using embeddedPdb As MetadataReaderProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded) Dim pdbReader = embeddedPdb.GetMetadataReader() Dim metadataReferenceReader = DeterministicBuildCompilationTestHelpers.GetSingleBlob(PortableCustomDebugInfoKinds.CompilationMetadataReferences, pdbReader) Dim compilationOptionsReader = DeterministicBuildCompilationTestHelpers.GetSingleBlob(PortableCustomDebugInfoKinds.CompilationOptions, pdbReader) VerifyCompilationOptions(compilationOptions, compilationOptionsReader, emitOptions, originalCompilation) DeterministicBuildCompilationTestHelpers.VerifyReferenceInfo(metadataReferences, tf, metadataReferenceReader) End Using End Using End Sub <Theory> <ClassData(GetType(VisualBasicDeterministicBuildCompilationTests))> Public Sub PortablePdb_DeterministicCompilation(compilationOptions As VisualBasicCompilationOptions, emitOptions As EmitOptions) Dim sourceOne = Parse(" Class C1 End Class", fileName:="one.vb", options:=compilationOptions.ParseOptions, encoding:=Encoding.UTF8) Dim sourceTwo = Parse(" Class C2 End Class", fileName:="two.vb", options:=compilationOptions.ParseOptions, encoding:=New UTF8Encoding(encoderShouldEmitUTF8Identifier:=False)) Dim referenceSourceOne = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceSourceTwo = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceOneCompilation = CreateCompilation(referenceSourceOne, options:=TestOptions.DebugDll) Dim referenceTwoCompilation = CreateCompilation(referenceSourceTwo, options:=TestOptions.DebugDll) Using referenceOne As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceOneCompilation, "abcd.dll", EmitOptions.Default) Using referenceTwo As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceTwoCompilation, "efgh.dll", EmitOptions.Default) TestDeterministicCompilationVB({sourceOne, sourceTwo}, compilationOptions, emitOptions, referenceOne, referenceTwo) End Using End Using End Sub <ConditionalTheory(GetType(DesktopOnly))> <ClassData(GetType(VisualBasicDeterministicBuildCompilationTests))> Public Sub PortablePdb_DeterministicCompilationWithSJIS(compilationOptions As VisualBasicCompilationOptions, emitOptions As EmitOptions) Dim sourceOne = Parse(" Class C1 End Class", fileName:="one.vb", options:=compilationOptions.ParseOptions, encoding:=Encoding.UTF8) Dim sourceTwo = Parse(" Class C2 End Class", fileName:="two.vb", options:=compilationOptions.ParseOptions, encoding:=New UTF8Encoding(encoderShouldEmitUTF8Identifier:=False)) Dim sourceThree = Parse(" Class C3 End Class", fileName:="three.vb", options:=compilationOptions.ParseOptions, encoding:=Encoding.GetEncoding(932)) ' SJIS encoding Dim referenceSourceOne = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceSourceTwo = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceOneCompilation = CreateCompilation(referenceSourceOne, options:=TestOptions.DebugDll) Dim referenceTwoCompilation = CreateCompilation(referenceSourceTwo, options:=TestOptions.DebugDll) Using referenceOne As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceOneCompilation, "abcd.dll", EmitOptions.Default) Using referenceTwo As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceTwoCompilation, "efgh.dll", EmitOptions.Default) TestDeterministicCompilationVB({sourceOne, sourceTwo, sourceThree}, compilationOptions, emitOptions, referenceOne, referenceTwo) End Using End Using End Sub Public Iterator Function GetEnumerator() As IEnumerator(Of Object()) Implements IEnumerable(Of Object()).GetEnumerator For Each compilationOptions As VisualBasicCompilationOptions In GetCompilationOptions() For Each emitOptions As EmitOptions In GetEmitOptions() Yield {compilationOptions, emitOptions} Next Next End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return GetEnumerator() End Function Private Iterator Function GetEmitOptions() As IEnumerable(Of EmitOptions) Dim emitOptions = New EmitOptions(debugInformationFormat:=DebugInformationFormat.Embedded) Yield emitOptions Yield emitOptions.WithDefaultSourceFileEncoding(Encoding.UTF8) End Function Private Iterator Function GetCompilationOptions() As IEnumerable(Of VisualBasicCompilationOptions) For Each parseOption As VisualBasicParseOptions In GetParseOptions() ' Provide non default options for to test that they are being serialized ' to the pdb correctly. It needs to produce a compilation to be emitted, but otherwise ' everything should be non-default if possible. Diagnostic settings are ignored ' because they won't be serialized. ' Use constructor that requires all arguments. If New arguments are added, it's possible they need to be ' included in the pdb serialization And added to tests here Dim defaultOptions = New VisualBasicCompilationOptions( OutputKind.DynamicallyLinkedLibrary, moduleName:=Nothing, mainTypeName:=Nothing, scriptClassName:=WellKnownMemberNames.DefaultScriptClassName, globalImports:={GlobalImport.Parse("System")}, rootNamespace:=Nothing, optionStrict:=OptionStrict.Off, optionInfer:=True, optionExplicit:=True, optionCompareText:=False, parseOptions:=parseOption, embedVbCoreRuntime:=False, optimizationLevel:=OptimizationLevel.Debug, checkOverflow:=True, cryptoKeyContainer:=Nothing, cryptoKeyFile:=Nothing, cryptoPublicKey:=Nothing, delaySign:=Nothing, platform:=Platform.AnyCpu, generalDiagnosticOption:=ReportDiagnostic.Default, specificDiagnosticOptions:=Nothing, concurrentBuild:=True, deterministic:=True, xmlReferenceResolver:=Nothing, sourceReferenceResolver:=Nothing, metadataReferenceResolver:=Nothing, assemblyIdentityComparer:=Nothing, strongNameProvider:=Nothing, publicSign:=False, reportSuppressedDiagnostics:=False, metadataImportOptions:=MetadataImportOptions.Public) Yield defaultOptions Yield defaultOptions.WithOptimizationLevel(OptimizationLevel.Release) Yield defaultOptions.WithDebugPlusMode(True) Yield defaultOptions.WithOptimizationLevel(OptimizationLevel.Release).WithDebugPlusMode(True) Next End Function Private Iterator Function GetParseOptions() As IEnumerable(Of VisualBasicParseOptions) Dim parseOptions As New VisualBasicParseOptions() Yield parseOptions Yield parseOptions.WithLanguageVersion(LanguageVersion.VisualBasic15_3) ' https://github.com/dotnet/roslyn/issues/44802 tracks ' enabling preprocessor symbol validation for VB ' Yield parseOptions.WithPreprocessorSymbols({New KeyValuePair(Of String, Object)("TestPre", True), New KeyValuePair(Of String, Object)("TestPreTwo", True)}) End Function End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Reflection.Metadata Imports System.Reflection.PortableExecutable Imports System.Text Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.PDB Public Class VisualBasicDeterministicBuildCompilationTests Inherits BasicTestBase Implements IEnumerable(Of Object()) Private Sub VerifyCompilationOptions(originalOptions As VisualBasicCompilationOptions, compilationOptionsBlobReader As BlobReader, emitOptions As EmitOptions, compilation As VisualBasicCompilation) Dim pdbOptions = DeterministicBuildCompilationTestHelpers.ParseCompilationOptions(compilationOptionsBlobReader) DeterministicBuildCompilationTestHelpers.AssertCommonOptions(emitOptions, originalOptions, compilation, pdbOptions) ' See VisualBasicCompilation.SerializeForPdb for options that are added pdbOptions.VerifyPdbOption("checked", originalOptions.CheckOverflow) pdbOptions.VerifyPdbOption("strict", originalOptions.OptionStrict) Assert.Equal(originalOptions.ParseOptions.LanguageVersion.MapSpecifiedToEffectiveVersion().ToDisplayString(), pdbOptions("language-version")) pdbOptions.VerifyPdbOption( "define", originalOptions.ParseOptions.PreprocessorSymbols, isDefault:=Function(v) v.IsEmpty, toString:=Function(v) String.Join(",", v.Select(Function(p) If(p.Value IsNot Nothing, $"{p.Key}=""{p.Value}""", p.Key)))) End Sub Private Sub TestDeterministicCompilationVB(syntaxTrees As SyntaxTree(), compilationOptions As VisualBasicCompilationOptions, emitOptions As EmitOptions, ParamArray metadataReferences() As TestMetadataReferenceInfo) Dim tf = TargetFramework.NetStandard20 Dim originalCompilation = CreateCompilation( syntaxTrees, references:=metadataReferences.SelectAsArray(Of MetadataReference)(Function(r) r.MetadataReference), options:=compilationOptions, targetFramework:=tf) Dim peBlob = originalCompilation.EmitToArray(emitOptions) Using peReader As PEReader = New PEReader(peBlob) Dim entries = peReader.ReadDebugDirectory() AssertEx.Equal({DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.Reproducible, DebugDirectoryEntryType.EmbeddedPortablePdb}, entries.Select(Of DebugDirectoryEntryType)(Function(e) e.Type)) Dim codeView = entries(0) Dim checksum = entries(1) Dim reproducible = entries(2) Dim embedded = entries(3) Using embeddedPdb As MetadataReaderProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded) Dim pdbReader = embeddedPdb.GetMetadataReader() Dim metadataReferenceReader = DeterministicBuildCompilationTestHelpers.GetSingleBlob(PortableCustomDebugInfoKinds.CompilationMetadataReferences, pdbReader) Dim compilationOptionsReader = DeterministicBuildCompilationTestHelpers.GetSingleBlob(PortableCustomDebugInfoKinds.CompilationOptions, pdbReader) VerifyCompilationOptions(compilationOptions, compilationOptionsReader, emitOptions, originalCompilation) DeterministicBuildCompilationTestHelpers.VerifyReferenceInfo(metadataReferences, tf, metadataReferenceReader) End Using End Using End Sub <Theory> <ClassData(GetType(VisualBasicDeterministicBuildCompilationTests))> Public Sub PortablePdb_DeterministicCompilation(compilationOptions As VisualBasicCompilationOptions, emitOptions As EmitOptions) Dim sourceOne = Parse(" Class C1 End Class", fileName:="one.vb", options:=compilationOptions.ParseOptions, encoding:=Encoding.UTF8) Dim sourceTwo = Parse(" Class C2 End Class", fileName:="two.vb", options:=compilationOptions.ParseOptions, encoding:=New UTF8Encoding(encoderShouldEmitUTF8Identifier:=False)) Dim referenceSourceOne = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceSourceTwo = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceOneCompilation = CreateCompilation(referenceSourceOne, options:=TestOptions.DebugDll) Dim referenceTwoCompilation = CreateCompilation(referenceSourceTwo, options:=TestOptions.DebugDll) Using referenceOne As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceOneCompilation, "abcd.dll", EmitOptions.Default) Using referenceTwo As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceTwoCompilation, "efgh.dll", EmitOptions.Default) TestDeterministicCompilationVB({sourceOne, sourceTwo}, compilationOptions, emitOptions, referenceOne, referenceTwo) End Using End Using End Sub <ConditionalTheory(GetType(DesktopOnly))> <ClassData(GetType(VisualBasicDeterministicBuildCompilationTests))> Public Sub PortablePdb_DeterministicCompilationWithSJIS(compilationOptions As VisualBasicCompilationOptions, emitOptions As EmitOptions) Dim sourceOne = Parse(" Class C1 End Class", fileName:="one.vb", options:=compilationOptions.ParseOptions, encoding:=Encoding.UTF8) Dim sourceTwo = Parse(" Class C2 End Class", fileName:="two.vb", options:=compilationOptions.ParseOptions, encoding:=New UTF8Encoding(encoderShouldEmitUTF8Identifier:=False)) Dim sourceThree = Parse(" Class C3 End Class", fileName:="three.vb", options:=compilationOptions.ParseOptions, encoding:=Encoding.GetEncoding(932)) ' SJIS encoding Dim referenceSourceOne = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceSourceTwo = <compilation> <file name="b.vb"> Public Class SomeClass End Class Public Class SomeOtherClass End Class </file> </compilation> Dim referenceOneCompilation = CreateCompilation(referenceSourceOne, options:=TestOptions.DebugDll) Dim referenceTwoCompilation = CreateCompilation(referenceSourceTwo, options:=TestOptions.DebugDll) Using referenceOne As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceOneCompilation, "abcd.dll", EmitOptions.Default) Using referenceTwo As TestMetadataReferenceInfo = TestMetadataReferenceInfo.Create(referenceTwoCompilation, "efgh.dll", EmitOptions.Default) TestDeterministicCompilationVB({sourceOne, sourceTwo, sourceThree}, compilationOptions, emitOptions, referenceOne, referenceTwo) End Using End Using End Sub Public Iterator Function GetEnumerator() As IEnumerator(Of Object()) Implements IEnumerable(Of Object()).GetEnumerator For Each compilationOptions As VisualBasicCompilationOptions In GetCompilationOptions() For Each emitOptions As EmitOptions In GetEmitOptions() Yield {compilationOptions, emitOptions} Next Next End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return GetEnumerator() End Function Private Iterator Function GetEmitOptions() As IEnumerable(Of EmitOptions) Dim emitOptions = New EmitOptions(debugInformationFormat:=DebugInformationFormat.Embedded) Yield emitOptions Yield emitOptions.WithDefaultSourceFileEncoding(Encoding.UTF8) End Function Private Iterator Function GetCompilationOptions() As IEnumerable(Of VisualBasicCompilationOptions) For Each parseOption As VisualBasicParseOptions In GetParseOptions() ' Provide non default options for to test that they are being serialized ' to the pdb correctly. It needs to produce a compilation to be emitted, but otherwise ' everything should be non-default if possible. Diagnostic settings are ignored ' because they won't be serialized. ' Use constructor that requires all arguments. If New arguments are added, it's possible they need to be ' included in the pdb serialization And added to tests here Dim defaultOptions = New VisualBasicCompilationOptions( OutputKind.DynamicallyLinkedLibrary, moduleName:=Nothing, mainTypeName:=Nothing, scriptClassName:=WellKnownMemberNames.DefaultScriptClassName, globalImports:={GlobalImport.Parse("System")}, rootNamespace:=Nothing, optionStrict:=OptionStrict.Off, optionInfer:=True, optionExplicit:=True, optionCompareText:=False, parseOptions:=parseOption, embedVbCoreRuntime:=False, optimizationLevel:=OptimizationLevel.Debug, checkOverflow:=True, cryptoKeyContainer:=Nothing, cryptoKeyFile:=Nothing, cryptoPublicKey:=Nothing, delaySign:=Nothing, platform:=Platform.AnyCpu, generalDiagnosticOption:=ReportDiagnostic.Default, specificDiagnosticOptions:=Nothing, concurrentBuild:=True, deterministic:=True, xmlReferenceResolver:=Nothing, sourceReferenceResolver:=Nothing, metadataReferenceResolver:=Nothing, assemblyIdentityComparer:=Nothing, strongNameProvider:=Nothing, publicSign:=False, reportSuppressedDiagnostics:=False, metadataImportOptions:=MetadataImportOptions.Public) Yield defaultOptions Yield defaultOptions.WithOptimizationLevel(OptimizationLevel.Release) Yield defaultOptions.WithDebugPlusMode(True) Yield defaultOptions.WithOptimizationLevel(OptimizationLevel.Release).WithDebugPlusMode(True) Next End Function Private Iterator Function GetParseOptions() As IEnumerable(Of VisualBasicParseOptions) Dim parseOptions As New VisualBasicParseOptions() Yield parseOptions Yield parseOptions.WithLanguageVersion(LanguageVersion.VisualBasic15_3) ' https://github.com/dotnet/roslyn/issues/44802 tracks ' enabling preprocessor symbol validation for VB ' Yield parseOptions.WithPreprocessorSymbols({New KeyValuePair(Of String, Object)("TestPre", True), New KeyValuePair(Of String, Object)("TestPreTwo", True)}) End Function End Class
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ITypeImportCompletionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion { internal interface ITypeImportCompletionService : ILanguageService { /// <summary> /// Get completion items for all the accessible top level types from the given project and all its references. /// Each array returned contains all items from one of the reachable entities (i.e. projects and PE references.) /// Returns null if we don't have all the items cached and <paramref name="forceCacheCreation"/> is false. /// </summary> /// <remarks> /// Because items from each entity are cached as a separate array, we simply return them as is instead of an /// aggregated array to avoid unnecessary allocations. /// </remarks> Task<ImmutableArray<ImmutableArray<CompletionItem>>?> GetAllTopLevelTypesAsync( Project project, SyntaxContext syntaxContext, bool forceCacheCreation, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion { internal interface ITypeImportCompletionService : ILanguageService { /// <summary> /// Get completion items for all the accessible top level types from the given project and all its references. /// Each array returned contains all items from one of the reachable entities (i.e. projects and PE references.) /// Returns null if we don't have all the items cached and <paramref name="forceCacheCreation"/> is false. /// </summary> /// <remarks> /// Because items from each entity are cached as a separate array, we simply return them as is instead of an /// aggregated array to avoid unnecessary allocations. /// </remarks> Task<ImmutableArray<ImmutableArray<CompletionItem>>?> GetAllTopLevelTypesAsync( Project project, SyntaxContext syntaxContext, bool forceCacheCreation, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Compilers/VisualBasic/Portable/Scanner/ScannerXml.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. '----------------------------------------------------------------------------- ' Contains the definition of the Scanner, which produces tokens from text '----------------------------------------------------------------------------- Option Compare Binary Option Strict On Imports System.Text Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Imports CoreInternalSyntax = Microsoft.CodeAnalysis.Syntax.InternalSyntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Partial Friend Class Scanner Private Function ScanXmlTrivia(c As Char) As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) Debug.Assert(Not IsScanningXmlDoc) Debug.Assert(c = CARRIAGE_RETURN OrElse c = LINE_FEED OrElse c = " "c OrElse c = CHARACTER_TABULATION) Dim builder = _triviaListPool.Allocate Dim len = 0 Do If c = " "c OrElse c = CHARACTER_TABULATION Then len += 1 ElseIf c = CARRIAGE_RETURN OrElse c = LINE_FEED Then If len > 0 Then builder.Add(MakeWhiteSpaceTrivia(GetText(len))) len = 0 End If builder.Add(ScanNewlineAsTrivia(c)) Else Exit Do End If If Not CanGet(len) Then Exit Do End If c = Peek(len) Loop If len > 0 Then builder.Add(MakeWhiteSpaceTrivia(GetText(len))) len = 0 End If Debug.Assert(builder.Count > 0) Dim result = builder.ToList _triviaListPool.Free(builder) Return result End Function Friend Function ScanXmlElement(Optional state As ScannerState = ScannerState.Element) As SyntaxToken Debug.Assert(state = ScannerState.Element OrElse state = ScannerState.EndElement OrElse state = ScannerState.DocType) ' SHIM If IsScanningXmlDoc Then Return ScanXmlElementInXmlDoc(state) End If ' // Only legal tokens ' // QName ' // / ' // > ' // = ' // Whitespace Dim leadingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing While CanGet() Dim c As Char = Peek() Select Case (c) ' // Whitespace ' // S ::= (#x20 | #x9 | #xD | #xA)+ Case CARRIAGE_RETURN, LINE_FEED ' we should not visit this place twice Debug.Assert(leadingTrivia.Node Is Nothing) Dim offsets = CreateOffsetRestorePoint() leadingTrivia = ScanXmlTrivia(c) If ScanXmlForPossibleStatement(state) Then offsets.Restore() Return SyntaxFactory.Token(Nothing, SyntaxKind.EndOfXmlToken, Nothing, String.Empty) End If Case " "c, CHARACTER_TABULATION ' we should not visit this place twice Debug.Assert(leadingTrivia.Node Is Nothing) leadingTrivia = ScanXmlTrivia(c) Case "/"c If CanGet(1) AndAlso Peek(1) = ">" Then Return XmlMakeEndEmptyElementToken(leadingTrivia) End If Return XmlMakeDivToken(leadingTrivia) Case ">"c ' TODO: this will not consume trailing trivia ' consider cases where this is the last element in the literal. Return XmlMakeGreaterToken(leadingTrivia) Case "="c Return XmlMakeEqualsToken(leadingTrivia) Case "'"c, LEFT_SINGLE_QUOTATION_MARK, RIGHT_SINGLE_QUOTATION_MARK Return XmlMakeSingleQuoteToken(leadingTrivia, c, isOpening:=True) Case """"c, LEFT_DOUBLE_QUOTATION_MARK, RIGHT_DOUBLE_QUOTATION_MARK Return XmlMakeDoubleQuoteToken(leadingTrivia, c, isOpening:=True) Case "<"c If CanGet(1) Then Dim ch As Char = Peek(1) Select Case ch Case "!"c If CanGet(2) Then Select Case (Peek(2)) Case "-"c If NextIs(3, "-"c) Then Return XmlMakeBeginCommentToken(leadingTrivia, s_scanNoTriviaFunc) End If Case "["c If NextAre(3, "CDATA[") Then Return XmlMakeBeginCDataToken(leadingTrivia, s_scanNoTriviaFunc) End If Case "D"c If NextAre(3, "OCTYPE") Then Return XmlMakeBeginDTDToken(leadingTrivia) End If End Select End If Return XmlLessThanExclamationToken(state, leadingTrivia) Case "%"c If NextIs(2, "="c) Then Return XmlMakeBeginEmbeddedToken(leadingTrivia) End If Case "?"c Return XmlMakeBeginProcessingInstructionToken(leadingTrivia, s_scanNoTriviaFunc) Case "/"c Return XmlMakeBeginEndElementToken(leadingTrivia, s_scanNoTriviaFunc) End Select End If Return XmlMakeLessToken(leadingTrivia) Case "?"c If NextIs(1, ">"c) Then ' // Create token for the '?>' termination sequence Return XmlMakeEndProcessingInstructionToken(leadingTrivia) End If Return XmlMakeBadToken(leadingTrivia, 1, ERRID.ERR_IllegalXmlNameChar) Case "("c Return XmlMakeLeftParenToken(leadingTrivia) Case ")"c Return XmlMakeRightParenToken(leadingTrivia) Case "!"c, ";"c, "#"c, ","c, "}"c Return XmlMakeBadToken(leadingTrivia, 1, ERRID.ERR_IllegalXmlNameChar) Case ":"c Return XmlMakeColonToken(leadingTrivia) Case "["c Return XmlMakeOpenBracketToken(state, leadingTrivia) Case "]"c Return XmlMakeCloseBracketToken(state, leadingTrivia) Case Else ' // Because of weak scanning of QName, this state must always handle ' // '=' | '\'' | '"'| '/' | '>' | '<' | '?' Return ScanXmlNcName(leadingTrivia) End Select End While Return MakeEofToken(leadingTrivia) End Function '// '// This is used to detect a VB statement on the next line '// '// NL WS* KW WS* ID | KW '// Example Dim x '// '// For EndElement state only, </x followed by Sub '// NL WS* KW | ID '// Example Sub '// '// NL WS* ID WS* ( '// Example Console.WriteLine ( '// '// NL WS* < ID WS* ( '// Example <ClsCompliant( '// '// NL WS* # WS* KW '// Example #END '// '// NL WS* ' '// Example ' This is a comment Private Function ScanXmlForPossibleStatement(state As ScannerState) As Boolean If Not CanGet() Then Return False End If Dim token As SyntaxToken Dim possibleStatement As Boolean = False Dim offsets = CreateOffsetRestorePoint() Dim c As Char = Peek() Select Case c Case "#"c, FULLWIDTH_NUMBER_SIGN ' Check for preprocessor statement, i.e. # if AdvanceChar(1) token = ScanNextToken(allowLeadingMultilineTrivia:=False) possibleStatement = token.IsKeyword Case "<"c, FULLWIDTH_LESS_THAN_SIGN ' Check for code attribute, i.e < clscompliant ( AdvanceChar(1) Dim leadingTrivia = ScanSingleLineTrivia() ' Use ScanXmlNcName instead of ScanToken because it won't stop on "." token = ScanXmlNcName(leadingTrivia) Dim name As XmlNameTokenSyntax = TryCast(token, XmlNameTokenSyntax) If name IsNot Nothing AndAlso Not name.IsMissing Then If name.PossibleKeywordKind <> SyntaxKind.XmlNameToken Then leadingTrivia = ScanSingleLineTrivia() c = Peek() possibleStatement = c = "("c OrElse c = FULLWIDTH_LEFT_PARENTHESIS End If End If Case Else If IsSingleQuote(c) AndAlso LastToken.Kind <> SyntaxKind.EqualsToken Then ' Check for comment possibleStatement = True Else ' Check for statement or call Dim leadingTrivia = ScanSingleLineTrivia() ' Use ScanXmlNcName instead of ScanToken because it won't stop on "." token = ScanXmlNcName(leadingTrivia) Dim name As XmlNameTokenSyntax = TryCast(token, XmlNameTokenSyntax) If name IsNot Nothing AndAlso Not token.IsMissing Then If state = ScannerState.EndElement Then possibleStatement = token.Kind = SyntaxKind.XmlNameToken OrElse LastToken.Kind = SyntaxKind.XmlNameToken Exit Select End If ' If there was leading trivia, it must be trivia recognized by VB but not XML. Debug.Assert(Not leadingTrivia.Any() OrElse (IsNewLine(c) AndAlso (c <> CARRIAGE_RETURN) AndAlso (c <> LINE_FEED)) OrElse (IsWhitespace(c) AndAlso Not IsXmlWhitespace(c))) token = ScanNextToken(allowLeadingMultilineTrivia:=False) If name.PossibleKeywordKind = SyntaxKind.XmlNameToken Then possibleStatement = token.Kind = SyntaxKind.OpenParenToken Else possibleStatement = (token.Kind = SyntaxKind.IdentifierToken) OrElse token.IsKeyword End If End If End If End Select offsets.Restore() Return possibleStatement End Function Friend Function ScanXmlContent() As SyntaxToken ' SHIM If IsScanningXmlDoc Then Return ScanXmlContentInXmlDoc() End If ' // [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*) Dim Here As Integer = 0 Dim IsAllWhitespace As Boolean = True ' lets do an unusual peek-behind to make sure we are not restarting after a non-Ws char. If _lineBufferOffset > 0 Then Dim prevChar = Peek(-1) If prevChar <> ">"c AndAlso Not XmlCharType.IsWhiteSpace(prevChar) Then IsAllWhitespace = False End If End If Dim scratch = GetScratch() While CanGet(Here) Dim c As Char = Peek(Here) Select Case (c) Case CARRIAGE_RETURN, LINE_FEED Here = SkipLineBreak(c, Here) scratch.Append(LINE_FEED) Case " "c, CHARACTER_TABULATION scratch.Append(c) Here += 1 Case "&"c If Here <> 0 Then Return XmlMakeTextLiteralToken(Nothing, Here, scratch) End If ' TODO: the entity could be whitespace, do we want to report it as WS? Return ScanXmlReference(Nothing) Case "<"c Dim precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing If Here <> 0 Then If Not IsAllWhitespace Then Return XmlMakeTextLiteralToken(Nothing, Here, scratch) Else scratch.Clear() ' will not use this Here = 0 ' consumed chars. precedingTrivia = ScanXmlTrivia(Peek) End If End If Debug.Assert(Here = 0) If CanGet(1) Then Dim ch As Char = Peek(1) Select Case ch Case "!"c If CanGet(2) Then Select Case (Peek(2)) Case "-"c If NextIs(3, "-"c) Then Return XmlMakeBeginCommentToken(precedingTrivia, s_scanNoTriviaFunc) End If Case "["c If NextAre(3, "CDATA[") Then Return XmlMakeBeginCDataToken(precedingTrivia, s_scanNoTriviaFunc) End If Case "D"c If NextAre(3, "OCTYPE") Then Return XmlMakeBeginDTDToken(precedingTrivia) End If End Select End If Case "%"c If NextIs(2, "="c) Then Return XmlMakeBeginEmbeddedToken(precedingTrivia) End If Case "?"c Return XmlMakeBeginProcessingInstructionToken(precedingTrivia, s_scanNoTriviaFunc) Case "/"c Return XmlMakeBeginEndElementToken(precedingTrivia, s_scanNoTriviaFunc) End Select End If Return XmlMakeLessToken(precedingTrivia) Case "]"c If NextAre(Here + 1, "]>") Then ' // If valid characters found then return them. If Here <> 0 Then Return XmlMakeTextLiteralToken(Nothing, Here, scratch) End If ' // Create an invalid character data token for the illegal ']]>' sequence Return XmlMakeTextLiteralToken(Nothing, 3, ERRID.ERR_XmlEndCDataNotAllowedInContent) End If GoTo ScanChars Case "#"c ' // Even though # is valid in content, abort xml scanning if the m_State shows and error ' // and the line begins with NL WS* # WS* KW 'TODO: error recovery - how can we do this? 'If m_State.m_IsXmlError Then ' MakeXmlCharToken(tokens.tkXmlCharData, Here - m_InputStreamPosition, IsAllWhitespace) ' m_InputStreamPosition = Here ' Dim sharp As Token = MakeToken(tokens.tkSharp, 1) ' m_InputStreamPosition += 1 ' While (m_InputStream(m_InputStreamPosition) = " "c OrElse m_InputStream(m_InputStreamPosition) = CHARACTER_TABULATION) ' m_InputStreamPosition += 1 ' End While ' ScanXmlQName() ' Dim restart As Token = CheckXmlForStatement() ' If restart IsNot Nothing Then ' ' // Abort Xml - Found Keyword space at the beginning of the line ' AbandonTokens(restart) ' m_State.Init(LexicalState.VB) ' MakeToken(tokens.tkXmlAbort, 0) ' Return ' End If ' AbandonTokens(sharp) ' Here = m_InputStreamPosition 'End If GoTo ScanChars Case "%"c 'TODO: error recovery. We cannot do this. 'If there is all whitespace after ">", it will be scanned as insignificant, 'but in this case it is significant. 'Also as far as I can see Dev10 does not resync on "%>" text anyways. '' // Even though %> is valid in pcdata. When inside of an embedded expression '' // return this sequence separately so that the xml literal completion code can '' // easily detect the end of an embedded expression that may be temporarily hidden '' // by a new element. i.e. <%= <a> %> 'If CanGetCharAtOffset(Here + 1) AndAlso _ ' PeekAheadChar(Here + 1) = ">"c Then ' ' // If valid characters found then return them. ' If Here <> 0 Then ' Return XmlMakeCharDataToken(Nothing, Here, New String(value.ToArray)) ' End If ' ' // Create a special pcdata token for the possible tkEndXmlEmbedded ' Return XmlMakeCharDataToken(Nothing, 2, "%>") 'Else ' IsAllWhitespace = False ' value.Add("%"c) ' Here += 1 'End If 'Continue While GoTo ScanChars Case Else ScanChars: ' // Check characters are valid IsAllWhitespace = False Dim xmlCh = ScanXmlChar(Here) If xmlCh.Length = 0 Then ' bad char If Here > 0 Then Return XmlMakeTextLiteralToken(Nothing, Here, scratch) Else Return XmlMakeBadToken(Nothing, 1, ERRID.ERR_IllegalChar) End If End If xmlCh.AppendTo(scratch) Here += xmlCh.Length End Select End While ' no more chars If Here > 0 Then Return XmlMakeTextLiteralToken(Nothing, Here, scratch) Else Return MakeEofToken() End If End Function Friend Function ScanXmlComment() As SyntaxToken ' // [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->' Dim precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing If IsScanningXmlDoc AndAlso IsAtNewLine() Then Dim xDocTrivia = ScanXmlDocTrivia() If xDocTrivia Is Nothing Then Return MakeEofToken() ' XmlDoc lines must start with XmlDocTrivia End If precedingTrivia = xDocTrivia End If Dim Here = 0 While CanGet(Here) Dim c As Char = Peek(Here) Select Case (c) Case CARRIAGE_RETURN, LINE_FEED Return XmlMakeCommentToken(precedingTrivia, Here + LengthOfLineBreak(c, Here)) Case "-"c If NextIs(Here + 1, "-"c) Then ' // --> terminates an Xml comment but otherwise -- is an illegal character sequence. ' // The scanner will always returns "--" as a separate comment data string and the ' // the semantics will error if '--' is ever found. ' // Return valid characters up to the -- If Here > 0 Then Return XmlMakeCommentToken(precedingTrivia, Here) End If If CanGet(Here + 2) Then c = Peek(Here + 2) Here += 2 ' // if > is not found then this is an error. Return the -- string If c <> ">"c Then Return XmlMakeCommentToken(precedingTrivia, 2) ' TODO: we cannot do the following ' // For better error recovery, allow -> to terminate the comment. ' // This works because the -> terminates only when the invalid -- ' // is returned. 'If Here + 1 < m_InputStreamEnd AndAlso _ ' m_InputStream(Here) = "-"c AndAlso _ ' m_InputStream(Here + 1) = ">"c Then ' Here += 1 'Else ' Continue While 'End If Else Return XmlMakeEndCommentToken(precedingTrivia) End If End If End If GoTo ScanChars Case Else ScanChars: Dim xmlCh = ScanXmlChar(Here) If xmlCh.Length <> 0 Then Here += xmlCh.Length Continue While End If ' bad char If Here > 0 Then Return XmlMakeCommentToken(precedingTrivia, Here) Else Return XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalChar) End If End Select End While ' no more chars If Here > 0 Then Return XmlMakeCommentToken(precedingTrivia, Here) Else Return MakeEofToken(precedingTrivia) End If End Function Friend Function ScanXmlCData() As SyntaxToken ' // [18] CDSect ::= CDStart CData CDEnd ' // [19] CDStart ::= '<![CDATA[' ' // [20] CData ::= (Char* - (Char* ']]>' Char*)) ' // [21] CDEnd ::= ']]>' Dim precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing If IsScanningXmlDoc AndAlso IsAtNewLine() Then Dim xDocTrivia = ScanXmlDocTrivia() If xDocTrivia Is Nothing Then Return MakeEofToken() ' XmlDoc lines must start with XmlDocTrivia End If precedingTrivia = xDocTrivia End If Dim scratch = GetScratch() Dim Here = 0 While CanGet(Here) Dim c As Char = Peek(Here) Select Case (c) Case CARRIAGE_RETURN, LINE_FEED Here = SkipLineBreak(c, Here) scratch.Append(LINE_FEED) Return XmlMakeCDataToken(precedingTrivia, Here, scratch) Case "]"c If NextAre(Here + 1, "]>") Then '// If valid characters found then return them. If Here <> 0 Then Return XmlMakeCDataToken(precedingTrivia, Here, scratch) End If ' // Create token for ']]>' sequence Return XmlMakeEndCDataToken(precedingTrivia) End If GoTo ScanChars Case Else ScanChars: Dim xmlCh = ScanXmlChar(Here) If xmlCh.Length = 0 Then ' bad char If Here > 0 Then Return XmlMakeCDataToken(precedingTrivia, Here, scratch) Else Return XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalChar) End If End If xmlCh.AppendTo(scratch) Here += xmlCh.Length End Select End While ' no more chars If Here > 0 Then Return XmlMakeCDataToken(precedingTrivia, Here, scratch) Else Return MakeEofToken(precedingTrivia) End If End Function Friend Function ScanXmlPIData(state As ScannerState) As SyntaxToken ' SHIM If IsScanningXmlDoc Then Return ScanXmlPIDataInXmlDoc(state) End If ' // Scan the PI data after the white space ' // [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>' ' // [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l')) Debug.Assert(state = ScannerState.StartProcessingInstruction OrElse state = ScannerState.ProcessingInstruction) Dim precedingTrivia = _triviaListPool.Allocate(Of VisualBasicSyntaxNode)() Dim result As SyntaxToken If state = ScannerState.StartProcessingInstruction AndAlso CanGet() Then ' // Whitespace ' // S ::= (#x20 | #x9 | #xD | #xA)+ Dim c = Peek() Select Case c Case CARRIAGE_RETURN, LINE_FEED, " "c, CHARACTER_TABULATION Dim wsTrivia = ScanXmlTrivia(c) precedingTrivia.AddRange(wsTrivia) End Select End If Dim Here = 0 While CanGet(Here) Dim c As Char = Peek(Here) Select Case (c) Case CARRIAGE_RETURN, LINE_FEED result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here + LengthOfLineBreak(c, Here)) GoTo CleanUp Case "?"c If NextIs(Here + 1, ">"c) Then '// If valid characters found then return them. If Here <> 0 Then result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here) GoTo CleanUp End If ' // Create token for the '?>' termination sequence result = XmlMakeEndProcessingInstructionToken(precedingTrivia.ToList) GoTo CleanUp End If GoTo ScanChars Case Else ScanChars: Dim xmlCh = ScanXmlChar(Here) If xmlCh.Length > 0 Then Here += xmlCh.Length Continue While End If ' bad char If Here <> 0 Then result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here) GoTo CleanUp Else result = XmlMakeBadToken(precedingTrivia.ToList, 1, ERRID.ERR_IllegalChar) GoTo CleanUp End If End Select End While ' no more chars If Here > 0 Then result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here) Else result = MakeEofToken(precedingTrivia.ToList) End If CleanUp: _triviaListPool.Free(precedingTrivia) Return result End Function Friend Function ScanXmlMisc() As SyntaxToken Debug.Assert(Not IsScanningXmlDoc) ' // Misc ::= Comment | PI | S Dim precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing While CanGet() Dim c As Char = Peek() Select Case (c) ' // Whitespace ' // S ::= (#x20 | #x9 | #xD | #xA)+ Case CARRIAGE_RETURN, LINE_FEED, " "c, CHARACTER_TABULATION ' we should not visit this place twice Debug.Assert(Not precedingTrivia.Any) precedingTrivia = ScanXmlTrivia(c) Case "<"c If CanGet(1) Then Dim ch As Char = Peek(1) Select Case ch Case "!"c If NextAre(2, "--") Then Return XmlMakeBeginCommentToken(precedingTrivia, s_scanNoTriviaFunc) ElseIf NextAre(2, "DOCTYPE") Then Return XmlMakeBeginDTDToken(precedingTrivia) End If Case "%"c If NextIs(2, "="c) Then Return XmlMakeBeginEmbeddedToken(precedingTrivia) End If Case "?"c Return XmlMakeBeginProcessingInstructionToken(precedingTrivia, s_scanNoTriviaFunc) End Select End If Return XmlMakeLessToken(precedingTrivia) ' TODO: review ' If Not m_State.m_ScannedElement OrElse c = "?"c OrElse c = "!"c Then ' ' // Remove tEOL from token ring if any exists ' If tEOL IsNot Nothing Then ' m_FirstFreeToken = tEOL ' End If ' m_State.m_LexicalState = LexicalState.XmlMarkup ' MakeToken(tokens.tkLT, 1) ' m_InputStreamPosition += 1 ' Return ' End If 'End If 'm_State.EndXmlState() 'If tEOL IsNot Nothing Then ' tEOL.m_EOL.m_NextLineAlreadyScanned = True 'Else ' MakeToken(tokens.tkLT, 1) ' m_InputStreamPosition += 1 'End If 'Return Case Else Return SyntaxFactory.Token(precedingTrivia.Node, SyntaxKind.EndOfXmlToken, Nothing, String.Empty) End Select End While Return MakeEofToken(precedingTrivia) End Function Friend Function ScanXmlStringUnQuoted() As SyntaxToken If Not CanGet() Then Return MakeEofToken() End If ' This can never happen as this token cannot cross lines. Debug.Assert(Not (IsScanningXmlDoc AndAlso IsAtNewLine())) Dim Here = 0 Dim scratch = GetScratch() While CanGet(Here) Dim c As Char = Peek(Here) Select Case (c) Case CARRIAGE_RETURN, LINE_FEED, " "c, CHARACTER_TABULATION If Here > 0 Then Return XmlMakeAttributeDataToken(Nothing, Here, scratch) Else Return MakeMissingToken(Nothing, SyntaxKind.SingleQuoteToken) End If Case "<"c, ">"c, "?"c ' This cannot be in a string. terminate the string. If Here <> 0 Then Return XmlMakeAttributeDataToken(Nothing, Here, scratch) Else Return MakeMissingToken(Nothing, SyntaxKind.SingleQuoteToken) End If Case "&"c If Here > 0 Then Return XmlMakeAttributeDataToken(Nothing, Here, scratch) Else Return ScanXmlReference(Nothing) End If Case "/"c If NextIs(Here + 1, ">"c) Then If Here <> 0 Then Return XmlMakeAttributeDataToken(Nothing, Here, scratch) Else Return MakeMissingToken(Nothing, SyntaxKind.SingleQuoteToken) End If End If GoTo ScanChars Case Else ScanChars: ' // Check characters are valid Dim xmlCh = ScanXmlChar(Here) If xmlCh.Length = 0 Then ' bad char If Here > 0 Then Return XmlMakeAttributeDataToken(Nothing, Here, scratch) Else Return XmlMakeBadToken(Nothing, 1, ERRID.ERR_IllegalChar) End If End If xmlCh.AppendTo(scratch) Here += xmlCh.Length End Select End While ' no more chars Return XmlMakeAttributeDataToken(Nothing, Here, scratch) End Function Friend Function ScanXmlStringSingle() As SyntaxToken Return ScanXmlString("'"c, "'"c, True) End Function Friend Function ScanXmlStringDouble() As SyntaxToken Return ScanXmlString(""""c, """"c, False) End Function Friend Function ScanXmlStringSmartSingle() As SyntaxToken Return ScanXmlString(RIGHT_SINGLE_QUOTATION_MARK, LEFT_SINGLE_QUOTATION_MARK, True) End Function Friend Function ScanXmlStringSmartDouble() As SyntaxToken Return ScanXmlString(RIGHT_DOUBLE_QUOTATION_MARK, LEFT_DOUBLE_QUOTATION_MARK, False) End Function Friend Function ScanXmlString(terminatingChar As Char, altTerminatingChar As Char, isSingle As Boolean) As SyntaxToken ' TODO: this trivia is used only in XmlDoc. May split the function? Dim precedingTrivia = _triviaListPool.Allocate(Of VisualBasicSyntaxNode)() Dim result As SyntaxToken If IsScanningXmlDoc AndAlso IsAtNewLine() Then Dim xDocTrivia = ScanXmlDocTrivia() If xDocTrivia Is Nothing Then result = MakeEofToken() ' XmlDoc lines must start with XmlDocTrivia GoTo CleanUp End If precedingTrivia.Add(xDocTrivia) End If Dim Here = 0 Dim scratch = GetScratch() While CanGet(Here) Dim c As Char = Peek(Here) If c = terminatingChar Or c = altTerminatingChar Then If Here > 0 Then result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch) GoTo CleanUp Else If isSingle Then result = XmlMakeSingleQuoteToken(precedingTrivia, c, isOpening:=False) Else result = XmlMakeDoubleQuoteToken(precedingTrivia, c, isOpening:=False) End If GoTo CleanUp End If End If Select Case (c) Case CARRIAGE_RETURN, LINE_FEED Here = SkipLineBreak(c, Here) scratch.Append(SPACE) result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch) GoTo CleanUp Case CHARACTER_TABULATION scratch.Append(SPACE) Here += 1 Case "<"c ' This cannot be in a string. terminate the string. If Here > 0 Then result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch) GoTo CleanUp Else ' report unexpected <%= in a special way. If NextAre(1, "%=") Then Dim errEmbedStart = XmlMakeAttributeDataToken(precedingTrivia, 3, "<%=") Dim errEmbedInfo = ErrorFactory.ErrorInfo(ERRID.ERR_QuotedEmbeddedExpression) result = DirectCast(errEmbedStart.SetDiagnostics({errEmbedInfo}), SyntaxToken) GoTo CleanUp End If Dim data = SyntaxFactory.MissingToken(SyntaxKind.SingleQuoteToken) If precedingTrivia.Count > 0 Then data = DirectCast(data.WithLeadingTrivia(precedingTrivia.ToList.Node), SyntaxToken) End If Dim errInfo = ErrorFactory.ErrorInfo(If(isSingle, ERRID.ERR_ExpectedSQuote, ERRID.ERR_ExpectedQuote)) result = DirectCast(data.SetDiagnostics({errInfo}), SyntaxToken) GoTo CleanUp End If Case "&"c If Here > 0 Then result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch) GoTo CleanUp Else result = ScanXmlReference(precedingTrivia) GoTo CleanUp End If Case Else ScanChars: ' // Check characters are valid Dim xmlCh = ScanXmlChar(Here) If xmlCh.Length = 0 Then ' bad char If Here > 0 Then result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch) GoTo CleanUp Else result = XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalChar) GoTo CleanUp End If End If xmlCh.AppendTo(scratch) Here += xmlCh.Length End Select End While ' no more chars If Here > 0 Then result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch) GoTo CleanUp Else result = MakeEofToken(precedingTrivia) GoTo CleanUp End If CleanUp: _triviaListPool.Free(precedingTrivia) Return result End Function ''' <summary> ''' 0 - not a surrogate, 2 - is valid surrogate ''' 1 is an error ''' </summary> Private Function ScanSurrogatePair(c1 As Char, Here As Integer) As XmlCharResult Debug.Assert(Here >= 0) Debug.Assert(CanGet(Here)) Debug.Assert(Peek(Here) = c1) If IsHighSurrogate(c1) AndAlso CanGet(Here + 1) Then Dim c2 = Peek(Here + 1) If IsLowSurrogate(c2) Then Return New XmlCharResult(c1, c2) End If End If Return Nothing End Function ' contains result of Xml char scanning. Friend Structure XmlCharResult Friend ReadOnly Length As Integer Friend ReadOnly Char1 As Char Friend ReadOnly Char2 As Char Friend Sub New(ch As Char) Length = 1 Char1 = ch End Sub Friend Sub New(ch1 As Char, ch2 As Char) Length = 2 Char1 = ch1 Char2 = ch2 End Sub Friend Sub AppendTo(list As StringBuilder) Debug.Assert(list IsNot Nothing) Debug.Assert(Length <> 0) list.Append(Char1) If Length = 2 Then list.Append(Char2) End If End Sub End Structure Private Function ScanXmlChar(Here As Integer) As XmlCharResult Debug.Assert(Here >= 0) Debug.Assert(CanGet(Here)) Dim c = Peek(Here) If Not isValidUtf16(c) Then Return Nothing End If If Not IsSurrogate(c) Then Return New XmlCharResult(c) End If Return ScanSurrogatePair(c, Here) End Function Private Function ScanXmlNcName(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken ' // Scan a non qualified name per Xml Namespace 1.0 ' // [4] NCName ::= (Letter | '_') (NCNameChar)* /* An XML Name, minus the ":" */ ' // This scanner is much looser than a pure Xml scanner. ' // Names are any character up to a separator character from ' // ':' | ' ' | '\t' | '\n' | '\r' | '=' | '\'' | '"'| '/' | '<' | '>' | EOF ' // Each name token will be marked as to whether it contains only valid Xml name characters. Dim Here As Integer = 0 Dim IsIllegalChar As Boolean = False Dim isFirst As Boolean = True Dim err As ERRID = ERRID.ERR_None Dim errUnicode As Integer = 0 Dim errChar As String = Nothing 'TODO - Fix ScanXmlNCName to conform to XML spec instead of old loose scanning. While CanGet(Here) Dim c As Char = Peek(Here) Select Case (c) Case ":"c, " "c, CHARACTER_TABULATION, LINE_FEED, CARRIAGE_RETURN, "="c, "'"c, """"c, "/"c, ">"c, "<"c, "("c, ")"c, "?"c, ";"c, ","c, "}"c GoTo CreateNCNameToken Case Else ' // Invalid Xml name but scan as Xml name anyway ' // Check characters are valid name chars Dim xmlCh = ScanXmlChar(Here) If xmlCh.Length = 0 Then IsIllegalChar = True GoTo CreateNCNameToken Else If err = ERRID.ERR_None Then If xmlCh.Length = 1 Then ' Non surrogate check If isFirst Then err = If(Not isStartNameChar(xmlCh.Char1), ERRID.ERR_IllegalXmlStartNameChar, ERRID.ERR_None) isFirst = False Else err = If(Not isNameChar(xmlCh.Char1), ERRID.ERR_IllegalXmlNameChar, ERRID.ERR_None) End If If err <> ERRID.ERR_None Then errChar = Convert.ToString(xmlCh.Char1) errUnicode = Convert.ToInt32(xmlCh.Char1) End If Else ' Surrogate check Dim unicode = UTF16ToUnicode(xmlCh) If Not (unicode >= &H10000 AndAlso unicode <= &HEFFFF) Then err = ERRID.ERR_IllegalXmlNameChar errChar = {xmlCh.Char1, xmlCh.Char2} errUnicode = unicode End If End If End If Here += xmlCh.Length End If End Select End While CreateNCNameToken: If Here <> 0 Then Dim name = XmlMakeXmlNCNameToken(precedingTrivia, Here) If err <> ERRID.ERR_None Then name = name.WithDiagnostics(ErrorFactory.ErrorInfo(err, errChar, String.Format("&H{0:X}", errUnicode))) End If Return name ElseIf IsIllegalChar Then Return XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalChar) End If Return MakeMissingToken(precedingTrivia, SyntaxKind.XmlNameToken) End Function Private Function ScanXmlReference(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As XmlTextTokenSyntax Debug.Assert(CanGet) Debug.Assert(Peek() = "&"c) ' skip 1 char for "&" If CanGet(1) Then Dim c As Char = Peek(1) Select Case (c) Case "#"c Dim Here = 2 ' skip "&#" Dim result = ScanXmlCharRef(Here) If result.Length <> 0 Then Dim value As String = Nothing If result.Length = 1 Then value = Intern(result.Char1) ElseIf result.Length = 2 Then value = Intern({result.Char1, result.Char2}) End If If CanGet(Here) AndAlso Peek(Here) = ";"c Then Return XmlMakeEntityLiteralToken(precedingTrivia, Here + 1, value) Else Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, Here, value) Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon) Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax) End If End If Case "a"c ' // &amp; ' // &apos; If CanGet(4) AndAlso NextAre(2, "mp") Then If Peek(4) = ";"c Then Return XmlMakeAmpLiteralToken(precedingTrivia) Else Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, 4, "&") Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon) Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax) End If ElseIf CanGet(5) AndAlso NextAre(2, "pos") Then If Peek(5) = ";"c Then Return XmlMakeAposLiteralToken(precedingTrivia) Else Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, 5, "'") Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon) Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax) End If End If Case "l"c ' // &lt; If CanGet(3) AndAlso NextIs(2, "t"c) Then If Peek(3) = ";"c Then Return XmlMakeLtLiteralToken(precedingTrivia) Else Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, 3, "<") Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon) Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax) End If End If Case "g"c ' // &gt; If CanGet(3) AndAlso NextIs(2, "t"c) Then If Peek(3) = ";"c Then Return XmlMakeGtLiteralToken(precedingTrivia) Else Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, 3, ">") Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon) Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax) End If End If Case "q"c ' // &quot; If CanGet(5) AndAlso NextAre(2, "uot") Then If Peek(5) = ";"c Then Return XmlMakeQuotLiteralToken(precedingTrivia) Else Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, 5, """") Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon) Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax) End If End If End Select End If Dim badEntity = XmlMakeEntityLiteralToken(precedingTrivia, 1, "") Dim errInfo = ErrorFactory.ErrorInfo(ERRID.ERR_XmlEntityReference) Return DirectCast(badEntity.SetDiagnostics({errInfo}), XmlTextTokenSyntax) End Function Private Function ScanXmlCharRef(ByRef index As Integer) As XmlCharResult Debug.Assert(index >= 0) If Not CanGet(index) Then Return Nothing End If ' cannot reuse Scratch as this can be used in a nested call. Dim charRefSb As New StringBuilder Dim Here = index Dim ch = Peek(Here) If ch = "x"c Then Here += 1 While CanGet(Here) ch = Peek(Here) If XmlCharType.IsHexDigit(ch) Then charRefSb.Append(ch) Else Exit While End If Here += 1 End While If charRefSb.Length > 0 Then Dim result = HexToUTF16(charRefSb) If result.Length <> 0 Then index = Here End If Return result End If Else While CanGet(Here) ch = Peek(Here) If XmlCharType.IsDigit(ch) Then charRefSb.Append(ch) Else Exit While End If Here += 1 End While If charRefSb.Length > 0 Then Dim result = DecToUTF16(charRefSb) If result.Length <> 0 Then index = Here End If Return result End If End If Return Nothing 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. '----------------------------------------------------------------------------- ' Contains the definition of the Scanner, which produces tokens from text '----------------------------------------------------------------------------- Option Compare Binary Option Strict On Imports System.Text Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Imports CoreInternalSyntax = Microsoft.CodeAnalysis.Syntax.InternalSyntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Partial Friend Class Scanner Private Function ScanXmlTrivia(c As Char) As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) Debug.Assert(Not IsScanningXmlDoc) Debug.Assert(c = CARRIAGE_RETURN OrElse c = LINE_FEED OrElse c = " "c OrElse c = CHARACTER_TABULATION) Dim builder = _triviaListPool.Allocate Dim len = 0 Do If c = " "c OrElse c = CHARACTER_TABULATION Then len += 1 ElseIf c = CARRIAGE_RETURN OrElse c = LINE_FEED Then If len > 0 Then builder.Add(MakeWhiteSpaceTrivia(GetText(len))) len = 0 End If builder.Add(ScanNewlineAsTrivia(c)) Else Exit Do End If If Not CanGet(len) Then Exit Do End If c = Peek(len) Loop If len > 0 Then builder.Add(MakeWhiteSpaceTrivia(GetText(len))) len = 0 End If Debug.Assert(builder.Count > 0) Dim result = builder.ToList _triviaListPool.Free(builder) Return result End Function Friend Function ScanXmlElement(Optional state As ScannerState = ScannerState.Element) As SyntaxToken Debug.Assert(state = ScannerState.Element OrElse state = ScannerState.EndElement OrElse state = ScannerState.DocType) ' SHIM If IsScanningXmlDoc Then Return ScanXmlElementInXmlDoc(state) End If ' // Only legal tokens ' // QName ' // / ' // > ' // = ' // Whitespace Dim leadingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing While CanGet() Dim c As Char = Peek() Select Case (c) ' // Whitespace ' // S ::= (#x20 | #x9 | #xD | #xA)+ Case CARRIAGE_RETURN, LINE_FEED ' we should not visit this place twice Debug.Assert(leadingTrivia.Node Is Nothing) Dim offsets = CreateOffsetRestorePoint() leadingTrivia = ScanXmlTrivia(c) If ScanXmlForPossibleStatement(state) Then offsets.Restore() Return SyntaxFactory.Token(Nothing, SyntaxKind.EndOfXmlToken, Nothing, String.Empty) End If Case " "c, CHARACTER_TABULATION ' we should not visit this place twice Debug.Assert(leadingTrivia.Node Is Nothing) leadingTrivia = ScanXmlTrivia(c) Case "/"c If CanGet(1) AndAlso Peek(1) = ">" Then Return XmlMakeEndEmptyElementToken(leadingTrivia) End If Return XmlMakeDivToken(leadingTrivia) Case ">"c ' TODO: this will not consume trailing trivia ' consider cases where this is the last element in the literal. Return XmlMakeGreaterToken(leadingTrivia) Case "="c Return XmlMakeEqualsToken(leadingTrivia) Case "'"c, LEFT_SINGLE_QUOTATION_MARK, RIGHT_SINGLE_QUOTATION_MARK Return XmlMakeSingleQuoteToken(leadingTrivia, c, isOpening:=True) Case """"c, LEFT_DOUBLE_QUOTATION_MARK, RIGHT_DOUBLE_QUOTATION_MARK Return XmlMakeDoubleQuoteToken(leadingTrivia, c, isOpening:=True) Case "<"c If CanGet(1) Then Dim ch As Char = Peek(1) Select Case ch Case "!"c If CanGet(2) Then Select Case (Peek(2)) Case "-"c If NextIs(3, "-"c) Then Return XmlMakeBeginCommentToken(leadingTrivia, s_scanNoTriviaFunc) End If Case "["c If NextAre(3, "CDATA[") Then Return XmlMakeBeginCDataToken(leadingTrivia, s_scanNoTriviaFunc) End If Case "D"c If NextAre(3, "OCTYPE") Then Return XmlMakeBeginDTDToken(leadingTrivia) End If End Select End If Return XmlLessThanExclamationToken(state, leadingTrivia) Case "%"c If NextIs(2, "="c) Then Return XmlMakeBeginEmbeddedToken(leadingTrivia) End If Case "?"c Return XmlMakeBeginProcessingInstructionToken(leadingTrivia, s_scanNoTriviaFunc) Case "/"c Return XmlMakeBeginEndElementToken(leadingTrivia, s_scanNoTriviaFunc) End Select End If Return XmlMakeLessToken(leadingTrivia) Case "?"c If NextIs(1, ">"c) Then ' // Create token for the '?>' termination sequence Return XmlMakeEndProcessingInstructionToken(leadingTrivia) End If Return XmlMakeBadToken(leadingTrivia, 1, ERRID.ERR_IllegalXmlNameChar) Case "("c Return XmlMakeLeftParenToken(leadingTrivia) Case ")"c Return XmlMakeRightParenToken(leadingTrivia) Case "!"c, ";"c, "#"c, ","c, "}"c Return XmlMakeBadToken(leadingTrivia, 1, ERRID.ERR_IllegalXmlNameChar) Case ":"c Return XmlMakeColonToken(leadingTrivia) Case "["c Return XmlMakeOpenBracketToken(state, leadingTrivia) Case "]"c Return XmlMakeCloseBracketToken(state, leadingTrivia) Case Else ' // Because of weak scanning of QName, this state must always handle ' // '=' | '\'' | '"'| '/' | '>' | '<' | '?' Return ScanXmlNcName(leadingTrivia) End Select End While Return MakeEofToken(leadingTrivia) End Function '// '// This is used to detect a VB statement on the next line '// '// NL WS* KW WS* ID | KW '// Example Dim x '// '// For EndElement state only, </x followed by Sub '// NL WS* KW | ID '// Example Sub '// '// NL WS* ID WS* ( '// Example Console.WriteLine ( '// '// NL WS* < ID WS* ( '// Example <ClsCompliant( '// '// NL WS* # WS* KW '// Example #END '// '// NL WS* ' '// Example ' This is a comment Private Function ScanXmlForPossibleStatement(state As ScannerState) As Boolean If Not CanGet() Then Return False End If Dim token As SyntaxToken Dim possibleStatement As Boolean = False Dim offsets = CreateOffsetRestorePoint() Dim c As Char = Peek() Select Case c Case "#"c, FULLWIDTH_NUMBER_SIGN ' Check for preprocessor statement, i.e. # if AdvanceChar(1) token = ScanNextToken(allowLeadingMultilineTrivia:=False) possibleStatement = token.IsKeyword Case "<"c, FULLWIDTH_LESS_THAN_SIGN ' Check for code attribute, i.e < clscompliant ( AdvanceChar(1) Dim leadingTrivia = ScanSingleLineTrivia() ' Use ScanXmlNcName instead of ScanToken because it won't stop on "." token = ScanXmlNcName(leadingTrivia) Dim name As XmlNameTokenSyntax = TryCast(token, XmlNameTokenSyntax) If name IsNot Nothing AndAlso Not name.IsMissing Then If name.PossibleKeywordKind <> SyntaxKind.XmlNameToken Then leadingTrivia = ScanSingleLineTrivia() c = Peek() possibleStatement = c = "("c OrElse c = FULLWIDTH_LEFT_PARENTHESIS End If End If Case Else If IsSingleQuote(c) AndAlso LastToken.Kind <> SyntaxKind.EqualsToken Then ' Check for comment possibleStatement = True Else ' Check for statement or call Dim leadingTrivia = ScanSingleLineTrivia() ' Use ScanXmlNcName instead of ScanToken because it won't stop on "." token = ScanXmlNcName(leadingTrivia) Dim name As XmlNameTokenSyntax = TryCast(token, XmlNameTokenSyntax) If name IsNot Nothing AndAlso Not token.IsMissing Then If state = ScannerState.EndElement Then possibleStatement = token.Kind = SyntaxKind.XmlNameToken OrElse LastToken.Kind = SyntaxKind.XmlNameToken Exit Select End If ' If there was leading trivia, it must be trivia recognized by VB but not XML. Debug.Assert(Not leadingTrivia.Any() OrElse (IsNewLine(c) AndAlso (c <> CARRIAGE_RETURN) AndAlso (c <> LINE_FEED)) OrElse (IsWhitespace(c) AndAlso Not IsXmlWhitespace(c))) token = ScanNextToken(allowLeadingMultilineTrivia:=False) If name.PossibleKeywordKind = SyntaxKind.XmlNameToken Then possibleStatement = token.Kind = SyntaxKind.OpenParenToken Else possibleStatement = (token.Kind = SyntaxKind.IdentifierToken) OrElse token.IsKeyword End If End If End If End Select offsets.Restore() Return possibleStatement End Function Friend Function ScanXmlContent() As SyntaxToken ' SHIM If IsScanningXmlDoc Then Return ScanXmlContentInXmlDoc() End If ' // [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*) Dim Here As Integer = 0 Dim IsAllWhitespace As Boolean = True ' lets do an unusual peek-behind to make sure we are not restarting after a non-Ws char. If _lineBufferOffset > 0 Then Dim prevChar = Peek(-1) If prevChar <> ">"c AndAlso Not XmlCharType.IsWhiteSpace(prevChar) Then IsAllWhitespace = False End If End If Dim scratch = GetScratch() While CanGet(Here) Dim c As Char = Peek(Here) Select Case (c) Case CARRIAGE_RETURN, LINE_FEED Here = SkipLineBreak(c, Here) scratch.Append(LINE_FEED) Case " "c, CHARACTER_TABULATION scratch.Append(c) Here += 1 Case "&"c If Here <> 0 Then Return XmlMakeTextLiteralToken(Nothing, Here, scratch) End If ' TODO: the entity could be whitespace, do we want to report it as WS? Return ScanXmlReference(Nothing) Case "<"c Dim precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing If Here <> 0 Then If Not IsAllWhitespace Then Return XmlMakeTextLiteralToken(Nothing, Here, scratch) Else scratch.Clear() ' will not use this Here = 0 ' consumed chars. precedingTrivia = ScanXmlTrivia(Peek) End If End If Debug.Assert(Here = 0) If CanGet(1) Then Dim ch As Char = Peek(1) Select Case ch Case "!"c If CanGet(2) Then Select Case (Peek(2)) Case "-"c If NextIs(3, "-"c) Then Return XmlMakeBeginCommentToken(precedingTrivia, s_scanNoTriviaFunc) End If Case "["c If NextAre(3, "CDATA[") Then Return XmlMakeBeginCDataToken(precedingTrivia, s_scanNoTriviaFunc) End If Case "D"c If NextAre(3, "OCTYPE") Then Return XmlMakeBeginDTDToken(precedingTrivia) End If End Select End If Case "%"c If NextIs(2, "="c) Then Return XmlMakeBeginEmbeddedToken(precedingTrivia) End If Case "?"c Return XmlMakeBeginProcessingInstructionToken(precedingTrivia, s_scanNoTriviaFunc) Case "/"c Return XmlMakeBeginEndElementToken(precedingTrivia, s_scanNoTriviaFunc) End Select End If Return XmlMakeLessToken(precedingTrivia) Case "]"c If NextAre(Here + 1, "]>") Then ' // If valid characters found then return them. If Here <> 0 Then Return XmlMakeTextLiteralToken(Nothing, Here, scratch) End If ' // Create an invalid character data token for the illegal ']]>' sequence Return XmlMakeTextLiteralToken(Nothing, 3, ERRID.ERR_XmlEndCDataNotAllowedInContent) End If GoTo ScanChars Case "#"c ' // Even though # is valid in content, abort xml scanning if the m_State shows and error ' // and the line begins with NL WS* # WS* KW 'TODO: error recovery - how can we do this? 'If m_State.m_IsXmlError Then ' MakeXmlCharToken(tokens.tkXmlCharData, Here - m_InputStreamPosition, IsAllWhitespace) ' m_InputStreamPosition = Here ' Dim sharp As Token = MakeToken(tokens.tkSharp, 1) ' m_InputStreamPosition += 1 ' While (m_InputStream(m_InputStreamPosition) = " "c OrElse m_InputStream(m_InputStreamPosition) = CHARACTER_TABULATION) ' m_InputStreamPosition += 1 ' End While ' ScanXmlQName() ' Dim restart As Token = CheckXmlForStatement() ' If restart IsNot Nothing Then ' ' // Abort Xml - Found Keyword space at the beginning of the line ' AbandonTokens(restart) ' m_State.Init(LexicalState.VB) ' MakeToken(tokens.tkXmlAbort, 0) ' Return ' End If ' AbandonTokens(sharp) ' Here = m_InputStreamPosition 'End If GoTo ScanChars Case "%"c 'TODO: error recovery. We cannot do this. 'If there is all whitespace after ">", it will be scanned as insignificant, 'but in this case it is significant. 'Also as far as I can see Dev10 does not resync on "%>" text anyways. '' // Even though %> is valid in pcdata. When inside of an embedded expression '' // return this sequence separately so that the xml literal completion code can '' // easily detect the end of an embedded expression that may be temporarily hidden '' // by a new element. i.e. <%= <a> %> 'If CanGetCharAtOffset(Here + 1) AndAlso _ ' PeekAheadChar(Here + 1) = ">"c Then ' ' // If valid characters found then return them. ' If Here <> 0 Then ' Return XmlMakeCharDataToken(Nothing, Here, New String(value.ToArray)) ' End If ' ' // Create a special pcdata token for the possible tkEndXmlEmbedded ' Return XmlMakeCharDataToken(Nothing, 2, "%>") 'Else ' IsAllWhitespace = False ' value.Add("%"c) ' Here += 1 'End If 'Continue While GoTo ScanChars Case Else ScanChars: ' // Check characters are valid IsAllWhitespace = False Dim xmlCh = ScanXmlChar(Here) If xmlCh.Length = 0 Then ' bad char If Here > 0 Then Return XmlMakeTextLiteralToken(Nothing, Here, scratch) Else Return XmlMakeBadToken(Nothing, 1, ERRID.ERR_IllegalChar) End If End If xmlCh.AppendTo(scratch) Here += xmlCh.Length End Select End While ' no more chars If Here > 0 Then Return XmlMakeTextLiteralToken(Nothing, Here, scratch) Else Return MakeEofToken() End If End Function Friend Function ScanXmlComment() As SyntaxToken ' // [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->' Dim precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing If IsScanningXmlDoc AndAlso IsAtNewLine() Then Dim xDocTrivia = ScanXmlDocTrivia() If xDocTrivia Is Nothing Then Return MakeEofToken() ' XmlDoc lines must start with XmlDocTrivia End If precedingTrivia = xDocTrivia End If Dim Here = 0 While CanGet(Here) Dim c As Char = Peek(Here) Select Case (c) Case CARRIAGE_RETURN, LINE_FEED Return XmlMakeCommentToken(precedingTrivia, Here + LengthOfLineBreak(c, Here)) Case "-"c If NextIs(Here + 1, "-"c) Then ' // --> terminates an Xml comment but otherwise -- is an illegal character sequence. ' // The scanner will always returns "--" as a separate comment data string and the ' // the semantics will error if '--' is ever found. ' // Return valid characters up to the -- If Here > 0 Then Return XmlMakeCommentToken(precedingTrivia, Here) End If If CanGet(Here + 2) Then c = Peek(Here + 2) Here += 2 ' // if > is not found then this is an error. Return the -- string If c <> ">"c Then Return XmlMakeCommentToken(precedingTrivia, 2) ' TODO: we cannot do the following ' // For better error recovery, allow -> to terminate the comment. ' // This works because the -> terminates only when the invalid -- ' // is returned. 'If Here + 1 < m_InputStreamEnd AndAlso _ ' m_InputStream(Here) = "-"c AndAlso _ ' m_InputStream(Here + 1) = ">"c Then ' Here += 1 'Else ' Continue While 'End If Else Return XmlMakeEndCommentToken(precedingTrivia) End If End If End If GoTo ScanChars Case Else ScanChars: Dim xmlCh = ScanXmlChar(Here) If xmlCh.Length <> 0 Then Here += xmlCh.Length Continue While End If ' bad char If Here > 0 Then Return XmlMakeCommentToken(precedingTrivia, Here) Else Return XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalChar) End If End Select End While ' no more chars If Here > 0 Then Return XmlMakeCommentToken(precedingTrivia, Here) Else Return MakeEofToken(precedingTrivia) End If End Function Friend Function ScanXmlCData() As SyntaxToken ' // [18] CDSect ::= CDStart CData CDEnd ' // [19] CDStart ::= '<![CDATA[' ' // [20] CData ::= (Char* - (Char* ']]>' Char*)) ' // [21] CDEnd ::= ']]>' Dim precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing If IsScanningXmlDoc AndAlso IsAtNewLine() Then Dim xDocTrivia = ScanXmlDocTrivia() If xDocTrivia Is Nothing Then Return MakeEofToken() ' XmlDoc lines must start with XmlDocTrivia End If precedingTrivia = xDocTrivia End If Dim scratch = GetScratch() Dim Here = 0 While CanGet(Here) Dim c As Char = Peek(Here) Select Case (c) Case CARRIAGE_RETURN, LINE_FEED Here = SkipLineBreak(c, Here) scratch.Append(LINE_FEED) Return XmlMakeCDataToken(precedingTrivia, Here, scratch) Case "]"c If NextAre(Here + 1, "]>") Then '// If valid characters found then return them. If Here <> 0 Then Return XmlMakeCDataToken(precedingTrivia, Here, scratch) End If ' // Create token for ']]>' sequence Return XmlMakeEndCDataToken(precedingTrivia) End If GoTo ScanChars Case Else ScanChars: Dim xmlCh = ScanXmlChar(Here) If xmlCh.Length = 0 Then ' bad char If Here > 0 Then Return XmlMakeCDataToken(precedingTrivia, Here, scratch) Else Return XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalChar) End If End If xmlCh.AppendTo(scratch) Here += xmlCh.Length End Select End While ' no more chars If Here > 0 Then Return XmlMakeCDataToken(precedingTrivia, Here, scratch) Else Return MakeEofToken(precedingTrivia) End If End Function Friend Function ScanXmlPIData(state As ScannerState) As SyntaxToken ' SHIM If IsScanningXmlDoc Then Return ScanXmlPIDataInXmlDoc(state) End If ' // Scan the PI data after the white space ' // [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>' ' // [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l')) Debug.Assert(state = ScannerState.StartProcessingInstruction OrElse state = ScannerState.ProcessingInstruction) Dim precedingTrivia = _triviaListPool.Allocate(Of VisualBasicSyntaxNode)() Dim result As SyntaxToken If state = ScannerState.StartProcessingInstruction AndAlso CanGet() Then ' // Whitespace ' // S ::= (#x20 | #x9 | #xD | #xA)+ Dim c = Peek() Select Case c Case CARRIAGE_RETURN, LINE_FEED, " "c, CHARACTER_TABULATION Dim wsTrivia = ScanXmlTrivia(c) precedingTrivia.AddRange(wsTrivia) End Select End If Dim Here = 0 While CanGet(Here) Dim c As Char = Peek(Here) Select Case (c) Case CARRIAGE_RETURN, LINE_FEED result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here + LengthOfLineBreak(c, Here)) GoTo CleanUp Case "?"c If NextIs(Here + 1, ">"c) Then '// If valid characters found then return them. If Here <> 0 Then result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here) GoTo CleanUp End If ' // Create token for the '?>' termination sequence result = XmlMakeEndProcessingInstructionToken(precedingTrivia.ToList) GoTo CleanUp End If GoTo ScanChars Case Else ScanChars: Dim xmlCh = ScanXmlChar(Here) If xmlCh.Length > 0 Then Here += xmlCh.Length Continue While End If ' bad char If Here <> 0 Then result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here) GoTo CleanUp Else result = XmlMakeBadToken(precedingTrivia.ToList, 1, ERRID.ERR_IllegalChar) GoTo CleanUp End If End Select End While ' no more chars If Here > 0 Then result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here) Else result = MakeEofToken(precedingTrivia.ToList) End If CleanUp: _triviaListPool.Free(precedingTrivia) Return result End Function Friend Function ScanXmlMisc() As SyntaxToken Debug.Assert(Not IsScanningXmlDoc) ' // Misc ::= Comment | PI | S Dim precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing While CanGet() Dim c As Char = Peek() Select Case (c) ' // Whitespace ' // S ::= (#x20 | #x9 | #xD | #xA)+ Case CARRIAGE_RETURN, LINE_FEED, " "c, CHARACTER_TABULATION ' we should not visit this place twice Debug.Assert(Not precedingTrivia.Any) precedingTrivia = ScanXmlTrivia(c) Case "<"c If CanGet(1) Then Dim ch As Char = Peek(1) Select Case ch Case "!"c If NextAre(2, "--") Then Return XmlMakeBeginCommentToken(precedingTrivia, s_scanNoTriviaFunc) ElseIf NextAre(2, "DOCTYPE") Then Return XmlMakeBeginDTDToken(precedingTrivia) End If Case "%"c If NextIs(2, "="c) Then Return XmlMakeBeginEmbeddedToken(precedingTrivia) End If Case "?"c Return XmlMakeBeginProcessingInstructionToken(precedingTrivia, s_scanNoTriviaFunc) End Select End If Return XmlMakeLessToken(precedingTrivia) ' TODO: review ' If Not m_State.m_ScannedElement OrElse c = "?"c OrElse c = "!"c Then ' ' // Remove tEOL from token ring if any exists ' If tEOL IsNot Nothing Then ' m_FirstFreeToken = tEOL ' End If ' m_State.m_LexicalState = LexicalState.XmlMarkup ' MakeToken(tokens.tkLT, 1) ' m_InputStreamPosition += 1 ' Return ' End If 'End If 'm_State.EndXmlState() 'If tEOL IsNot Nothing Then ' tEOL.m_EOL.m_NextLineAlreadyScanned = True 'Else ' MakeToken(tokens.tkLT, 1) ' m_InputStreamPosition += 1 'End If 'Return Case Else Return SyntaxFactory.Token(precedingTrivia.Node, SyntaxKind.EndOfXmlToken, Nothing, String.Empty) End Select End While Return MakeEofToken(precedingTrivia) End Function Friend Function ScanXmlStringUnQuoted() As SyntaxToken If Not CanGet() Then Return MakeEofToken() End If ' This can never happen as this token cannot cross lines. Debug.Assert(Not (IsScanningXmlDoc AndAlso IsAtNewLine())) Dim Here = 0 Dim scratch = GetScratch() While CanGet(Here) Dim c As Char = Peek(Here) Select Case (c) Case CARRIAGE_RETURN, LINE_FEED, " "c, CHARACTER_TABULATION If Here > 0 Then Return XmlMakeAttributeDataToken(Nothing, Here, scratch) Else Return MakeMissingToken(Nothing, SyntaxKind.SingleQuoteToken) End If Case "<"c, ">"c, "?"c ' This cannot be in a string. terminate the string. If Here <> 0 Then Return XmlMakeAttributeDataToken(Nothing, Here, scratch) Else Return MakeMissingToken(Nothing, SyntaxKind.SingleQuoteToken) End If Case "&"c If Here > 0 Then Return XmlMakeAttributeDataToken(Nothing, Here, scratch) Else Return ScanXmlReference(Nothing) End If Case "/"c If NextIs(Here + 1, ">"c) Then If Here <> 0 Then Return XmlMakeAttributeDataToken(Nothing, Here, scratch) Else Return MakeMissingToken(Nothing, SyntaxKind.SingleQuoteToken) End If End If GoTo ScanChars Case Else ScanChars: ' // Check characters are valid Dim xmlCh = ScanXmlChar(Here) If xmlCh.Length = 0 Then ' bad char If Here > 0 Then Return XmlMakeAttributeDataToken(Nothing, Here, scratch) Else Return XmlMakeBadToken(Nothing, 1, ERRID.ERR_IllegalChar) End If End If xmlCh.AppendTo(scratch) Here += xmlCh.Length End Select End While ' no more chars Return XmlMakeAttributeDataToken(Nothing, Here, scratch) End Function Friend Function ScanXmlStringSingle() As SyntaxToken Return ScanXmlString("'"c, "'"c, True) End Function Friend Function ScanXmlStringDouble() As SyntaxToken Return ScanXmlString(""""c, """"c, False) End Function Friend Function ScanXmlStringSmartSingle() As SyntaxToken Return ScanXmlString(RIGHT_SINGLE_QUOTATION_MARK, LEFT_SINGLE_QUOTATION_MARK, True) End Function Friend Function ScanXmlStringSmartDouble() As SyntaxToken Return ScanXmlString(RIGHT_DOUBLE_QUOTATION_MARK, LEFT_DOUBLE_QUOTATION_MARK, False) End Function Friend Function ScanXmlString(terminatingChar As Char, altTerminatingChar As Char, isSingle As Boolean) As SyntaxToken ' TODO: this trivia is used only in XmlDoc. May split the function? Dim precedingTrivia = _triviaListPool.Allocate(Of VisualBasicSyntaxNode)() Dim result As SyntaxToken If IsScanningXmlDoc AndAlso IsAtNewLine() Then Dim xDocTrivia = ScanXmlDocTrivia() If xDocTrivia Is Nothing Then result = MakeEofToken() ' XmlDoc lines must start with XmlDocTrivia GoTo CleanUp End If precedingTrivia.Add(xDocTrivia) End If Dim Here = 0 Dim scratch = GetScratch() While CanGet(Here) Dim c As Char = Peek(Here) If c = terminatingChar Or c = altTerminatingChar Then If Here > 0 Then result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch) GoTo CleanUp Else If isSingle Then result = XmlMakeSingleQuoteToken(precedingTrivia, c, isOpening:=False) Else result = XmlMakeDoubleQuoteToken(precedingTrivia, c, isOpening:=False) End If GoTo CleanUp End If End If Select Case (c) Case CARRIAGE_RETURN, LINE_FEED Here = SkipLineBreak(c, Here) scratch.Append(SPACE) result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch) GoTo CleanUp Case CHARACTER_TABULATION scratch.Append(SPACE) Here += 1 Case "<"c ' This cannot be in a string. terminate the string. If Here > 0 Then result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch) GoTo CleanUp Else ' report unexpected <%= in a special way. If NextAre(1, "%=") Then Dim errEmbedStart = XmlMakeAttributeDataToken(precedingTrivia, 3, "<%=") Dim errEmbedInfo = ErrorFactory.ErrorInfo(ERRID.ERR_QuotedEmbeddedExpression) result = DirectCast(errEmbedStart.SetDiagnostics({errEmbedInfo}), SyntaxToken) GoTo CleanUp End If Dim data = SyntaxFactory.MissingToken(SyntaxKind.SingleQuoteToken) If precedingTrivia.Count > 0 Then data = DirectCast(data.WithLeadingTrivia(precedingTrivia.ToList.Node), SyntaxToken) End If Dim errInfo = ErrorFactory.ErrorInfo(If(isSingle, ERRID.ERR_ExpectedSQuote, ERRID.ERR_ExpectedQuote)) result = DirectCast(data.SetDiagnostics({errInfo}), SyntaxToken) GoTo CleanUp End If Case "&"c If Here > 0 Then result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch) GoTo CleanUp Else result = ScanXmlReference(precedingTrivia) GoTo CleanUp End If Case Else ScanChars: ' // Check characters are valid Dim xmlCh = ScanXmlChar(Here) If xmlCh.Length = 0 Then ' bad char If Here > 0 Then result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch) GoTo CleanUp Else result = XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalChar) GoTo CleanUp End If End If xmlCh.AppendTo(scratch) Here += xmlCh.Length End Select End While ' no more chars If Here > 0 Then result = XmlMakeAttributeDataToken(precedingTrivia, Here, scratch) GoTo CleanUp Else result = MakeEofToken(precedingTrivia) GoTo CleanUp End If CleanUp: _triviaListPool.Free(precedingTrivia) Return result End Function ''' <summary> ''' 0 - not a surrogate, 2 - is valid surrogate ''' 1 is an error ''' </summary> Private Function ScanSurrogatePair(c1 As Char, Here As Integer) As XmlCharResult Debug.Assert(Here >= 0) Debug.Assert(CanGet(Here)) Debug.Assert(Peek(Here) = c1) If IsHighSurrogate(c1) AndAlso CanGet(Here + 1) Then Dim c2 = Peek(Here + 1) If IsLowSurrogate(c2) Then Return New XmlCharResult(c1, c2) End If End If Return Nothing End Function ' contains result of Xml char scanning. Friend Structure XmlCharResult Friend ReadOnly Length As Integer Friend ReadOnly Char1 As Char Friend ReadOnly Char2 As Char Friend Sub New(ch As Char) Length = 1 Char1 = ch End Sub Friend Sub New(ch1 As Char, ch2 As Char) Length = 2 Char1 = ch1 Char2 = ch2 End Sub Friend Sub AppendTo(list As StringBuilder) Debug.Assert(list IsNot Nothing) Debug.Assert(Length <> 0) list.Append(Char1) If Length = 2 Then list.Append(Char2) End If End Sub End Structure Private Function ScanXmlChar(Here As Integer) As XmlCharResult Debug.Assert(Here >= 0) Debug.Assert(CanGet(Here)) Dim c = Peek(Here) If Not isValidUtf16(c) Then Return Nothing End If If Not IsSurrogate(c) Then Return New XmlCharResult(c) End If Return ScanSurrogatePair(c, Here) End Function Private Function ScanXmlNcName(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken ' // Scan a non qualified name per Xml Namespace 1.0 ' // [4] NCName ::= (Letter | '_') (NCNameChar)* /* An XML Name, minus the ":" */ ' // This scanner is much looser than a pure Xml scanner. ' // Names are any character up to a separator character from ' // ':' | ' ' | '\t' | '\n' | '\r' | '=' | '\'' | '"'| '/' | '<' | '>' | EOF ' // Each name token will be marked as to whether it contains only valid Xml name characters. Dim Here As Integer = 0 Dim IsIllegalChar As Boolean = False Dim isFirst As Boolean = True Dim err As ERRID = ERRID.ERR_None Dim errUnicode As Integer = 0 Dim errChar As String = Nothing 'TODO - Fix ScanXmlNCName to conform to XML spec instead of old loose scanning. While CanGet(Here) Dim c As Char = Peek(Here) Select Case (c) Case ":"c, " "c, CHARACTER_TABULATION, LINE_FEED, CARRIAGE_RETURN, "="c, "'"c, """"c, "/"c, ">"c, "<"c, "("c, ")"c, "?"c, ";"c, ","c, "}"c GoTo CreateNCNameToken Case Else ' // Invalid Xml name but scan as Xml name anyway ' // Check characters are valid name chars Dim xmlCh = ScanXmlChar(Here) If xmlCh.Length = 0 Then IsIllegalChar = True GoTo CreateNCNameToken Else If err = ERRID.ERR_None Then If xmlCh.Length = 1 Then ' Non surrogate check If isFirst Then err = If(Not isStartNameChar(xmlCh.Char1), ERRID.ERR_IllegalXmlStartNameChar, ERRID.ERR_None) isFirst = False Else err = If(Not isNameChar(xmlCh.Char1), ERRID.ERR_IllegalXmlNameChar, ERRID.ERR_None) End If If err <> ERRID.ERR_None Then errChar = Convert.ToString(xmlCh.Char1) errUnicode = Convert.ToInt32(xmlCh.Char1) End If Else ' Surrogate check Dim unicode = UTF16ToUnicode(xmlCh) If Not (unicode >= &H10000 AndAlso unicode <= &HEFFFF) Then err = ERRID.ERR_IllegalXmlNameChar errChar = {xmlCh.Char1, xmlCh.Char2} errUnicode = unicode End If End If End If Here += xmlCh.Length End If End Select End While CreateNCNameToken: If Here <> 0 Then Dim name = XmlMakeXmlNCNameToken(precedingTrivia, Here) If err <> ERRID.ERR_None Then name = name.WithDiagnostics(ErrorFactory.ErrorInfo(err, errChar, String.Format("&H{0:X}", errUnicode))) End If Return name ElseIf IsIllegalChar Then Return XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalChar) End If Return MakeMissingToken(precedingTrivia, SyntaxKind.XmlNameToken) End Function Private Function ScanXmlReference(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As XmlTextTokenSyntax Debug.Assert(CanGet) Debug.Assert(Peek() = "&"c) ' skip 1 char for "&" If CanGet(1) Then Dim c As Char = Peek(1) Select Case (c) Case "#"c Dim Here = 2 ' skip "&#" Dim result = ScanXmlCharRef(Here) If result.Length <> 0 Then Dim value As String = Nothing If result.Length = 1 Then value = Intern(result.Char1) ElseIf result.Length = 2 Then value = Intern({result.Char1, result.Char2}) End If If CanGet(Here) AndAlso Peek(Here) = ";"c Then Return XmlMakeEntityLiteralToken(precedingTrivia, Here + 1, value) Else Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, Here, value) Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon) Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax) End If End If Case "a"c ' // &amp; ' // &apos; If CanGet(4) AndAlso NextAre(2, "mp") Then If Peek(4) = ";"c Then Return XmlMakeAmpLiteralToken(precedingTrivia) Else Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, 4, "&") Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon) Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax) End If ElseIf CanGet(5) AndAlso NextAre(2, "pos") Then If Peek(5) = ";"c Then Return XmlMakeAposLiteralToken(precedingTrivia) Else Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, 5, "'") Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon) Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax) End If End If Case "l"c ' // &lt; If CanGet(3) AndAlso NextIs(2, "t"c) Then If Peek(3) = ";"c Then Return XmlMakeLtLiteralToken(precedingTrivia) Else Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, 3, "<") Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon) Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax) End If End If Case "g"c ' // &gt; If CanGet(3) AndAlso NextIs(2, "t"c) Then If Peek(3) = ";"c Then Return XmlMakeGtLiteralToken(precedingTrivia) Else Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, 3, ">") Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon) Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax) End If End If Case "q"c ' // &quot; If CanGet(5) AndAlso NextAre(2, "uot") Then If Peek(5) = ";"c Then Return XmlMakeQuotLiteralToken(precedingTrivia) Else Dim noSemicolon = XmlMakeEntityLiteralToken(precedingTrivia, 5, """") Dim noSemicolonError = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedSColon) Return DirectCast(noSemicolon.SetDiagnostics({noSemicolonError}), XmlTextTokenSyntax) End If End If End Select End If Dim badEntity = XmlMakeEntityLiteralToken(precedingTrivia, 1, "") Dim errInfo = ErrorFactory.ErrorInfo(ERRID.ERR_XmlEntityReference) Return DirectCast(badEntity.SetDiagnostics({errInfo}), XmlTextTokenSyntax) End Function Private Function ScanXmlCharRef(ByRef index As Integer) As XmlCharResult Debug.Assert(index >= 0) If Not CanGet(index) Then Return Nothing End If ' cannot reuse Scratch as this can be used in a nested call. Dim charRefSb As New StringBuilder Dim Here = index Dim ch = Peek(Here) If ch = "x"c Then Here += 1 While CanGet(Here) ch = Peek(Here) If XmlCharType.IsHexDigit(ch) Then charRefSb.Append(ch) Else Exit While End If Here += 1 End While If charRefSb.Length > 0 Then Dim result = HexToUTF16(charRefSb) If result.Length <> 0 Then index = Here End If Return result End If Else While CanGet(Here) ch = Peek(Here) If XmlCharType.IsDigit(ch) Then charRefSb.Append(ch) Else Exit While End If Here += 1 End While If charRefSb.Length > 0 Then Dim result = DecToUTF16(charRefSb) If result.Length <> 0 Then index = Here End If Return result End If End If Return Nothing End Function End Class End Namespace
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/EditorFeatures/Core/Preview/DifferenceViewerPreview.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.VisualStudio.Text.Differencing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { internal class DifferenceViewerPreview : IDisposable { private IDifferenceViewer _viewer; public DifferenceViewerPreview(IDifferenceViewer viewer) { Contract.ThrowIfNull(viewer); _viewer = viewer; } public IDifferenceViewer Viewer => _viewer; public void Dispose() { GC.SuppressFinalize(this); if (_viewer != null && !_viewer.IsClosed) { _viewer.Close(); } _viewer = null; } ~DifferenceViewerPreview() { // make sure we are not leaking diff viewer // we can't close the view from finalizer thread since it must be same // thread (owner thread) this UI is created. if (Environment.HasShutdownStarted) { return; } FatalError.ReportAndCatch(new Exception($"Dispose is not called how? viewer state : {_viewer.IsClosed}")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.VisualStudio.Text.Differencing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { internal class DifferenceViewerPreview : IDisposable { private IDifferenceViewer _viewer; public DifferenceViewerPreview(IDifferenceViewer viewer) { Contract.ThrowIfNull(viewer); _viewer = viewer; } public IDifferenceViewer Viewer => _viewer; public void Dispose() { GC.SuppressFinalize(this); if (_viewer != null && !_viewer.IsClosed) { _viewer.Close(); } _viewer = null; } ~DifferenceViewerPreview() { // make sure we are not leaking diff viewer // we can't close the view from finalizer thread since it must be same // thread (owner thread) this UI is created. if (Environment.HasShutdownStarted) { return; } FatalError.ReportAndCatch(new Exception($"Dispose is not called how? viewer state : {_viewer.IsClosed}")); } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/VisualStudio/CSharp/Impl/LanguageService/CSharpCreateServicesOnTextViewConnection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets { [Export(typeof(IWpfTextViewConnectionListener))] [ContentType(ContentTypeNames.CSharpContentType)] [TextViewRole(PredefinedTextViewRoles.Interactive)] internal class CSharpCreateServicesOnTextViewConnection : AbstractCreateServicesOnTextViewConnection { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCreateServicesOnTextViewConnection( VisualStudioWorkspace workspace, IAsynchronousOperationListenerProvider listenerProvider, IThreadingContext threadingContext) : base(workspace, listenerProvider, threadingContext, LanguageNames.CSharp) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets { [Export(typeof(IWpfTextViewConnectionListener))] [ContentType(ContentTypeNames.CSharpContentType)] [TextViewRole(PredefinedTextViewRoles.Interactive)] internal class CSharpCreateServicesOnTextViewConnection : AbstractCreateServicesOnTextViewConnection { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCreateServicesOnTextViewConnection( VisualStudioWorkspace workspace, IAsynchronousOperationListenerProvider listenerProvider, IThreadingContext threadingContext) : base(workspace, listenerProvider, threadingContext, LanguageNames.CSharp) { } } }
-1
dotnet/roslyn
55,562
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only
https://github.com/dotnet/roslyn/issues/55546
genlu
2021-08-12T00:33:02Z
2021-08-24T23:32:34Z
87f6fdf02ebaeddc2982de1a100783dc9f435267
4d86e7e8867f586b29440152fd4792a14b55659a
Consider MatchPriority when comparing CompletionItems when filter text is lowercase only . https://github.com/dotnet/roslyn/issues/55546
./src/Features/Core/Portable/DocumentationComments/IDocumentationCommentSnippetService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.DocumentationComments { internal interface IDocumentationCommentSnippetService : ILanguageService { /// <summary> /// A single character string indicating what the comment character is for the documentation comments /// </summary> string DocumentationCommentCharacter { get; } DocumentationCommentSnippet? GetDocumentationCommentSnippetOnCharacterTyped( SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken); DocumentationCommentSnippet? GetDocumentationCommentSnippetOnCommandInvoke( SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken); DocumentationCommentSnippet? GetDocumentationCommentSnippetOnEnterTyped( SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken); DocumentationCommentSnippet? GetDocumentationCommentSnippetFromPreviousLine( DocumentOptionSet options, TextLine currentLine, TextLine previousLine); bool IsValidTargetMember(SyntaxTree syntaxTree, SourceText text, int caretPosition, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.DocumentationComments { internal interface IDocumentationCommentSnippetService : ILanguageService { /// <summary> /// A single character string indicating what the comment character is for the documentation comments /// </summary> string DocumentationCommentCharacter { get; } DocumentationCommentSnippet? GetDocumentationCommentSnippetOnCharacterTyped( SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken); DocumentationCommentSnippet? GetDocumentationCommentSnippetOnCommandInvoke( SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken); DocumentationCommentSnippet? GetDocumentationCommentSnippetOnEnterTyped( SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken); DocumentationCommentSnippet? GetDocumentationCommentSnippetFromPreviousLine( DocumentOptionSet options, TextLine currentLine, TextLine previousLine); bool IsValidTargetMember(SyntaxTree syntaxTree, SourceText text, int caretPosition, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordCopyCtor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedRecordCopyCtor : SynthesizedInstanceConstructor { private readonly int _memberOffset; public SynthesizedRecordCopyCtor( SourceMemberContainerTypeSymbol containingType, int memberOffset) : base(containingType) { _memberOffset = memberOffset; Parameters = ImmutableArray.Create(SynthesizedParameterSymbol.Create( this, TypeWithAnnotations.Create( isNullableEnabled: true, ContainingType), ordinal: 0, RefKind.None, "original")); } public override ImmutableArray<ParameterSymbol> Parameters { get; } public override Accessibility DeclaredAccessibility => ContainingType.IsSealed ? Accessibility.Private : Accessibility.Protected; internal override LexicalSortKey GetLexicalSortKey() => LexicalSortKey.GetSynthesizedMemberKey(_memberOffset); internal override void GenerateMethodBodyStatements(SyntheticBoundNodeFactory F, ArrayBuilder<BoundStatement> statements, BindingDiagnosticBag diagnostics) { // Tracking issue for copy constructor in inheritance scenario: https://github.com/dotnet/roslyn/issues/44902 // Write assignments to fields // .ctor(DerivedRecordType original) : base((BaseRecordType)original) // { // this.field1 = parameter.field1 // ... // this.fieldN = parameter.fieldN // } var param = F.Parameter(Parameters[0]); foreach (var field in ContainingType.GetFieldsToEmit()) { if (!field.IsStatic) { statements.Add(F.Assignment(F.Field(F.This(), field), F.Field(param, field))); } } } internal static MethodSymbol? FindCopyConstructor(NamedTypeSymbol containingType, NamedTypeSymbol within, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { MethodSymbol? bestCandidate = null; int bestModifierCountSoFar = -1; // stays as -1 unless we hit an ambiguity foreach (var member in containingType.InstanceConstructors) { if (HasCopyConstructorSignature(member) && !member.HasUnsupportedMetadata && AccessCheck.IsSymbolAccessible(member, within, ref useSiteInfo)) { // If one has fewer custom modifiers, that is better // (see OverloadResolution.BetterFunctionMember) if (bestCandidate is null && bestModifierCountSoFar < 0) { bestCandidate = member; continue; } if (bestModifierCountSoFar < 0) { bestModifierCountSoFar = bestCandidate.CustomModifierCount(); } var memberModCount = member.CustomModifierCount(); if (memberModCount > bestModifierCountSoFar) { continue; } if (memberModCount == bestModifierCountSoFar) { bestCandidate = null; continue; } bestCandidate = member; bestModifierCountSoFar = memberModCount; } } return bestCandidate; } internal static bool IsCopyConstructor(Symbol member) { if (member is MethodSymbol { MethodKind: MethodKind.Constructor } method) { return HasCopyConstructorSignature(method); } return false; } internal static bool HasCopyConstructorSignature(MethodSymbol member) { NamedTypeSymbol containingType = member.ContainingType; return member is MethodSymbol { IsStatic: false, ParameterCount: 1, Arity: 0 } method && method.Parameters[0].Type.Equals(containingType, TypeCompareKind.AllIgnoreOptions) && method.Parameters[0].RefKind == RefKind.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. using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedRecordCopyCtor : SynthesizedInstanceConstructor { private readonly int _memberOffset; public SynthesizedRecordCopyCtor( SourceMemberContainerTypeSymbol containingType, int memberOffset) : base(containingType) { _memberOffset = memberOffset; Parameters = ImmutableArray.Create(SynthesizedParameterSymbol.Create( this, TypeWithAnnotations.Create( isNullableEnabled: true, ContainingType), ordinal: 0, RefKind.None, "original")); } public override ImmutableArray<ParameterSymbol> Parameters { get; } public override Accessibility DeclaredAccessibility => ContainingType.IsSealed ? Accessibility.Private : Accessibility.Protected; internal override LexicalSortKey GetLexicalSortKey() => LexicalSortKey.GetSynthesizedMemberKey(_memberOffset); internal override void GenerateMethodBodyStatements(SyntheticBoundNodeFactory F, ArrayBuilder<BoundStatement> statements, BindingDiagnosticBag diagnostics) { // Tracking issue for copy constructor in inheritance scenario: https://github.com/dotnet/roslyn/issues/44902 // Write assignments to fields // .ctor(DerivedRecordType original) : base((BaseRecordType)original) // { // this.field1 = parameter.field1 // ... // this.fieldN = parameter.fieldN // } var param = F.Parameter(Parameters[0]); foreach (var field in ContainingType.GetFieldsToEmit()) { if (!field.IsStatic) { statements.Add(F.Assignment(F.Field(F.This(), field), F.Field(param, field))); } } } internal static MethodSymbol? FindCopyConstructor(NamedTypeSymbol containingType, NamedTypeSymbol within, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { MethodSymbol? bestCandidate = null; int bestModifierCountSoFar = -1; // stays as -1 unless we hit an ambiguity foreach (var member in containingType.InstanceConstructors) { if (HasCopyConstructorSignature(member) && !member.HasUnsupportedMetadata && AccessCheck.IsSymbolAccessible(member, within, ref useSiteInfo)) { // If one has fewer custom modifiers, that is better // (see OverloadResolution.BetterFunctionMember) if (bestCandidate is null && bestModifierCountSoFar < 0) { bestCandidate = member; continue; } if (bestModifierCountSoFar < 0) { bestModifierCountSoFar = bestCandidate.CustomModifierCount(); } var memberModCount = member.CustomModifierCount(); if (memberModCount > bestModifierCountSoFar) { continue; } if (memberModCount == bestModifierCountSoFar) { bestCandidate = null; continue; } bestCandidate = member; bestModifierCountSoFar = memberModCount; } } return bestCandidate; } internal static bool IsCopyConstructor(Symbol member) { if (member is MethodSymbol { ContainingType: { IsRecordStruct: false }, MethodKind: MethodKind.Constructor } method) { return HasCopyConstructorSignature(method); } return false; } internal static bool HasCopyConstructorSignature(MethodSymbol member) { NamedTypeSymbol containingType = member.ContainingType; return member is MethodSymbol { IsStatic: false, ParameterCount: 1, Arity: 0 } method && method.Parameters[0].Type.Equals(containingType, TypeCompareKind.AllIgnoreOptions) && method.Parameters[0].RefKind == RefKind.None; } } }
1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/CSharp/Test/Semantic/Semantics/RecordStructTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using 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.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { [CompilerTrait(CompilerFeature.RecordStructs)] public class RecordStructTests : CompilingTestBase { private static CSharpCompilation CreateCompilation(CSharpTestSource source) => CSharpTestBase.CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); private CompilationVerifier CompileAndVerify( CSharpTestSource src, string? expectedOutput = null, IEnumerable<MetadataReference>? references = null) => base.CompileAndVerify( new[] { src, IsExternalInitTypeDefinition }, expectedOutput: expectedOutput, parseOptions: TestOptions.RegularPreview, references: references, // init-only is unverifiable verify: Verification.Skipped); [Fact] public void StructRecord1() { var src = @" record struct Point(int X, int Y);"; var verifier = CompileAndVerify(src).VerifyDiagnostics(); verifier.VerifyIL("Point.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""Point"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""Point"" IL_000f: call ""readonly bool Point.Equals(Point)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("Point.Equals(Point)", @" { // Code size 49 (0x31) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int Point.<X>k__BackingField"" IL_000b: ldarg.1 IL_000c: ldfld ""int Point.<X>k__BackingField"" IL_0011: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0016: brfalse.s IL_002f IL_0018: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001d: ldarg.0 IL_001e: ldfld ""int Point.<Y>k__BackingField"" IL_0023: ldarg.1 IL_0024: ldfld ""int Point.<Y>k__BackingField"" IL_0029: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002e: ret IL_002f: ldc.i4.0 IL_0030: ret }"); } [Fact] public void StructRecord2() { var src = @" using System; record struct S(int X, int Y) { public static void Main() { var s1 = new S(0, 1); var s2 = new S(0, 1); Console.WriteLine(s1.X); Console.WriteLine(s1.Y); Console.WriteLine(s1.Equals(s2)); Console.WriteLine(s1.Equals(new S(1, 0))); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 1 True False").VerifyDiagnostics(); } [Fact] public void StructRecord3() { var src = @" using System; record struct S(int X, int Y) { public bool Equals(S s) => false; public static void Main() { var s1 = new S(0, 1); Console.WriteLine(s1.Equals(s1)); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"False") .VerifyDiagnostics( // (5,17): warning CS8851: 'S' defines 'Equals' but not 'GetHashCode' // public bool Equals(S s) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("S").WithLocation(5, 17)); verifier.VerifyIL("S.Main", @" { // Code size 23 (0x17) .maxstack 3 .locals init (S V_0) //s1 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""S..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldloc.0 IL_000c: call ""bool S.Equals(S)"" IL_0011: call ""void System.Console.WriteLine(bool)"" IL_0016: ret }"); } [Fact] public void StructRecord5() { var src = @" using System; record struct S(int X, int Y) { public bool Equals(S s) { Console.Write(""s""); return true; } public static void Main() { var s1 = new S(0, 1); s1.Equals((object)s1); s1.Equals(s1); } }"; CompileAndVerify(src, expectedOutput: @"ss") .VerifyDiagnostics( // (5,17): warning CS8851: 'S' defines 'Equals' but not 'GetHashCode' // public bool Equals(S s) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("S").WithLocation(5, 17)); } [Fact] public void StructRecordDefaultCtor() { const string src = @" public record struct S(int X);"; const string src2 = @" class C { public S M() => new S(); }"; var comp = CreateCompilation(src + src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src); var comp2 = CreateCompilation(src2, references: new[] { comp.EmitToImageReference() }); comp2.VerifyDiagnostics(); } [Fact] public void Equality_01() { var source = @"using static System.Console; record struct S; class Program { static void Main() { var x = new S(); var y = new S(); WriteLine(x.Equals(y)); WriteLine(((object)x).Equals(y)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"True True").VerifyDiagnostics(); verifier.VerifyIL("S.Equals(S)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("S.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""S"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""S"" IL_000f: call ""readonly bool S.Equals(S)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); } [Fact] public void RecordStructLanguageVersion() { var src1 = @" struct Point(int x, int y); "; var src2 = @" record struct Point { } "; var src3 = @" record struct Point(int x, int y); "; var comp = CreateCompilation(new[] { src1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,13): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS8803: Top-level statements must precede namespace and type declarations. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS8805: Program using top-level statements must be an executable. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 13), // (2,14): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 14), // (2,14): error CS0165: Use of unassigned local variable 'x' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 14), // (2,21): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 21), // (2,21): error CS0165: Use of unassigned local variable 'y' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 21) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,13): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS8803: Top-level statements must precede namespace and type declarations. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS8805: Program using top-level statements must be an executable. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 13), // (2,14): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 14), // (2,14): error CS0165: Use of unassigned local variable 'x' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 14), // (2,21): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 21), // (2,21): error CS0165: Use of unassigned local variable 'y' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 21) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [Fact] public void RecordStructLanguageVersion_Nested() { var src1 = @" class C { struct Point(int x, int y); } "; var src2 = @" class D { record struct Point { } } "; var src3 = @" struct E { record struct Point(int x, int y); } "; var src4 = @" namespace NS { record struct Point { } } "; var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,17): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 17), // (4,17): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 17), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(src4, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(src1); comp.VerifyDiagnostics( // (4,17): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 17), // (4,17): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 17), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31) ); comp = CreateCompilation(src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src3); comp.VerifyDiagnostics(); comp = CreateCompilation(src4); comp.VerifyDiagnostics(); } [Fact] public void TypeDeclaration_IsStruct() { var src = @" record struct Point(int x, int y); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validateModule, sourceSymbolValidator: validateModule); Assert.True(SyntaxFacts.IsTypeDeclaration(SyntaxKind.RecordStructDeclaration)); static void validateModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var point = module.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsValueType); Assert.False(point.IsReferenceType); Assert.False(point.IsRecord); Assert.Equal(TypeKind.Struct, point.TypeKind); Assert.Equal(SpecialType.System_ValueType, point.BaseTypeNoUseSiteDiagnostics.SpecialType); Assert.Equal("Point", point.ToTestDisplayString()); if (isSourceSymbol) { Assert.True(point is SourceNamedTypeSymbol); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); Assert.Equal("record struct Point", point.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } else { Assert.True(point is PENamedTypeSymbol); Assert.False(point.IsRecordStruct); Assert.False(point.GetPublicSymbol().IsRecord); Assert.Equal("struct Point", point.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } } } [Fact] public void TypeDeclaration_IsStruct_InConstraints() { var src = @" record struct Point(int x, int y); class C<T> where T : struct { void M(C<Point> c) { } } class C2<T> where T : new() { void M(C2<Point> c) { } } class C3<T> where T : class { void M(C3<Point> c) { } // 1 } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (16,22): error CS0452: The type 'Point' must be a reference type in order to use it as parameter 'T' in the generic type or method 'C3<T>' // void M(C3<Point> c) { } // 1 Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "c").WithArguments("C3<T>", "T", "Point").WithLocation(16, 22) ); } [Fact] public void TypeDeclaration_IsStruct_Unmanaged() { var src = @" record struct Point(int x, int y); record struct Point2(string x, string y); class C<T> where T : unmanaged { void M(C<Point> c) { } void M2(C<Point2> c) { } // 1 } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,23): error CS8377: The type 'Point2' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C<T>' // void M2(C<Point2> c) { } // 1 Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "c").WithArguments("C<T>", "T", "Point2").WithLocation(8, 23) ); } [Fact] public void IsRecord_Generic() { var src = @" record struct Point<T>(T x, T y); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validateModule, sourceSymbolValidator: validateModule); static void validateModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var point = module.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsValueType); Assert.False(point.IsReferenceType); Assert.False(point.IsRecord); Assert.Equal(TypeKind.Struct, point.TypeKind); Assert.Equal(SpecialType.System_ValueType, point.BaseTypeNoUseSiteDiagnostics.SpecialType); Assert.True(SyntaxFacts.IsTypeDeclaration(SyntaxKind.RecordStructDeclaration)); if (isSourceSymbol) { Assert.True(point is SourceNamedTypeSymbol); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); } else { Assert.True(point is PENamedTypeSymbol); Assert.False(point.IsRecordStruct); Assert.False(point.GetPublicSymbol().IsRecord); } } } [Fact] public void IsRecord_Retargeting() { var src = @" public record struct Point(int x, int y); "; var comp = CreateCompilation(src, targetFramework: TargetFramework.Mscorlib40); var comp2 = CreateCompilation("", targetFramework: TargetFramework.Mscorlib46, references: new[] { comp.ToMetadataReference() }); var point = comp2.GlobalNamespace.GetTypeMember("Point"); Assert.Equal("Point", point.ToTestDisplayString()); Assert.IsType<RetargetingNamedTypeSymbol>(point); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); } [Fact] public void IsRecord_AnonymousType() { var src = @" class C { void M() { var x = new { X = 1 }; } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var creation = tree.GetRoot().DescendantNodes().OfType<AnonymousObjectCreationExpressionSyntax>().Single(); var type = model.GetTypeInfo(creation).Type!; Assert.Equal("<anonymous type: System.Int32 X>", type.ToTestDisplayString()); Assert.IsType<AnonymousTypeManager.AnonymousTypePublicSymbol>(((Symbols.PublicModel.NonErrorNamedTypeSymbol)type).UnderlyingNamedTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_ErrorType() { var src = @" class C { Error M() => throw null; } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.ReturnType; Assert.Equal("Error", type.ToTestDisplayString()); Assert.IsType<ExtendedErrorTypeSymbol>(((Symbols.PublicModel.ErrorTypeSymbol)type).UnderlyingNamedTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_Pointer() { var src = @" class C { int* M() => throw null; } "; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.ReturnType; Assert.Equal("System.Int32*", type.ToTestDisplayString()); Assert.IsType<PointerTypeSymbol>(((Symbols.PublicModel.PointerTypeSymbol)type).UnderlyingTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_Dynamic() { var src = @" class C { void M(dynamic d) { } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.GetParameterType(0); Assert.Equal("dynamic", type.ToTestDisplayString()); Assert.IsType<DynamicTypeSymbol>(((Symbols.PublicModel.DynamicTypeSymbol)type).UnderlyingTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void TypeDeclaration_MayNotHaveBaseType() { var src = @" record struct Point(int x, int y) : object; record struct Point2(int x, int y) : System.ValueType; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,37): error CS0527: Type 'object' in interface list is not an interface // record struct Point(int x, int y) : object; Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "object").WithArguments("object").WithLocation(2, 37), // (3,38): error CS0527: Type 'ValueType' in interface list is not an interface // record struct Point2(int x, int y) : System.ValueType; Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "System.ValueType").WithArguments("System.ValueType").WithLocation(3, 38) ); } [Fact] public void TypeDeclaration_MayNotHaveTypeConstraintsWithoutTypeParameters() { var src = @" record struct Point(int x, int y) where T : struct; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,35): error CS0080: Constraints are not allowed on non-generic declarations // record struct Point(int x, int y) where T : struct; Diagnostic(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, "where").WithLocation(2, 35) ); } [Fact] public void TypeDeclaration_AllowedModifiers() { var src = @" readonly partial record struct S1; public record struct S2; internal record struct S3; public class Base { public int S6; } public class C : Base { private protected record struct S4; protected internal record struct S5; new record struct S6; } unsafe record struct S7; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics(); Assert.Equal(Accessibility.Internal, comp.GlobalNamespace.GetTypeMember("S1").DeclaredAccessibility); Assert.Equal(Accessibility.Public, comp.GlobalNamespace.GetTypeMember("S2").DeclaredAccessibility); Assert.Equal(Accessibility.Internal, comp.GlobalNamespace.GetTypeMember("S3").DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedAndInternal, comp.GlobalNamespace.GetTypeMember("C").GetTypeMember("S4").DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, comp.GlobalNamespace.GetTypeMember("C").GetTypeMember("S5").DeclaredAccessibility); } [Fact] public void TypeDeclaration_DisallowedModifiers() { var src = @" abstract record struct S1; volatile record struct S2; extern record struct S3; virtual record struct S4; override record struct S5; async record struct S6; ref record struct S7; unsafe record struct S8; static record struct S9; sealed record struct S10; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS0106: The modifier 'abstract' is not valid for this item // abstract record struct S1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S1").WithArguments("abstract").WithLocation(2, 24), // (3,24): error CS0106: The modifier 'volatile' is not valid for this item // volatile record struct S2; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S2").WithArguments("volatile").WithLocation(3, 24), // (4,22): error CS0106: The modifier 'extern' is not valid for this item // extern record struct S3; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S3").WithArguments("extern").WithLocation(4, 22), // (5,23): error CS0106: The modifier 'virtual' is not valid for this item // virtual record struct S4; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S4").WithArguments("virtual").WithLocation(5, 23), // (6,24): error CS0106: The modifier 'override' is not valid for this item // override record struct S5; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S5").WithArguments("override").WithLocation(6, 24), // (7,21): error CS0106: The modifier 'async' is not valid for this item // async record struct S6; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S6").WithArguments("async").WithLocation(7, 21), // (8,19): error CS0106: The modifier 'ref' is not valid for this item // ref record struct S7; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S7").WithArguments("ref").WithLocation(8, 19), // (9,22): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe record struct S8; Diagnostic(ErrorCode.ERR_IllegalUnsafe, "S8").WithLocation(9, 22), // (10,22): error CS0106: The modifier 'static' is not valid for this item // static record struct S9; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S9").WithArguments("static").WithLocation(10, 22), // (11,22): error CS0106: The modifier 'sealed' is not valid for this item // sealed record struct S10; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S10").WithArguments("sealed").WithLocation(11, 22) ); } [Fact] public void TypeDeclaration_DuplicatesModifiers() { var src = @" public public record struct S2; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,8): error CS1004: Duplicate 'public' modifier // public public record struct S2; Diagnostic(ErrorCode.ERR_DuplicateModifier, "public").WithArguments("public").WithLocation(2, 8) ); } [Fact] public void TypeDeclaration_BeforeTopLevelStatement() { var src = @" record struct S; System.Console.WriteLine(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine();").WithLocation(3, 1) ); } [Fact] public void TypeDeclaration_WithTypeParameters() { var src = @" S<string> local = default; local.ToString(); record struct S<T>; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); Assert.Equal(new[] { "T" }, comp.GlobalNamespace.GetTypeMember("S").TypeParameters.ToTestDisplayStrings()); } [Fact] public void TypeDeclaration_AllowedModifiersForMembers() { var src = @" record struct S { protected int Property { get; set; } // 1 internal protected string field; // 2, 3 abstract void M(); // 4 virtual void M2() { } // 5 }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0666: 'S.Property': new protected member declared in struct // protected int Property { get; set; } // 1 Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Property").WithArguments("S.Property").WithLocation(4, 19), // (5,31): error CS0666: 'S.field': new protected member declared in struct // internal protected string field; // 2, 3 Diagnostic(ErrorCode.ERR_ProtectedInStruct, "field").WithArguments("S.field").WithLocation(5, 31), // (5,31): warning CS0649: Field 'S.field' is never assigned to, and will always have its default value null // internal protected string field; // 2, 3 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("S.field", "null").WithLocation(5, 31), // (6,19): error CS0621: 'S.M()': virtual or abstract members cannot be private // abstract void M(); // 4 Diagnostic(ErrorCode.ERR_VirtualPrivate, "M").WithArguments("S.M()").WithLocation(6, 19), // (7,18): error CS0621: 'S.M2()': virtual or abstract members cannot be private // virtual void M2() { } // 5 Diagnostic(ErrorCode.ERR_VirtualPrivate, "M2").WithArguments("S.M2()").WithLocation(7, 18) ); } [Fact] public void TypeDeclaration_ImplementInterface() { var src = @" I i = (I)default(S); System.Console.Write(i.M(""four"")); I i2 = (I)default(S2); System.Console.Write(i2.M(""four"")); interface I { int M(string s); } public record struct S : I { public int M(string s) => s.Length; } public record struct S2 : I { int I.M(string s) => s.Length + 1; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "45"); AssertEx.Equal(new[] { "System.Int32 S.M(System.String s)", "readonly System.String S.ToString()", "readonly System.Boolean S.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean S.op_Inequality(S left, S right)", "System.Boolean S.op_Equality(S left, S right)", "readonly System.Int32 S.GetHashCode()", "readonly System.Boolean S.Equals(System.Object obj)", "readonly System.Boolean S.Equals(S other)", "S..ctor()" }, comp.GetMember<NamedTypeSymbol>("S").GetMembers().ToTestDisplayStrings()); } [Fact] public void TypeDeclaration_SatisfiesStructConstraint() { var src = @" S s = default; System.Console.Write(M(s)); static int M<T>(T t) where T : struct, I => t.Property; public interface I { int Property { get; } } public record struct S : I { public int Property => 42; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void TypeDeclaration_AccessingThis() { var src = @" S s = new S(); System.Console.Write(s.M()); public record struct S { public int Property => 42; public int M() => this.Property; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("S.M", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int S.Property.get"" IL_0006: ret } "); } [Fact] public void TypeDeclaration_NoBaseInitializer() { var src = @" public record struct S { public S(int i) : base() { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,12): error CS0522: 'S': structs cannot call base class constructors // public S(int i) : base() { } Diagnostic(ErrorCode.ERR_StructWithBaseConstructorCall, "S").WithArguments("S").WithLocation(4, 12) ); } [Fact] public void TypeDeclaration_ParameterlessConstructor_01() { var src = @"record struct S0(); record struct S1; record struct S2 { public S2() { } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S0(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(1, 8), // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8), // (3,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(3, 8), // (5,12): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // public S2() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S2").WithArguments("parameterless struct constructors", "10.0").WithLocation(5, 12)); var verifier = CompileAndVerify(src); verifier.VerifyIL("S0..ctor()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); verifier.VerifyMissing("S1..ctor()"); verifier.VerifyIL("S2..ctor()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [Fact] public void TypeDeclaration_ParameterlessConstructor_02() { var src = @"record struct S1 { S1() { } } record struct S2 { internal S2() { } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(1, 8), // (3,5): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // S1() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S1").WithArguments("parameterless struct constructors", "10.0").WithLocation(3, 5), // (3,5): error CS8938: The parameterless struct constructor must be 'public'. // S1() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S1").WithLocation(3, 5), // (5,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(5, 8), // (7,14): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // internal S2() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S2").WithArguments("parameterless struct constructors", "10.0").WithLocation(7, 14), // (7,14): error CS8938: The parameterless struct constructor must be 'public'. // internal S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(7, 14)); comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,5): error CS8918: The parameterless struct constructor must be 'public'. // S1() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S1").WithLocation(3, 5), // (7,14): error CS8918: The parameterless struct constructor must be 'public'. // internal S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(7, 14)); } [Fact] public void TypeDeclaration_ParameterlessConstructor_OtherConstructors() { var src = @" record struct S1 { public S1() { } S1(object o) { } // ok because no record parameter list } record struct S2 { S2(object o) { } } record struct S3() { S3(object o) { } // 1 } record struct S4() { S4(object o) : this() { } } record struct S5(object o) { public S5() { } // 2 } record struct S6(object o) { public S6() : this(null) { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,5): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // S3(object o) { } // 1 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "S3").WithLocation(13, 5), // (21,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public S5() { } // 2 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "S5").WithLocation(21, 12) ); } [Fact] public void TypeDeclaration_ParameterlessConstructor_Initializers() { var src = @" var s1 = new S1(); var s2 = new S2(null); var s2b = new S2(); var s3 = new S3(); var s4 = new S4(new object()); var s5 = new S5(); var s6 = new S6(""s6.other""); System.Console.Write((s1.field, s2.field, s2b.field is null, s3.field, s4.field, s5.field, s6.field, s6.other)); record struct S1 { public string field = ""s1""; public S1() { } } record struct S2 { public string field = ""s2""; public S2(object o) { } } record struct S3() { public string field = ""s3""; } record struct S4 { public string field = ""s4""; public S4(object o) : this() { } } record struct S5() { public string field = ""s5""; public S5(object o) : this() { } } record struct S6(string other) { public string field = ""s6.field""; public S6() : this(""ignored"") { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(s1, s2, True, s3, s4, s5, s6.field, s6.other)"); } [Fact] public void TypeDeclaration_InstanceInitializers() { var src = @" public record struct S { public int field = 42; public int Property { get; set; } = 43; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,15): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // public record struct S Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 15), // (4,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int field = 42; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "field").WithArguments("struct field initializers", "10.0").WithLocation(4, 16), // (5,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int Property { get; set; } = 43; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Property").WithArguments("struct field initializers", "10.0").WithLocation(5, 16)); comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void TypeDeclaration_NoDestructor() { var src = @" public record struct S { ~S() { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,6): error CS0575: Only class types can contain destructors // ~S() { } Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "S").WithArguments("S.~S()").WithLocation(4, 6) ); } [Fact] public void TypeDeclaration_DifferentPartials() { var src = @" partial record struct S1; partial struct S1 { } partial struct S2 { } partial record struct S2; partial record struct S3; partial record S3 { } partial record struct S4; partial record class S4 { } partial record struct S5; partial class S5 { } partial record struct S6; partial interface S6 { } partial record class C1; partial struct C1 { } partial record class C2; partial record struct C2 { } partial record class C3 { } partial record C3; partial record class C4; partial class C4 { } partial record class C5; partial interface C5 { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,16): error CS0261: Partial declarations of 'S1' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial struct S1 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S1").WithArguments("S1").WithLocation(3, 16), // (6,23): error CS0261: Partial declarations of 'S2' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record struct S2; Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S2").WithArguments("S2").WithLocation(6, 23), // (9,16): error CS0261: Partial declarations of 'S3' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record S3 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S3").WithArguments("S3").WithLocation(9, 16), // (12,22): error CS0261: Partial declarations of 'S4' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record class S4 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S4").WithArguments("S4").WithLocation(12, 22), // (15,15): error CS0261: Partial declarations of 'S5' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class S5 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S5").WithArguments("S5").WithLocation(15, 15), // (18,19): error CS0261: Partial declarations of 'S6' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial interface S6 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S6").WithArguments("S6").WithLocation(18, 19), // (21,16): error CS0261: Partial declarations of 'C1' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial struct C1 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C1").WithArguments("C1").WithLocation(21, 16), // (24,23): error CS0261: Partial declarations of 'C2' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record struct C2 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C2").WithArguments("C2").WithLocation(24, 23), // (30,15): error CS0261: Partial declarations of 'C4' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class C4 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C4").WithArguments("C4").WithLocation(30, 15), // (33,19): error CS0261: Partial declarations of 'C5' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial interface C5 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C5").WithArguments("C5").WithLocation(33, 19) ); } [Fact] public void PartialRecord_OnlyOnePartialHasParameterList() { var src = @" partial record struct S(int i); partial record struct S(int i); partial record struct S2(int i); partial record struct S2(); partial record struct S3(); partial record struct S3(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,24): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S(int i); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int i)").WithLocation(3, 24), // (6,25): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S2(); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "()").WithLocation(6, 25), // (9,25): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S3(); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "()").WithLocation(9, 25) ); } [Fact] public void PartialRecord_ParametersInScopeOfBothParts() { var src = @" var c = new C(2); System.Console.Write((c.P1, c.P2)); public partial record struct C(int X) { public int P1 { get; set; } = X; } public partial record struct C { public int P2 { get; set; } = X; } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */) .VerifyDiagnostics( // (5,30): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'C'. To specify an ordering, all instance fields must be in the same declaration. // public partial record struct C(int X) Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "C").WithArguments("C").WithLocation(5, 30) ); } [Fact] public void PartialRecord_DuplicateMemberNames() { var src = @" public partial record struct C(int X) { public void M(int i) { } } public partial record struct C { public void M(string s) { } } "; var comp = CreateCompilation(src); var expectedMemberNames = new string[] { ".ctor", "<X>k__BackingField", "get_X", "set_X", "X", "M", "M", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "Deconstruct", ".ctor", }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordInsideGenericType() { var src = @" var c = new C<int>.Nested(2); System.Console.Write(c.T); public class C<T> { public record struct Nested(T T); } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void PositionalMemberModifiers_RefOrOut() { var src = @" record struct R(ref int P1, out int P2); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,15): error CS0177: The out parameter 'P2' must be assigned to before control leaves the current method // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_ParamUnassigned, "R").WithArguments("P2").WithLocation(2, 15), // (2,17): error CS0631: ref and out are not valid in this context // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(2, 17), // (2,29): error CS0631: ref and out are not valid in this context // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(2, 29) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_This() { var src = @" record struct R(this int i); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,17): error CS0027: Keyword 'this' is not available in the current context // record struct R(this int i); Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(2, 17) ); } [Fact, WorkItem(45591, "https://github.com/dotnet/roslyn/issues/45591")] public void Clone_DisallowedInSource() { var src = @" record struct C1(string Clone); // 1 record struct C2 { string Clone; // 2 } record struct C3 { string Clone { get; set; } // 3 } record struct C5 { void Clone() { } // 4 void Clone(int i) { } // 5 } record struct C6 { class Clone { } // 6 } record struct C7 { delegate void Clone(); // 7 } record struct C8 { event System.Action Clone; // 8 } record struct Clone { Clone(int i) => throw null; } record struct C9 : System.ICloneable { object System.ICloneable.Clone() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,25): error CS8859: Members named 'Clone' are disallowed in records. // record struct C1(string Clone); // 1 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(2, 25), // (5,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone; // 2 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(5, 12), // (5,12): warning CS0169: The field 'C2.Clone' is never used // string Clone; // 2 Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C2.Clone").WithLocation(5, 12), // (9,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone { get; set; } // 3 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(9, 12), // (13,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone() { } // 4 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(13, 10), // (14,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone(int i) { } // 5 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(14, 10), // (18,11): error CS8859: Members named 'Clone' are disallowed in records. // class Clone { } // 6 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(18, 11), // (22,19): error CS8859: Members named 'Clone' are disallowed in records. // delegate void Clone(); // 7 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(22, 19), // (26,25): error CS8859: Members named 'Clone' are disallowed in records. // event System.Action Clone; // 8 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(26, 25), // (26,25): warning CS0067: The event 'C8.Clone' is never used // event System.Action Clone; // 8 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Clone").WithArguments("C8.Clone").WithLocation(26, 25) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes() { var src = @" class C<T> { } static class C2 { } ref struct RefLike{} unsafe record struct C( // 1 int* P1, // 2 int*[] P2, // 3 C<int*[]> P3, delegate*<int, int> P4, // 4 void P5, // 5 C2 P6, // 6, 7 System.ArgIterator P7, // 8 System.TypedReference P8, // 9 RefLike P9); // 10 "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (6,22): error CS0721: 'C2': static types cannot be used as parameters // unsafe record struct C( // 1 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C").WithArguments("C2").WithLocation(6, 22), // (7,10): error CS8908: The type 'int*' may not be used for a field of a record. // int* P1, // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P1").WithArguments("int*").WithLocation(7, 10), // (8,12): error CS8908: The type 'int*[]' may not be used for a field of a record. // int*[] P2, // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P2").WithArguments("int*[]").WithLocation(8, 12), // (10,25): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // delegate*<int, int> P4, // 4 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P4").WithArguments("delegate*<int, int>").WithLocation(10, 25), // (11,5): error CS1536: Invalid parameter type 'void' // void P5, // 5 Diagnostic(ErrorCode.ERR_NoVoidParameter, "void").WithLocation(11, 5), // (12,8): error CS0722: 'C2': static types cannot be used as return types // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (12,8): error CS0721: 'C2': static types cannot be used as parameters // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (13,5): error CS0610: Field or property cannot be of type 'ArgIterator' // System.ArgIterator P7, // 8 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 5), // (14,5): error CS0610: Field or property cannot be of type 'TypedReference' // System.TypedReference P8, // 9 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 5), // (15,5): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // RefLike P9); // 10 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 5) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record struct C { public int* f1; // 1 public int*[] f2; // 2 public C<int*[]> f3; public delegate*<int, int> f4; // 3 public void f5; // 4 public C2 f6; // 5 public System.ArgIterator f7; // 6 public System.TypedReference f8; // 7 public RefLike f9; // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1; // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2; // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4; // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,12): error CS0670: Field cannot have void type // public void f5; // 4 Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void").WithLocation(12, 12), // (13,15): error CS0723: Cannot declare a variable of static type 'C2' // public C2 f6; // 5 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(13, 15), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7; // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8; // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9; // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers_AutoProperties() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record struct C { public int* f1 { get; set; } // 1 public int*[] f2 { get; set; } // 2 public C<int*[]> f3 { get; set; } public delegate*<int, int> f4 { get; set; } // 3 public void f5 { get; set; } // 4 public C2 f6 { get; set; } // 5, 6 public System.ArgIterator f7 { get; set; } // 6 public System.TypedReference f8 { get; set; } // 7 public RefLike f9 { get; set; } // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1 { get; set; } // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2 { get; set; } // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4 { get; set; } // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,17): error CS0547: 'C.f5': property or indexer cannot have void type // public void f5 { get; set; } // 4 Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "f5").WithArguments("C.f5").WithLocation(12, 17), // (13,20): error CS0722: 'C2': static types cannot be used as return types // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("C2").WithLocation(13, 20), // (13,25): error CS0721: 'C2': static types cannot be used as parameters // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("C2").WithLocation(13, 25), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7 { get; set; } // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8 { get; set; } // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9 { get; set; } // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [Fact] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_PointerTypeAllowedForParameterAndProperty() { var src = @" class C<T> { } unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) { int* P1 { get { System.Console.Write(""P1 ""); return null; } init { } } int*[] P2 { get { System.Console.Write(""P2 ""); return null; } init { } } C<int*[]> P3 { get { System.Console.Write(""P3 ""); return null; } init { } } public unsafe static void Main() { var x = new C(null, null, null); var (x1, x2, x3) = x; System.Console.Write(""RAN""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugExe); comp.VerifyEmitDiagnostics( // (4,29): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(4, 29), // (4,40): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(4, 40), // (4,54): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(4, 54) ); CompileAndVerify(comp, expectedOutput: "P1 P2 P3 RAN", verify: Verification.Skipped /* pointers */); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_StaticFields() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public static int* f1; public static int*[] f2; public static C<int*[]> f3; public static delegate*<int, int> f4; public static C2 f6; // 1 public static System.ArgIterator f7; // 2 public static System.TypedReference f8; // 3 public static RefLike f9; // 4 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (12,22): error CS0723: Cannot declare a variable of static type 'C2' // public static C2 f6; // 1 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(12, 22), // (13,19): error CS0610: Field or property cannot be of type 'ArgIterator' // public static System.ArgIterator f7; // 2 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 19), // (14,19): error CS0610: Field or property cannot be of type 'TypedReference' // public static System.TypedReference f8; // 3 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 19), // (15,19): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public static RefLike f9; // 4 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 19) ); } [Fact] public void RecordProperties_01() { var src = @" using System; record struct C(int X, int Y) { int Z = 345; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); Console.Write(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"12345").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 26 (0x1a) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4 0x159 IL_0014: stfld ""int C.Z"" IL_0019: ret } "); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); Assert.False(c.IsReadOnly); var x = (IPropertySymbol)c.GetMember("X"); Assert.Equal("readonly System.Int32 C.X.get", x.GetMethod.ToTestDisplayString()); Assert.Equal("void C.X.set", x.SetMethod.ToTestDisplayString()); Assert.False(x.SetMethod!.IsInitOnly); var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField"); Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString()); Assert.False(xBackingField.IsReadOnly); } [Fact] public void RecordProperties_01_EmptyParameterList() { var src = @" using System; record struct C() { int Z = 345; public static void Main() { var c = new C(); Console.Write(c.Z); } }"; CreateCompilation(src).VerifyEmitDiagnostics(); } [Fact] public void RecordProperties_01_Readonly() { var src = @" using System; readonly record struct C(int X, int Y) { readonly int Z = 345; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); Console.Write(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"12345").VerifyDiagnostics(); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); Assert.True(c.IsReadOnly); var x = (IPropertySymbol)c.GetMember("X"); Assert.Equal("System.Int32 C.X.get", x.GetMethod.ToTestDisplayString()); Assert.Equal("void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init", x.SetMethod.ToTestDisplayString()); Assert.True(x.SetMethod!.IsInitOnly); var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField"); Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString()); Assert.True(xBackingField.IsReadOnly); } [Fact] public void RecordProperties_01_ReadonlyMismatch() { var src = @" readonly record struct C(int X) { public int X { get; set; } = X; // 1 } record struct C2(int X) { public int X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,16): error CS8341: Auto-implemented instance properties in readonly structs must be readonly. // public int X { get; set; } = X; // 1 Diagnostic(ErrorCode.ERR_AutoPropsInRoStruct, "X").WithLocation(4, 16) ); } [Fact] public void RecordProperties_02() { var src = @" using System; record struct C(int X, int Y) { public C(int a, int b) { } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } private int X1 = X; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types // public C(int a, int b) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(5, 12), // (5,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public C(int a, int b) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(5, 12), // (11,21): error CS0121: The call is ambiguous between the following methods or properties: 'C.C(int, int)' and 'C.C(int, int)' // var c = new C(1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "C").WithArguments("C.C(int, int)", "C.C(int, int)").WithLocation(11, 21) ); } [Fact] public void RecordProperties_03() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,15): error CS0843: Auto-implemented property 'C.X' must be fully assigned before control is returned to the caller. // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "C").WithArguments("C.X").WithLocation(3, 15), // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_03_InitializedWithY() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } = Y; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); } }"; CompileAndVerify(src, expectedOutput: "22") .VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_04() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } = 3; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); } }"; CompileAndVerify(src, expectedOutput: "32") .VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_05() { var src = @" record struct C(int X, int X) { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,28): error CS0100: The parameter name 'X' is a duplicate // record struct C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 28), // (2,28): error CS0102: The type 'C' already contains a definition for 'X' // record struct C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 28) ); var expectedMembers = new[] { "System.Int32 C.X { get; set; }", "System.Int32 C.X { get; set; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var expectedMemberNames = new[] { ".ctor", "<X>k__BackingField", "get_X", "set_X", "X", "<X>k__BackingField", "get_X", "set_X", "X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "Deconstruct", ".ctor" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordProperties_06() { var src = @" record struct C(int X, int Y) { public void get_X() { } public void set_X() { } int get_Y(int value) => value; int set_Y(int value) => value; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,21): error CS0082: Type 'C' already reserves a member called 'get_X' with the same parameter types // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "X").WithArguments("get_X", "C").WithLocation(2, 21), // (2,28): error CS0082: Type 'C' already reserves a member called 'set_Y' with the same parameter types // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "Y").WithArguments("set_Y", "C").WithLocation(2, 28) ); var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "System.Int32 C.<X>k__BackingField", "readonly System.Int32 C.X.get", "void C.X.set", "System.Int32 C.X { get; set; }", "System.Int32 C.<Y>k__BackingField", "readonly System.Int32 C.Y.get", "void C.Y.set", "System.Int32 C.Y { get; set; }", "void C.get_X()", "void C.set_X()", "System.Int32 C.get_Y(System.Int32 value)", "System.Int32 C.set_Y(System.Int32 value)", "readonly System.String C.ToString()", "readonly System.Boolean C.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C left, C right)", "System.Boolean C.op_Equality(C left, C right)", "readonly System.Int32 C.GetHashCode()", "readonly System.Boolean C.Equals(System.Object obj)", "readonly System.Boolean C.Equals(C other)", "readonly void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", "C..ctor()", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void RecordProperties_07() { var comp = CreateCompilation(@" record struct C1(object P, object get_P); record struct C2(object get_P, object P);"); comp.VerifyDiagnostics( // (2,25): error CS0102: The type 'C1' already contains a definition for 'get_P' // record struct C1(object P, object get_P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C1", "get_P").WithLocation(2, 25), // (3,39): error CS0102: The type 'C2' already contains a definition for 'get_P' // record struct C2(object get_P, object P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C2", "get_P").WithLocation(3, 39) ); } [Fact] public void RecordProperties_08() { var comp = CreateCompilation(@" record struct C1(object O1) { public object O1 { get; } = O1; public object O2 { get; } = O1; }"); comp.VerifyDiagnostics(); } [Fact] public void RecordProperties_09() { var src = @" record struct C(object P1, object P2, object P3, object P4) { class P1 { } object P2 = 2; int P3(object o) => 3; int P4<T>(T t) => 4; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS0102: The type 'C' already contains a definition for 'P1' // record struct C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(2, 24), // (2,35): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record struct C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(2, 35), // (6,9): error CS0102: The type 'C' already contains a definition for 'P3' // int P3(object o) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(6, 9), // (7,9): error CS0102: The type 'C' already contains a definition for 'P4' // int P4<T>(T t) => 4; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(7, 9) ); } [Fact] public void RecordProperties_10() { var src = @" record struct C(object P) { const int P = 4; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'. // record struct C(object P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "object", "P").WithLocation(2, 24), // (2,24): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct C(object P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 24) ); } [Fact] public void RecordProperties_11_UnreadPositionalParameter() { var comp = CreateCompilation(@" record struct C1(object O1, object O2, object O3) // 1, 2 { public object O1 { get; init; } public object O2 { get; init; } = M(O2); public object O3 { get; init; } = M(O3 = null); private static object M(object o) => o; } "); comp.VerifyDiagnostics( // (2,15): error CS0843: Auto-implemented property 'C1.O1' must be fully assigned before control is returned to the caller. // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "C1").WithArguments("C1.O1").WithLocation(2, 15), // (2,25): warning CS8907: Parameter 'O1' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O1").WithArguments("O1").WithLocation(2, 25), // (2,47): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 47) ); } [Fact] public void RecordProperties_11_UnreadPositionalParameter_InRefOut() { var comp = CreateCompilation(@" record struct C1(object O1, object O2, object O3) // 1 { public object O1 { get; init; } = MIn(in O1); public object O2 { get; init; } = MRef(ref O2); public object O3 { get; init; } = MOut(out O3); static object MIn(in object o) => o; static object MRef(ref object o) => o; static object MOut(out object o) => throw null; } "); comp.VerifyDiagnostics( // (2,47): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 47) ); } [Fact] public void RecordProperties_SelfContainedStruct() { var comp = CreateCompilation(@" record struct C(C c); "); comp.VerifyDiagnostics( // (2,19): error CS0523: Struct member 'C.c' of type 'C' causes a cycle in the struct layout // record struct C(C c); Diagnostic(ErrorCode.ERR_StructLayoutCycle, "c").WithArguments("C.c", "C").WithLocation(2, 19) ); } [Fact] public void RecordProperties_PropertyInValueType() { var corlib_cs = @" namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public bool X { get; set; } } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var corlibRef = CreateEmptyCompilation(corlib_cs).EmitToImageReference(); { var src = @" record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,22): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 22) ); Assert.Null(comp.GlobalNamespace.GetTypeMember("C").GetMember("X")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().Expression; Assert.Equal("System.Boolean System.ValueType.X { get; set; }", model.GetSymbolInfo(x!).Symbol.ToTestDisplayString()); } { var src = @" readonly record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,31): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // readonly record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 31) ); Assert.Null(comp.GlobalNamespace.GetTypeMember("C").GetMember("X")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().Expression; Assert.Equal("System.Boolean System.ValueType.X { get; set; }", model.GetSymbolInfo(x!).Symbol.ToTestDisplayString()); } } [Fact] public void RecordProperties_PropertyInValueType_Static() { var corlib_cs = @" namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public static bool X { get; set; } } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var corlibRef = CreateEmptyCompilation(corlib_cs).EmitToImageReference(); var src = @" record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,22): error CS8866: Record member 'System.ValueType.X' must be a readable instance property or field of type 'bool' to match positional parameter 'X'. // record struct C(bool X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("System.ValueType.X", "bool", "X").WithLocation(2, 22), // (2,22): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 22) ); } [Fact] public void StaticCtor() { var src = @" record R(int x) { static void Main() { } static R() { System.Console.Write(""static ctor""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "static ctor", verify: Verification.Skipped /* init-only */); } [Fact] public void StaticCtor_ParameterlessPrimaryCtor() { var src = @" record struct R(int I) { static R() { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void StaticCtor_CopyCtor() { var src = @" record struct R(int I) { static R(R r) { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,12): error CS0132: 'R.R(R)': a static constructor must be parameterless // static R(R r) { } Diagnostic(ErrorCode.ERR_StaticConstParam, "R").WithArguments("R.R(R)").WithLocation(4, 12) ); } [Fact] public void InterfaceImplementation_NotReadonly() { var source = @" I r = new R(42); r.P2 = 43; r.P3 = 44; System.Console.Write((r.P1, r.P2, r.P3)); interface I { int P1 { get; set; } int P2 { get; set; } int P3 { get; set; } } record struct R(int P1) : I { public int P2 { get; set; } = 0; int I.P3 { get; set; } = 0; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44)"); } [Fact] public void InterfaceImplementation_NotReadonly_InitOnlyInterface() { var source = @" interface I { int P1 { get; init; } } record struct R(int P1) : I; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,27): error CS8854: 'R' does not implement interface member 'I.P1.init'. 'R.P1.set' cannot implement 'I.P1.init'. // record struct R(int P1) : I; Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("R", "I.P1.init", "R.P1.set").WithLocation(6, 27) ); } [Fact] public void InterfaceImplementation_Readonly() { var source = @" I r = new R(42) { P2 = 43 }; System.Console.Write((r.P1, r.P2)); interface I { int P1 { get; init; } int P2 { get; init; } } readonly record struct R(int P1) : I { public int P2 { get; init; } = 0; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43)", verify: Verification.Skipped /* init-only */); } [Fact] public void InterfaceImplementation_Readonly_SetInterface() { var source = @" interface I { int P1 { get; set; } } readonly record struct R(int P1) : I; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,36): error CS8854: 'R' does not implement interface member 'I.P1.set'. 'R.P1.init' cannot implement 'I.P1.set'. // readonly record struct R(int P1) : I; Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("R", "I.P1.set", "R.P1.init").WithLocation(6, 36) ); } [Fact] public void InterfaceImplementation_Readonly_PrivateImplementation() { var source = @" I r = new R(42) { P2 = 43, P3 = 44 }; System.Console.Write((r.P1, r.P2, r.P3)); interface I { int P1 { get; init; } int P2 { get; init; } int P3 { get; init; } } readonly record struct R(int P1) : I { public int P2 { get; init; } = 0; int I.P3 { get; init; } = 0; // not practically initializable } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,28): error CS0117: 'R' does not contain a definition for 'P3' // I r = new R(42) { P2 = 43, P3 = 44 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "P3").WithArguments("R", "P3").WithLocation(2, 28) ); } [Fact] public void Initializers_01() { var src = @" using System; record struct C(int X) { int Z = X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Single(); Assert.Equal("C", recordDeclaration.Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclaration)); } [Fact] public void Initializers_02() { var src = @" record struct C(int X) { static int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,20): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // static int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 20) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; set; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_03() { var src = @" record struct C(int X) { const int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // const int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 19) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; set; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_04() { var src = @" using System; record struct C(int X) { Func<int> Z = () => X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z()); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("() => X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("lambda expression", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void SynthesizedRecordPointerProperty() { var src = @" record struct R(int P1, int* P2, delegate*<int> P3);"; var comp = CreateCompilation(src); var p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P1"); Assert.False(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P2"); Assert.True(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P3"); Assert.True(p.HasPointerType); } [Fact] public void PositionalMemberModifiers_In() { var src = @" var r = new R(42); int i = 43; var r2 = new R(in i); System.Console.Write((r.P1, r2.P1)); record struct R(in int P1); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "(42, 43)"); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(in System.Int32 P1)", "R..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void PositionalMemberModifiers_Params() { var src = @" var r = new R(42, 43); var r2 = new R(new[] { 44, 45 }); System.Console.Write((r.Array[0], r.Array[1], r2.Array[0], r2.Array[1])); record struct R(params int[] Array); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44, 45)"); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(params System.Int32[] Array)", "R..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void PositionalMemberDefaultValue() { var src = @" var r = new R(); // This uses the parameterless constructor System.Console.Write(r.P); record struct R(int P = 42); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "0"); } [Fact] public void PositionalMemberDefaultValue_PassingOneArgument() { var src = @" var r = new R(41); System.Console.Write(r.O); System.Console.Write("" ""); System.Console.Write(r.P); record struct R(int O, int P = 42); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "41 42"); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithInitializer() { var src = @" var r = new R(0); System.Console.Write(r.P); record struct R(int O, int P = 1) { public int P { get; init; } = 42; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,28): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int O, int P = 1) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(5, 28) ); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int, int)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<O>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldc.i4.s 42 IL_000a: stfld ""int R.<P>k__BackingField"" IL_000f: ret }"); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithoutInitializer() { var src = @" record struct R(int P = 42) { public int P { get; init; } public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): error CS0843: Auto-implemented property 'R.P' must be fully assigned before control is returned to the caller. // record struct R(int P = 42) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "R").WithArguments("R.P").WithLocation(2, 15), // (2,21): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int P = 42) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 21) ); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithInitializer_CopyingParameter() { var src = @" var r = new R(0); System.Console.Write(r.P); record struct R(int O, int P = 42) { public int P { get; init; } = P; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int, int)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<O>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int R.<P>k__BackingField"" IL_000e: ret }"); } [Fact] public void RecordWithConstraints_NullableWarning() { var src = @" #nullable enable var r = new R<string?>(""R""); var r2 = new R2<string?>(""R2""); System.Console.Write((r.P, r2.P)); record struct R<T>(T P) where T : class; record struct R2<T>(T P) where T : class { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,15): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r = new R<string?>("R"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R<T>", "T", "string?").WithLocation(3, 15), // (4,17): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R2<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r2 = new R2<string?>("R2"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R2<T>", "T", "string?").WithLocation(4, 17) ); CompileAndVerify(comp, expectedOutput: "(R, R2)"); } [Fact] public void RecordWithConstraints_ConstraintError() { var src = @" record struct R<T>(T P) where T : class; record struct R2<T>(T P) where T : class { } public class C { public static void Main() { _ = new R<int>(1); _ = new R2<int>(2); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,19): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R<T>' // _ = new R<int>(1); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R<T>", "T", "int").WithLocation(9, 19), // (10,20): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R2<T>' // _ = new R2<int>(2); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R2<T>", "T", "int").WithLocation(10, 20) ); } [Fact] public void CyclicBases4() { var text = @" record struct A<T> : B<A<T>> { } record struct B<T> : A<B<T>> { A<T> F() { return null; } } "; var comp = CreateCompilation(text); comp.GetDeclarationDiagnostics().Verify( // (3,22): error CS0527: Type 'A<B<T>>' in interface list is not an interface // record struct B<T> : A<B<T>> Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "A<B<T>>").WithArguments("A<B<T>>").WithLocation(3, 22), // (2,22): error CS0527: Type 'B<A<T>>' in interface list is not an interface // record struct A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "B<A<T>>").WithArguments("B<A<T>>").WithLocation(2, 22) ); } [Fact] public void PartialClassWithDifferentTupleNamesInImplementedInterfaces() { var source = @" public interface I<T> { } public partial record C1 : I<(int a, int b)> { } public partial record C1 : I<(int notA, int notB)> { } public partial record C2 : I<(int a, int b)> { } public partial record C2 : I<(int, int)> { } public partial record C3 : I<(int a, int b)> { } public partial record C3 : I<(int a, int b)> { } public partial record C4 : I<(int a, int b)> { } public partial record C4 : I<(int b, int a)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,23): error CS8140: 'I<(int notA, int notB)>' is already listed in the interface list on type 'C1' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C1 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C1").WithArguments("I<(int notA, int notB)>", "I<(int a, int b)>", "C1").WithLocation(3, 23), // (6,23): error CS8140: 'I<(int, int)>' is already listed in the interface list on type 'C2' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C2 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C2").WithArguments("I<(int, int)>", "I<(int a, int b)>", "C2").WithLocation(6, 23), // (12,23): error CS8140: 'I<(int b, int a)>' is already listed in the interface list on type 'C4' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C4 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C4").WithArguments("I<(int b, int a)>", "I<(int a, int b)>", "C4").WithLocation(12, 23) ); } [Fact] public void CS0267ERR_PartialMisplaced() { var test = @" partial public record struct C // CS0267 { } "; CreateCompilation(test).VerifyDiagnostics( // (2,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial public record struct C // CS0267 Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1) ); } [Fact] public void SealedStaticRecord() { var source = @" sealed static record struct R; "; CreateCompilation(source).VerifyDiagnostics( // (2,29): error CS0106: The modifier 'sealed' is not valid for this item // sealed static record struct R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("sealed").WithLocation(2, 29), // (2,29): error CS0106: The modifier 'static' is not valid for this item // sealed static record struct R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 29) ); } [Fact] public void CS0513ERR_AbstractInConcreteClass02() { var text = @" record struct C { public abstract event System.Action E; public abstract int this[int x] { get; set; } } "; CreateCompilation(text).VerifyDiagnostics( // (5,25): error CS0106: The modifier 'abstract' is not valid for this item // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(5, 25), // (4,41): error CS0106: The modifier 'abstract' is not valid for this item // public abstract event System.Action E; Diagnostic(ErrorCode.ERR_BadMemberFlag, "E").WithArguments("abstract").WithLocation(4, 41) ); } [Fact] public void CS0574ERR_BadDestructorName() { var test = @" public record struct iii { ~iiii(){} } "; CreateCompilation(test).VerifyDiagnostics( // (4,6): error CS0574: Name of destructor must match name of type // ~iiii(){} Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(4, 6), // (4,6): error CS0575: Only class types can contain destructors // ~iiii(){} Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "iiii").WithArguments("iii.~iii()").WithLocation(4, 6) ); } [Fact] public void StaticRecordWithConstructorAndDestructor() { var text = @" static record struct R(int I) { public R() : this(0) { } ~R() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,22): error CS0106: The modifier 'static' is not valid for this item // static record struct R(int I) Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 22), // (5,6): error CS0575: Only class types can contain destructors // ~R() { } Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "R").WithArguments("R.~R()").WithLocation(5, 6) ); } [Fact] public void RecordWithPartialMethodExplicitImplementation() { var source = @"record struct R { partial void M(); }"; CreateCompilation(source).VerifyDiagnostics( // (3,18): error CS0751: A partial method must be declared within a partial type // partial void M(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 18) ); } [Fact] public void RecordWithPartialMethodRequiringBody() { var source = @"partial record struct R { public partial int M(); }"; CreateCompilation(source).VerifyDiagnostics( // (3,24): error CS8795: Partial method 'R.M()' must have an implementation part because it has accessibility modifiers. // public partial int M(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M").WithArguments("R.M()").WithLocation(3, 24) ); } [Fact] public void CanDeclareIteratorInRecord() { var source = @" using System.Collections.Generic; foreach(var i in new X(42).GetItems()) { System.Console.Write(i); } public record struct X(int a) { public IEnumerable<int> GetItems() { yield return a; yield return a + 1; } }"; var comp = CreateCompilation(source).VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "4243"); } [Fact] public void ParameterlessConstructor() { var src = @" System.Console.Write(new C().Property); record struct C() { public int Property { get; set; } = 42; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void XmlDoc() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record struct C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact] public void XmlDoc_Cref() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for <see cref=""I1""/></param> public record struct C(int I1) { /// <summary>Summary</summary> /// <param name=""x"">Description for <see cref=""x""/></param> public void M(int x) { } } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,52): warning CS1574: XML comment has cref attribute 'x' that could not be resolved // /// <param name="x">Description for <see cref="x"/></param> Diagnostic(ErrorCode.WRN_BadXMLRef, "x").WithArguments("x").WithLocation(7, 52) ); var tree = comp.SyntaxTrees.Single(); var docComments = tree.GetCompilationUnitRoot().DescendantTrivia().Select(trivia => trivia.GetStructure()).OfType<DocumentationCommentTriviaSyntax>(); var cref = docComments.First().DescendantNodes().OfType<XmlCrefAttributeSyntax>().First().Cref; Assert.Equal("I1", cref.ToString()); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal(SymbolKind.Property, model.GetSymbolInfo(cref).Symbol!.Kind); } [Fact] public void Deconstruct_Simple() { var source = @"using System; record struct B(int X, int Y) { public static void Main() { M(new B(1, 2)); } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""readonly int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""readonly int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); var deconstruct = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("B.Deconstruct"); Assert.Equal(2, deconstruct.ParameterCount); Assert.Equal(RefKind.Out, deconstruct.Parameters[0].RefKind); Assert.Equal("X", deconstruct.Parameters[0].Name); Assert.Equal(RefKind.Out, deconstruct.Parameters[1].RefKind); Assert.Equal("Y", deconstruct.Parameters[1].Name); Assert.True(deconstruct.ReturnsVoid); Assert.False(deconstruct.IsVirtual); Assert.False(deconstruct.IsStatic); Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility); } [Fact] public void Deconstruct_PositionalAndNominalProperty() { var source = @"using System; record struct B(int X) { public int Y { get; init; } = 0; public static void Main() { M(new B(1)); } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal( "readonly void B.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Nested() { var source = @"using System; record struct B(int X, int Y); record struct C(B B, int Z) { public static void Main() { M(new C(new B(1, 2), 3)); } static void M(C c) { switch (c) { case C(B(int x, int y), int z): Console.Write(x); Console.Write(y); Console.Write(z); break; } } } "; var verifier = CompileAndVerify(source, expectedOutput: "123"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""readonly int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""readonly int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""readonly B C.B.get"" IL_0007: stobj ""B"" IL_000c: ldarg.2 IL_000d: ldarg.0 IL_000e: call ""readonly int C.Z.get"" IL_0013: stind.i4 IL_0014: ret }"); } [Fact] public void Deconstruct_PropertyCollision() { var source = @"using System; record struct B(int X, int Y) { public int X => 3; static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "32"); verifier.VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct B(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_01() { var source = @" record struct B(int X, int Y) { public int X() => 3; static void M(B b) { switch (b) { case B(int x, int y): break; } } static void Main() { M(new B(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS0102: The type 'B' already contains a definition for 'X' // public int X() => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("B", "X").WithLocation(4, 16) ); Assert.Equal( "readonly void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_FieldCollision() { var source = @" using System; record struct C(int X) { int X = 0; static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(0)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 21), // (6,9): warning CS0414: The field 'C.X' is assigned but its value is never used // int X = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "X").WithArguments("C.X").WithLocation(6, 9)); Assert.Equal( "readonly void C.Deconstruct(out System.Int32 X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty() { var source = @" record struct C { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); Assert.Null(comp.GetMember("C.Deconstruct")); } [Fact] public void Deconstruct_Conversion_02() { var source = @" #nullable enable using System; record struct C(string? X, string Y) { public string X { get; init; } = null!; public string? Y { get; init; } = string.Empty; static void M(C c) { switch (c) { case C(var x, string y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(""a"", ""b"")); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,25): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 25), // (5,35): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record struct C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 35) ); Assert.Equal( "readonly void C.Deconstruct(out System.String? X, out System.String Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty_WithParameterList() { var source = @" record struct C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); AssertEx.Equal(new[] { "C..ctor()", "void C.M(C c)", "void C.Main()", "readonly System.String C.ToString()", "readonly System.Boolean C.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C left, C right)", "System.Boolean C.op_Equality(C left, C right)", "readonly System.Int32 C.GetHashCode()", "readonly System.Boolean C.Equals(System.Object obj)", "readonly System.Boolean C.Equals(C other)" }, comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings()); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_01() { var source = @"using System; record struct C(int I) { public void Deconstruct() { } static void M(C c) { switch (c) { case C(): Console.Write(12); break; } } public static void Main() { M(new C(42)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordDeconstruct>("A.Deconstruct"); Assert.True(method.IsDeclaredReadOnly); } [Fact] public void Deconstruct_WihtNonReadOnlyGetter_GeneratedAsNonReadOnly() { var src = @" record struct A(int I, string S) { public int I { get => 0; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // record struct A(int I, string S) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 21)); var method = comp.GetMember<SynthesizedRecordDeconstruct>("A.Deconstruct"); Assert.False(method.IsDeclaredReadOnly); } [Fact] public void Deconstruct_UserDefined() { var source = @"using System; record struct B(int X, int Y) { public void Deconstruct(out int X, out int Y) { X = this.X + 1; Y = this.Y + 2; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(0, 0)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_02() { var source = @"using System; record struct B(int X) { public int Deconstruct(out int a) => throw null; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,16): error CS8874: Record member 'B.Deconstruct(out int)' must return 'void'. // public int Deconstruct(out int a) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Deconstruct").WithArguments("B.Deconstruct(out int)", "void").WithLocation(5, 16), // (11,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'B', with 1 out parameters and a void return type. // case B(int x): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int x)").WithArguments("B", "1").WithLocation(11, 19)); Assert.Equal("System.Int32 B.Deconstruct(out System.Int32 a)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] public void Deconstruct_UserDefined_Accessibility_07(string accessibility) { var source = $@" record struct A(int X) {{ { accessibility } void Deconstruct(out int a) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,11): error CS8873: Record member 'A.Deconstruct(out int)' must be public. // void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 11 + accessibility.Length) ); } [Fact] public void Deconstruct_UserDefined_Static_08() { var source = @" record struct A(int X) { public static void Deconstruct(out int a) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS8877: Record member 'A.Deconstruct(out int)' may not be static. // public static void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 24) ); } [Fact] public void OutVarInPositionalParameterDefaultValue() { var source = @" record struct A(int X = A.M(out int a) + a) { public static int M(out int a) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,25): error CS1736: Default parameter value for 'X' must be a compile-time constant // record struct A(int X = A.M(out int a) + a) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "A.M(out int a) + a").WithArguments("X").WithLocation(2, 25) ); } [Fact] public void FieldConsideredUnassignedIfInitializationViaProperty() { var source = @" record struct Pos(int X) { private int x; public int X { get { return x; } set { x = value; } } = X; } record struct Pos2(int X) { private int x = X; // value isn't validated by setter public int X { get { return x; } set { x = value; } } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0171: Field 'Pos.x' must be fully assigned before control is returned to the caller // record struct Pos(int X) Diagnostic(ErrorCode.ERR_UnassignedThis, "Pos").WithArguments("Pos.x").WithLocation(2, 15), // (5,16): error CS8050: Only auto-implemented properties can have initializers. // public int X { get { return x; } set { x = value; } } = X; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "X").WithArguments("Pos.X").WithLocation(5, 16) ); } [Fact] public void IEquatableT_01() { var source = @"record struct A<T>; class Program { static void F<T>(System.IEquatable<T> t) { } static void M<T>() { F(new A<T>()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( ); } [Fact] public void IEquatableT_02() { var source = @"using System; record struct A; record struct B<T>; class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "TrueTrue").VerifyDiagnostics(); } [Fact] public void IEquatableT_02_ImplicitImplementation() { var source = @"using System; record struct A { public bool Equals(A other) { System.Console.Write(""A.Equals(A) ""); return false; } } record struct B<T> { public bool Equals(B<T> other) { System.Console.Write(""B.Equals(B) ""); return true; } } class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write("" ""); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "A.Equals(A) False B.Equals(B) True").VerifyDiagnostics( // (4,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 17), // (12,17): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public bool Equals(B<T> other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(12, 17) ); } [Fact] public void IEquatableT_02_ExplicitImplementation() { var source = @"using System; record struct A { bool IEquatable<A>.Equals(A other) { System.Console.Write(""A.Equals(A) ""); return false; } } record struct B<T> { bool IEquatable<B<T>>.Equals(B<T> other) { System.Console.Write(""B.Equals(B) ""); return true; } } class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write("" ""); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "A.Equals(A) False B.Equals(B) True").VerifyDiagnostics(); } [Fact] public void IEquatableT_03() { var source = @" record struct A<T> : System.IEquatable<A<T>>; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_MissingIEquatable() { var source = @" record struct A<T>; "; var comp = CreateCompilation(source); comp.MakeTypeMissing(WellKnownType.System_IEquatable_T); comp.VerifyEmitDiagnostics( // (2,15): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record struct A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record struct A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 15) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void RecordEquals_01() { var source = @" var a1 = new B(); var a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); record struct B { public bool Equals(B other) { System.Console.WriteLine(""B.Equals(B)""); return false; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,17): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public bool Equals(B other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(8, 17) ); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False "); } [Fact] public void RecordEquals_01_NoInParameters() { var source = @" var a1 = new B(); var a2 = new B(); System.Console.WriteLine(a1.Equals(in a2)); record struct B; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,39): error CS1615: Argument 1 may not be passed with the 'in' keyword // System.Console.WriteLine(a1.Equals(in a2)); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "a2").WithArguments("1", "in").WithLocation(4, 39) ); } [Theory] [InlineData("protected")] [InlineData("private protected")] [InlineData("internal protected")] public void RecordEquals_10(string accessibility) { var source = $@" record struct A {{ { accessibility } bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,29): error CS0666: 'A.Equals(A)': new protected member declared in struct // internal protected bool Equals(A x) Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,29): error CS8873: Record member 'A.Equals(A)' must be public. // internal protected bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,29): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // internal protected bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 11 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] public void RecordEquals_11(string accessibility) { var source = $@" record struct A {{ { accessibility } bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,...): error CS8873: Record member 'A.Equals(A)' must be public. // { accessibility } bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,11): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 11 + accessibility.Length) ); } [Fact] public void RecordEquals_12() { var source = @" A a1 = new A(); A a2 = new A(); System.Console.Write(a1.Equals(a2)); System.Console.Write(a1.Equals((object)a2)); record struct A { public bool Equals(B other) => throw null; } class B { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueTrue"); verifier.VerifyIL("A.Equals(A)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("A.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""A"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""A"" IL_000f: call ""readonly bool A.Equals(A)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("readonly System.Boolean A.Equals(A other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.False(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); var objectEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordObjEquals>().Single(); Assert.Equal("readonly System.Boolean A.Equals(System.Object obj)", objectEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, objectEquals.DeclaredAccessibility); Assert.False(objectEquals.IsAbstract); Assert.False(objectEquals.IsVirtual); Assert.True(objectEquals.IsOverride); Assert.False(objectEquals.IsSealed); Assert.True(objectEquals.IsImplicitlyDeclared); MethodSymbol gethashCode = comp.GetMembers("A." + WellKnownMemberNames.ObjectGetHashCode).OfType<SynthesizedRecordGetHashCode>().Single(); Assert.Equal("readonly System.Int32 A.GetHashCode()", gethashCode.ToTestDisplayString()); Assert.Equal(Accessibility.Public, gethashCode.DeclaredAccessibility); Assert.False(gethashCode.IsStatic); Assert.False(gethashCode.IsAbstract); Assert.False(gethashCode.IsVirtual); Assert.True(gethashCode.IsOverride); Assert.False(gethashCode.IsSealed); Assert.True(gethashCode.IsImplicitlyDeclared); } [Fact] public void RecordEquals_13() { var source = @" record struct A { public int Equals(A other) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,16): error CS8874: Record member 'A.Equals(A)' must return 'bool'. // public int Equals(A other) Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 16), // (4,16): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public int Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 16) ); } [Fact] public void RecordEquals_14() { var source = @" record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (4,12): error CS0518: Predefined type 'System.Boolean' is not defined or imported // public bool Equals(A other) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(4, 12), // (4,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 17) ); } [Fact] public void RecordEquals_19() { var source = @" record struct A { public static bool Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is static. // record struct A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 15), // (4,24): error CS8877: Record member 'A.Equals(A)' may not be static. // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void RecordEquals_RecordEqualsInValueType() { var src = @" public record struct A; namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public bool Equals(A x) => throw null; } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) ); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("readonly System.Boolean A.Equals(A other)", recordEquals.ToTestDisplayString()); } [Fact] public void RecordEquals_FourFields() { var source = @" A a1 = new A(1, ""hello""); System.Console.Write(a1.Equals(a1)); System.Console.Write(a1.Equals((object)a1)); System.Console.Write("" - ""); A a2 = new A(1, ""hello"") { fieldI = 100 }; System.Console.Write(a1.Equals(a2)); System.Console.Write(a1.Equals((object)a2)); System.Console.Write(a2.Equals(a1)); System.Console.Write(a2.Equals((object)a1)); System.Console.Write("" - ""); A a3 = new A(1, ""world""); System.Console.Write(a1.Equals(a3)); System.Console.Write(a1.Equals((object)a3)); System.Console.Write(a3.Equals(a1)); System.Console.Write(a3.Equals((object)a1)); record struct A(int I, string S) { public int fieldI = 42; public string fieldS = ""hello""; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueTrue - FalseFalseFalseFalse - FalseFalseFalseFalse"); verifier.VerifyIL("A.Equals(A)", @" { // Code size 97 (0x61) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int A.<I>k__BackingField"" IL_000b: ldarg.1 IL_000c: ldfld ""int A.<I>k__BackingField"" IL_0011: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0016: brfalse.s IL_005f IL_0018: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_001d: ldarg.0 IL_001e: ldfld ""string A.<S>k__BackingField"" IL_0023: ldarg.1 IL_0024: ldfld ""string A.<S>k__BackingField"" IL_0029: callvirt ""bool System.Collections.Generic.EqualityComparer<string>.Equals(string, string)"" IL_002e: brfalse.s IL_005f IL_0030: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0035: ldarg.0 IL_0036: ldfld ""int A.fieldI"" IL_003b: ldarg.1 IL_003c: ldfld ""int A.fieldI"" IL_0041: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0046: brfalse.s IL_005f IL_0048: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_004d: ldarg.0 IL_004e: ldfld ""string A.fieldS"" IL_0053: ldarg.1 IL_0054: ldfld ""string A.fieldS"" IL_0059: callvirt ""bool System.Collections.Generic.EqualityComparer<string>.Equals(string, string)"" IL_005e: ret IL_005f: ldc.i4.0 IL_0060: ret }"); verifier.VerifyIL("A.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""A"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""A"" IL_000f: call ""readonly bool A.Equals(A)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 86 (0x56) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int A.<I>k__BackingField"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_0010: ldc.i4 0xa5555529 IL_0015: mul IL_0016: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""string A.<S>k__BackingField"" IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<string>.GetHashCode(string)"" IL_0026: add IL_0027: ldc.i4 0xa5555529 IL_002c: mul IL_002d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0032: ldarg.0 IL_0033: ldfld ""int A.fieldI"" IL_0038: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_003d: add IL_003e: ldc.i4 0xa5555529 IL_0043: mul IL_0044: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_0049: ldarg.0 IL_004a: ldfld ""string A.fieldS"" IL_004f: callvirt ""int System.Collections.Generic.EqualityComparer<string>.GetHashCode(string)"" IL_0054: add IL_0055: ret }"); } [Fact] public void RecordEquals_StaticField() { var source = @" record struct A { public static int field = 42; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("A.Equals(A)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); } [Fact] public void RecordEquals_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.True(recordEquals.IsDeclaredReadOnly); } [Fact] public void ObjectEquals_06() { var source = @" record struct A { public static new bool Equals(object obj) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,28): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public static new bool Equals(object obj) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(4, 28) ); } [Fact] public void ObjectEquals_UserDefined() { var source = @" record struct A { public override bool Equals(object obj) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,26): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public override bool Equals(object obj) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(4, 26) ); } [Fact] public void ObjectEquals_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var objectEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordObjEquals>().Single(); Assert.True(objectEquals.IsDeclaredReadOnly); } [Fact] public void GetHashCode_UserDefined() { var source = @" System.Console.Write(new A().GetHashCode()); record struct A { public override int GetHashCode() => 42; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void GetHashCode_GetHashCodeInValueType() { var src = @" public record struct A; namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public virtual int GetHashCode() => throw null; } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (2,22): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public record struct A; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "A").WithArguments("A.GetHashCode()").WithLocation(2, 22) ); } [Fact] public void GetHashCode_MissingEqualityComparer_EmptyRecord() { var src = @" public record struct A; "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Collections_Generic_EqualityComparer_T); comp.VerifyEmitDiagnostics(); } [Fact] public void GetHashCode_MissingEqualityComparer_NonEmptyRecord() { var src = @" public record struct A(int I); "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Collections_Generic_EqualityComparer_T); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // public record struct A(int I); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "public record struct A(int I);").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // public record struct A(int I); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "public record struct A(int I);").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1) ); } [Fact] public void GetHashCode_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordGetHashCode>("A.GetHashCode"); Assert.True(method.IsDeclaredReadOnly); } [Fact] public void GetHashCodeIsDefinedButEqualsIsNot() { var src = @" public record struct C { public object Data; public override int GetHashCode() { return 0; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void EqualsIsDefinedButGetHashCodeIsNot() { var src = @" public record struct C { public object Data; public bool Equals(C c) { return false; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public bool Equals(C c) { return false; } Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(5, 17)); } [Fact] public void EqualityOperators_01() { var source = @" record struct A(int X) { public bool Equals(ref A other) => throw null; static void Main() { Test(default, default); Test(default, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); var a = new A(11); Test(a, a); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } "; var verifier = CompileAndVerify(source, expectedOutput: @" True True False False True True False False True True False False False False True True True True False False ").VerifyDiagnostics(); var comp = (CSharpCompilation)verifier.Compilation; MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(); Assert.Equal("System.Boolean A.op_Equality(A left, A right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single(); Assert.Equal("System.Boolean A.op_Inequality(A left, A right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); verifier.VerifyIL("bool A.op_Equality(A, A)", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: ldarg.1 IL_0003: call ""readonly bool A.Equals(A)"" IL_0008: ret } "); verifier.VerifyIL("bool A.op_Inequality(A, A)", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool A.op_Equality(A, A)"" IL_0007: ldc.i4.0 IL_0008: ceq IL_000a: ret } "); } [Fact] public void EqualityOperators_03() { var source = @" record struct A { public static bool operator==(A r1, A r2) => throw null; public static bool operator==(A r1, string r2) => throw null; public static bool operator!=(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool operator==(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "==").WithArguments("op_Equality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_04() { var source = @" record struct A { public static bool operator!=(A r1, A r2) => throw null; public static bool operator!=(string r1, A r2) => throw null; public static bool operator==(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool operator!=(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "!=").WithArguments("op_Inequality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_05() { var source = @" record struct A { public static bool op_Equality(A r1, A r2) => throw null; public static bool op_Equality(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool op_Equality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Equality").WithArguments("op_Equality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_06() { var source = @" record struct A { public static bool op_Inequality(A r1, A r2) => throw null; public static bool op_Inequality(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool op_Inequality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Inequality").WithArguments("op_Inequality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_07() { var source = @" record struct A { public static bool Equals(A other) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is static. // record struct A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 15), // (4,24): error CS8877: Record member 'A.Equals(A)' may not be static. // public static bool Equals(A other) Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Theory] [CombinatorialData] public void EqualityOperators_09(bool useImageReference) { var source1 = @" public record struct A(int X); "; var comp1 = CreateCompilation(source1); var source2 = @" class Program { static void Main() { Test(default, default); Test(default, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } "; CompileAndVerify(source2, references: new[] { useImageReference ? comp1.EmitToImageReference() : comp1.ToMetadataReference() }, expectedOutput: @" True True False False True True False False True True False False False False True True ").VerifyDiagnostics(); } [Fact] public void GetSimpleNonTypeMembers_DirectApiCheck() { var src = @" public record struct RecordB(); "; var comp = CreateCompilation(src); var b = comp.GlobalNamespace.GetTypeMember("RecordB"); AssertEx.SetEqual(new[] { "System.Boolean RecordB.op_Equality(RecordB left, RecordB right)" }, b.GetSimpleNonTypeMembers("op_Equality").ToTestDisplayStrings()); } [Fact] public void ToString_NestedRecord() { var src = @" var c1 = new Outer.C1(42); System.Console.Write(c1.ToString()); public class Outer { public record struct C1(int I1); } "; var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }"); compDebug.VerifyEmitDiagnostics(); CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }"); compRelease.VerifyEmitDiagnostics(); } [Fact] public void ToString_TopLevelRecord_Empty() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: call ""readonly bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilder() { var src = @" record struct C1; "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Text_StringBuilder); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record struct C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "record struct C1;").WithArguments("System.Text.StringBuilder").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record struct C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C1").WithArguments("System.Text.StringBuilder").WithLocation(2, 15) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderCtor() { var src = @" record struct C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__ctor); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderAppendString() { var src = @" record struct C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendString() { var src = @" record struct C1(int P); "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record struct C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record struct C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_RecordWithIndexer() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); record struct C1(int I1) { private int field = 44; public int this[int i] => 0; public int PropertyWithoutGetter { set { } } public int P2 { get => 43; } public event System.Action a = null; private int field1 = 100; internal int field2 = 100; private int Property1 { get; set; } = 100; internal int Property2 { get; set; } = 100; } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "C1 { I1 = 42, P2 = 43 }"); comp.VerifyEmitDiagnostics( // (7,17): warning CS0414: The field 'C1.field' is assigned but its value is never used // private int field = 44; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C1.field").WithLocation(7, 17), // (11,32): warning CS0414: The field 'C1.a' is assigned but its value is never used // public event System.Action a = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("C1.a").WithLocation(11, 32), // (13,17): warning CS0414: The field 'C1.field1' is assigned but its value is never used // private int field1 = 100; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field1").WithArguments("C1.field1").WithLocation(13, 17) ); } [Fact] public void ToString_PrivateGetter() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1 { public int P1 { private get => 43; set => throw null; } } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "C1 { P1 = 43 }"); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_TopLevelRecord_OneField_ValueType() { var src = @" var c1 = new C1() { field = 42 }; System.Console.Write(c1.ToString()); record struct C1 { public int field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 38 (0x26) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""field = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldflda ""int C1.field"" IL_0013: constrained. ""int"" IL_0019: callvirt ""string object.ToString()"" IL_001e: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0023: pop IL_0024: ldc.i4.1 IL_0025: ret } "); } [Fact] public void ToString_TopLevelRecord_OneField_ConstrainedValueType() { var src = @" var c1 = new C1<int>() { field = 42 }; System.Console.Write(c1.ToString()); record struct C1<T> where T : struct { public T field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 41 (0x29) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.1 IL_0001: ldstr ""field = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldfld ""T C1<T>.field"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""T"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldc.i4.1 IL_0028: ret } "); } [Fact] public void ToString_TopLevelRecord_OneField_ReferenceType() { var src = @" var c1 = new C1() { field = ""hello"" }; System.Console.Write(c1.ToString()); record struct C1 { public string field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""field = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldfld ""string C1.field"" IL_0013: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0018: pop IL_0019: ldc.i4.1 IL_001a: ret } "); } [Fact] public void ToString_TopLevelRecord_TwoFields_ReferenceType() { var src = @" var c1 = new C1(42) { field1 = ""hi"", field2 = null }; System.Console.Write(c1.ToString()); record struct C1(int I) { public string field1 = null; public string field2 = null; private string field3 = null; internal string field4 = null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (10,20): warning CS0414: The field 'C1.field3' is assigned but its value is never used // private string field3 = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field3").WithArguments("C1.field3").WithLocation(10, 20) ); var v = CompileAndVerify(comp, expectedOutput: "C1 { I = 42, field1 = hi, field2 = }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 91 (0x5b) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldstr ""I = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: call ""readonly int C1.I.get"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""int"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldarg.1 IL_0028: ldstr "", field1 = "" IL_002d: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0032: pop IL_0033: ldarg.1 IL_0034: ldarg.0 IL_0035: ldfld ""string C1.field1"" IL_003a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_003f: pop IL_0040: ldarg.1 IL_0041: ldstr "", field2 = "" IL_0046: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_004b: pop IL_004c: ldarg.1 IL_004d: ldarg.0 IL_004e: ldfld ""string C1.field2"" IL_0053: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0058: pop IL_0059: ldc.i4.1 IL_005a: ret } "); } [Fact] public void ToString_TopLevelRecord_Readonly() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); readonly record struct C1(int I); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { I = 42 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 41 (0x29) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldstr ""I = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: call ""int C1.I.get"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""int"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldc.i4.1 IL_0028: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: call ""bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1 { public override string ToString() => ""RAN""; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal("readonly System.Boolean C1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", print.ToTestDisplayString()); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_New() { var src = @" record struct C1 { public new string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,23): error CS8869: 'C1.ToString()' does not override expected method from 'object'. // public new string ToString() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "ToString").WithArguments("C1.ToString()").WithLocation(4, 23) ); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_Sealed() { var src = @" record struct C1 { public sealed override string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,35): error CS0106: The modifier 'sealed' is not valid for this item // public sealed override string ToString() => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "ToString").WithArguments("sealed").WithLocation(4, 35) ); } [Fact] public void ToString_UserDefinedPrintMembers_WithNullableStringBuilder() { var src = @" #nullable enable record struct C1 { private bool PrintMembers(System.Text.StringBuilder? builder) => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_ErrorReturnType() { var src = @" record struct C1 { private Error PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,13): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // private Error PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 13) ); } [Fact] public void ToString_UserDefinedPrintMembers_WrongReturnType() { var src = @" record struct C1 { private int PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,17): error CS8874: Record member 'C1.PrintMembers(StringBuilder)' must return 'bool'. // private int PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "bool").WithLocation(4, 17) ); } [Fact] public void ToString_UserDefinedPrintMembers() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); System.Console.Write("" - ""); c1.M(); record struct C1 { private bool PrintMembers(System.Text.StringBuilder builder) { builder.Append(""RAN""); return true; } public void M() { var builder = new System.Text.StringBuilder(); if (PrintMembers(builder)) { System.Console.Write(builder.ToString()); } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { RAN } - RAN"); } [Fact] public void ToString_CallingSynthesizedPrintMembers() { var src = @" var c1 = new C1(1, 2, 3); System.Console.Write(c1.ToString()); System.Console.Write("" - ""); c1.M(); record struct C1(int I, int I2, int I3) { public void M() { var builder = new System.Text.StringBuilder(); if (PrintMembers(builder)) { System.Console.Write(builder.ToString()); } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { I = 1, I2 = 2, I3 = 3 } - I = 1, I2 = 2, I3 = 3"); } [Fact] public void ToString_UserDefinedPrintMembers_WrongAccessibility() { var src = @" var c = new C1(); System.Console.Write(c.ToString()); record struct C1 { internal bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (7,19): error CS8879: Record member 'C1.PrintMembers(StringBuilder)' must be private. // internal bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(7, 19) ); } [Fact] public void ToString_UserDefinedPrintMembers_Static() { var src = @" record struct C1 { static private bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,25): error CS8877: Record member 'C1.PrintMembers(StringBuilder)' may not be static. // static private bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25) ); } [Fact] public void ToString_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordToString>("A.ToString"); Assert.True(method.IsDeclaredReadOnly); } [Fact] public void ToString_WihtNonReadOnlyGetter_GeneratedAsNonReadOnly() { var src = @" record struct A(int I, string S) { public double T => 0.1; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordToString>("A.ToString"); Assert.False(method.IsDeclaredReadOnly); } [Fact] public void AmbigCtor_WithPropertyInitializer() { // Scenario causes ambiguous ctor for record class, but not record struct var src = @" record struct R(R X) { public R X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,14): error CS0523: Struct member 'R.X' of type 'R' causes a cycle in the struct layout // public R X { get; init; } = X; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "X").WithArguments("R.X", "R").WithLocation(4, 14) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var parameterSyntax = tree.GetRoot().DescendantNodes().OfType<ParameterSyntax>().Single(); var parameter = model.GetDeclaredSymbol(parameterSyntax)!; Assert.Equal("R X", parameter.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, parameter.Kind); Assert.Equal("R..ctor(R X)", parameter.ContainingSymbol.ToTestDisplayString()); var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); var initializer = model.GetSymbolInfo(initializerSyntax.Value).Symbol!; Assert.Equal("R X", initializer.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, initializer.Kind); Assert.Equal("R..ctor(R X)", initializer.ContainingSymbol.ToTestDisplayString()); var src2 = @" record struct R(R X); "; var comp2 = CreateCompilation(src2); comp2.VerifyEmitDiagnostics( // (2,19): error CS0523: Struct member 'R.X' of type 'R' causes a cycle in the struct layout // record struct R(R X); Diagnostic(ErrorCode.ERR_StructLayoutCycle, "X").WithArguments("R.X", "R").WithLocation(2, 19) ); } [Fact] public void GetDeclaredSymbolOnAnOutLocalInPropertyInitializer() { var src = @" record struct R(int I) { public int I { get; init; } = M(out int i); static int M(out int i) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 21) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var outVarSyntax = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Single(); var outVar = model.GetDeclaredSymbol(outVarSyntax)!; Assert.Equal("System.Int32 i", outVar.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, outVar.Kind); Assert.Equal("System.Int32 R.<I>k__BackingField", outVar.ContainingSymbol.ToTestDisplayString()); } [Fact] public void AnalyzerActions_01() { // Test RegisterSyntaxNodeAction var text1 = @" record struct A([Attr1]int X = 0) : I1 { private int M() => 3; A(string S) : this(4) => throw null; } interface I1 {} class Attr1 : System.Attribute {} "; var analyzer = new AnalyzerActions_01_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(1, analyzer.FireCountRecordStructDeclarationA); Assert.Equal(1, analyzer.FireCountRecordStructDeclarationACtor); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCountSimpleBaseTypeI1onA); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCountParameterListAPrimaryCtor); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCountConstructorDeclaration); Assert.Equal(1, analyzer.FireCountStringParameterList); Assert.Equal(1, analyzer.FireCountThisConstructorInitializer); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); } private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer { public int FireCount0; public int FireCountRecordStructDeclarationA; public int FireCountRecordStructDeclarationACtor; public int FireCount3; public int FireCountSimpleBaseTypeI1onA; public int FireCount5; public int FireCountParameterListAPrimaryCtor; public int FireCount7; public int FireCountConstructorDeclaration; public int FireCountStringParameterList; public int FireCountThisConstructorInitializer; public int FireCount11; public int FireCount12; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.ThisConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordStructDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); } protected void Handle1(SyntaxNodeAnalysisContext context) { var literal = (LiteralExpressionSyntax)context.Node; switch (literal.ToString()) { case "0": Interlocked.Increment(ref FireCount0); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "3": Interlocked.Increment(ref FireCount7); Assert.Equal("System.Int32 A.M()", context.ContainingSymbol.ToTestDisplayString()); break; case "4": Interlocked.Increment(ref FireCount12); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(literal.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle2(SyntaxNodeAnalysisContext context) { var equalsValue = (EqualsValueClauseSyntax)context.Node; switch (equalsValue.ToString()) { case "= 0": Interlocked.Increment(ref FireCount3); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(equalsValue.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle3(SyntaxNodeAnalysisContext context) { var initializer = (ConstructorInitializerSyntax)context.Node; switch (initializer.ToString()) { case ": this(4)": Interlocked.Increment(ref FireCountThisConstructorInitializer); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(initializer.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle4(SyntaxNodeAnalysisContext context) { Interlocked.Increment(ref FireCountConstructorDeclaration); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); } protected void Fail(SyntaxNodeAnalysisContext context) { Assert.True(false); } protected void Handle6(SyntaxNodeAnalysisContext context) { var record = (RecordDeclarationSyntax)context.Node; Assert.Equal(SyntaxKind.RecordStructDeclaration, record.Kind()); switch (context.ContainingSymbol.ToTestDisplayString()) { case "A": Interlocked.Increment(ref FireCountRecordStructDeclarationA); break; case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCountRecordStructDeclarationACtor); break; default: Assert.True(false); break; } Assert.Same(record.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle7(SyntaxNodeAnalysisContext context) { var identifier = (IdentifierNameSyntax)context.Node; switch (identifier.Identifier.ValueText) { case "Attr1": Interlocked.Increment(ref FireCount5); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; } } protected void Handle8(SyntaxNodeAnalysisContext context) { var baseType = (SimpleBaseTypeSyntax)context.Node; switch (baseType.ToString()) { case "I1": switch (context.ContainingSymbol.ToTestDisplayString()) { case "A": Interlocked.Increment(ref FireCountSimpleBaseTypeI1onA); break; default: Assert.True(false); break; } break; case "System.Attribute": break; default: Assert.True(false); break; } } protected void Handle9(SyntaxNodeAnalysisContext context) { var parameterList = (ParameterListSyntax)context.Node; switch (parameterList.ToString()) { case "([Attr1]int X = 0)": Interlocked.Increment(ref FireCountParameterListAPrimaryCtor); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "(string S)": Interlocked.Increment(ref FireCountStringParameterList); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; case "()": break; default: Assert.True(false); break; } } protected void Handle10(SyntaxNodeAnalysisContext context) { var argumentList = (ArgumentListSyntax)context.Node; switch (argumentList.ToString()) { case "(4)": Interlocked.Increment(ref FireCount11); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_02() { // Test RegisterSymbolAction var text1 = @" record struct A(int X = 0) {} record struct C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_02_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); } private class AnalyzerActions_02_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.Method); context.RegisterSymbolAction(Handle, SymbolKind.Property); context.RegisterSymbolAction(Handle, SymbolKind.Parameter); context.RegisterSymbolAction(Handle, SymbolKind.NamedType); } private void Handle(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "System.Int32 A.X { get; set; }": Interlocked.Increment(ref FireCount2); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount6); break; case "C": Interlocked.Increment(ref FireCount7); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_03() { // Test RegisterSymbolStartAction var text1 = @" readonly record struct A(int X = 0) {} readonly record struct C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_03_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(0, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(0, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); } private class AnalyzerActions_03_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolStartAction(Handle1, SymbolKind.Method); context.RegisterSymbolStartAction(Handle1, SymbolKind.Property); context.RegisterSymbolStartAction(Handle1, SymbolKind.Parameter); context.RegisterSymbolStartAction(Handle1, SymbolKind.NamedType); } private void Handle1(SymbolStartAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); context.RegisterSymbolEndAction(Handle2); break; case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount2); context.RegisterSymbolEndAction(Handle3); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); context.RegisterSymbolEndAction(Handle4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount9); Assert.Equal(0, FireCount1); Assert.Equal(0, FireCount2); Assert.Equal(0, FireCount6); Assert.Equal(0, FireCount7); context.RegisterSymbolEndAction(Handle5); break; case "C": Interlocked.Increment(ref FireCount10); Assert.Equal(0, FireCount4); Assert.Equal(0, FireCount8); context.RegisterSymbolEndAction(Handle6); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { Assert.Equal("A..ctor([System.Int32 X = 0])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); } private void Handle3(SymbolAnalysisContext context) { Assert.Equal("System.Int32 A.X { get; init; }", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); } private void Handle4(SymbolAnalysisContext context) { Assert.Equal("C..ctor([System.Int32 Z = 4])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); } private void Handle5(SymbolAnalysisContext context) { Assert.Equal("A", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount11); Assert.Equal(1, FireCount1); Assert.Equal(1, FireCount2); Assert.Equal(1, FireCount6); Assert.Equal(1, FireCount7); } private void Handle6(SymbolAnalysisContext context) { Assert.Equal("C", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount12); Assert.Equal(1, FireCount4); Assert.Equal(1, FireCount8); } } [Fact] public void AnalyzerActions_04() { // Test RegisterOperationAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 {} interface I1 {} "; var analyzer = new AnalyzerActions_04_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(0, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount14); } private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount6; public int FireCount7; public int FireCount14; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationAction(HandleConstructorBody, OperationKind.ConstructorBody); context.RegisterOperationAction(HandleInvocation, OperationKind.Invocation); context.RegisterOperationAction(HandleLiteral, OperationKind.Literal); context.RegisterOperationAction(HandleParameterInitializer, OperationKind.ParameterInitializer); context.RegisterOperationAction(Fail, OperationKind.PropertyInitializer); context.RegisterOperationAction(Fail, OperationKind.FieldInitializer); } protected void HandleConstructorBody(OperationAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind()); VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation, @""); break; default: Assert.True(false); break; } } protected void HandleInvocation(OperationAnalysisContext context) { Assert.True(false); } protected void HandleLiteral(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "100": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); break; case "0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); break; default: Assert.True(false); break; } } protected void HandleParameterInitializer(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "= 0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount14); break; default: Assert.True(false); break; } } protected void Fail(OperationAnalysisContext context) { Assert.True(false); } } [Fact] public void AnalyzerActions_05() { // Test RegisterOperationBlockAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 {} interface I1 {} "; var analyzer = new AnalyzerActions_05_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); } private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer { public int FireCount1; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockAction(Handle); } private void Handle(OperationBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_07() { // Test RegisterCodeBlockAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 { int M() => 3; } interface I1 {} "; var analyzer = new AnalyzerActions_07_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(Handle); } private void Handle(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1); break; default: Assert.True(false); break; } break; case "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_08() { // Test RegisterCodeBlockStartAction var text1 = @" record struct A([Attr1]int X = 0) : I1 { private int M() => 3; A(string S) : this(4) => throw null; } interface I1 {} "; var analyzer = new AnalyzerActions_08_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount100); Assert.Equal(1, analyzer.FireCount400); Assert.Equal(1, analyzer.FireCount500); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(0, analyzer.FireCountRecordStructDeclarationA); Assert.Equal(0, analyzer.FireCountRecordStructDeclarationACtor); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(0, analyzer.FireCountSimpleBaseTypeI1onA); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(0, analyzer.FireCountParameterListAPrimaryCtor); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(0, analyzer.FireCountConstructorDeclaration); Assert.Equal(0, analyzer.FireCountStringParameterList); Assert.Equal(1, analyzer.FireCountThisConstructorInitializer); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount1000); Assert.Equal(1, analyzer.FireCount4000); Assert.Equal(1, analyzer.FireCount5000); } private class AnalyzerActions_08_Analyzer : AnalyzerActions_01_Analyzer { public int FireCount100; public int FireCount400; public int FireCount500; public int FireCount1000; public int FireCount4000; public int FireCount5000; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(Handle); } private void Handle(CodeBlockStartAnalysisContext<SyntaxKind> context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount100); break; default: Assert.True(false); break; } break; case "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount400); break; default: Assert.True(false); break; } break; case "A..ctor(System.String S)": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount500); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.ThisConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordStructDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); context.RegisterCodeBlockEndAction(Handle11); } private void Handle11(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1000); break; default: Assert.True(false); break; } break; case "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4000); break; default: Assert.True(false); break; } break; case "A..ctor(System.String S)": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount5000); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_09() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_09_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); } private class AnalyzerActions_09_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle1, SymbolKind.Method); context.RegisterSymbolAction(Handle2, SymbolKind.Property); context.RegisterSymbolAction(Handle3, SymbolKind.Parameter); } private void Handle1(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount5); break; case "System.Int32 B.Y { get; init; }": Interlocked.Increment(ref FireCount6); break; default: Assert.True(false); break; } } private void Handle3(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount7); break; case "[System.Int32 Y = 1]": Interlocked.Increment(ref FireCount8); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount9); break; default: Assert.True(false); break; } } } [Fact] public void WithExprOnStruct_LangVersion() { var src = @" var b = new B() { X = 1 }; var b2 = b.M(); System.Console.Write(b2.X); System.Console.Write("" ""); System.Console.Write(b.X); public struct B { public int X { get; set; } public B M() /*<bind>*/{ return this with { X = 42 }; }/*</bind>*/ }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (13,16): error CS8773: Feature 'with on structs' is not available in C# 9.0. Please use language version 10.0 or greater. // return this with { X = 42 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "this with { X = 42 }").WithArguments("with on structs", "10.0").WithLocation(13, 16) ); comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 1"); verifier.VerifyIL("B.M", @" { // Code size 18 (0x12) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: ldobj ""B"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: ldc.i4.s 42 IL_000b: call ""void B.X.set"" IL_0010: ldloc.0 IL_0011: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var with = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var type = model.GetTypeInfo(with); Assert.Equal("B", type.Type.ToTestDisplayString()); var operation = model.GetOperation(with); VerifyOperationTree(comp, operation, @" IWithOperation (OperationKind.With, Type: B) (Syntax: 'this with { X = 42 }') Operand: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: B) (Syntax: '{ X = 42 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'X') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_DuplicateInitialization() { var src = @" public struct B { public int X { get; set; } public B M() /*<bind>*/{ return this with { X = 42, X = 43 }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (8,36): error CS1912: Duplicate initialization of member 'X' // return this with { X = 42, X = 43 }; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(8, 36) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'X = 43') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 43) (Syntax: '43') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_NestedInitializer() { var src = @" public struct C { public int Y { get; set; } } public struct B { public C X { get; set; } public B M() /*<bind>*/{ return this with { X = { Y = 1 } }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (12,32): error CS1525: Invalid expression term '{' // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "{").WithArguments("{").WithLocation(12, 32), // (12,32): error CS1513: } expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(12, 32), // (12,32): error CS1002: ; expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(12, 32), // (12,34): error CS0103: The name 'Y' does not exist in the current context // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_NameNotInContext, "Y").WithArguments("Y").WithLocation(12, 34), // (12,34): warning CS0162: Unreachable code detected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.WRN_UnreachableCode, "Y").WithLocation(12, 34), // (12,40): error CS1002: ; expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(12, 40), // (12,43): error CS1597: Semicolon after method or accessor block is not valid // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(12, 43), // (14,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(14, 1) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsInvalid) (Syntax: 'X = ') Left: IPropertyReferenceOperation: C B.X { get; set; } (OperationKind.PropertyReference, Type: C) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Next (Return) Block[B3] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Y = 1 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Y = 1') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Y') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_NonAssignmentExpression() { var src = @" public struct B { public int X { get; set; } public B M(int i, int j) /*<bind>*/{ return this with { i, j++, M2(), X = 2}; }/*</bind>*/ static int M2() => 0; }"; var expectedDiagnostics = new[] { // (8,28): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "i").WithLocation(8, 28), // (8,31): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "j++").WithLocation(8, 31), // (8,36): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "M2()").WithLocation(8, 36) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'j++') Children(1): IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32, IsInvalid) (Syntax: 'j++') Target: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2()') Children(1): IInvocationOperation (System.Int32 B.M2()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void ObjectCreationInitializer_ControlFlow_WithCoalescingExpressionForValue() { var src = @" public struct B { public string X; public void M(string hello) /*<bind>*/{ var x = new B() { X = Identity((string)null) ?? Identity(hello) }; }/*</bind>*/ T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [B x] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Value: IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B) (Syntax: 'new B() { X ... ty(hello) }') Arguments(0) Initializer: null 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: 'Identity((string)null)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity((string)null)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '(string)null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') 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) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity((string)null)') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(hello)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(hello)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'hello') IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') 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) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'X = Identit ... tity(hello)') Left: IFieldReferenceOperation: System.String B.X (OperationKind.FieldReference, Type: System.String) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((s ... tity(hello)') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: B, IsImplicit) (Syntax: 'x = new B() ... ty(hello) }') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: B, IsImplicit) (Syntax: 'x = new B() ... ty(hello) }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics); } [Fact] public void WithExprOnStruct_ControlFlow_WithCoalescingExpressionForValue() { var src = @" var b = new B() { X = string.Empty }; var b2 = b.M(""hello""); System.Console.Write(b2.X); public struct B { public string X; public B M(string hello) /*<bind>*/{ return Identity(this) with { X = Identity((string)null) ?? Identity(hello) }; }/*</bind>*/ T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "hello"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(this)') Value: IInvocationOperation ( B B.Identity<B>(B t)) (OperationKind.Invocation, Type: B) (Syntax: 'Identity(this)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'this') IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') 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) 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: 'Identity((string)null)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity((string)null)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '(string)null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') 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) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity((string)null)') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(hello)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(hello)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'hello') IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') 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) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'X = Identit ... tity(hello)') Left: IFieldReferenceOperation: System.String B.X (OperationKind.FieldReference, Type: System.String) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'Identity(this)') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((s ... tity(hello)') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (0) Next (Return) Block[B7] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'Identity(this)') Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_OnParameter() { var src = @" var b = new B() { X = 1 }; var b2 = B.M(b); System.Console.Write(b2.X); public struct B { public int X { get; set; } public static B M(B b) { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M", @" { // Code size 13 (0xd) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.set"" IL_000b: ldloc.0 IL_000c: ret }"); } [Fact] public void WithExprOnStruct_OnThis() { var src = @" record struct C { public int X { get; set; } C(string ignored) { _ = this with { X = 42 }; // 1 this = default; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS0188: The 'this' object cannot be used before all of its fields have been assigned // _ = this with { X = 42 }; // 1 Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this").WithLocation(8, 13) ); } [Fact] public void WithExprOnStruct_OnTStructParameter() { var src = @" var b = new B() { X = 1 }; var b2 = B.M(b); System.Console.Write(b2.X); public interface I { int X { get; set; } } public struct B : I { public int X { get; set; } public static T M<T>(T b) where T : struct, I { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M<T>(T)", @" { // Code size 19 (0x13) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: constrained. ""T"" IL_000c: callvirt ""void I.X.set"" IL_0011: ldloc.0 IL_0012: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var with = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var type = model.GetTypeInfo(with); Assert.Equal("T", type.Type.ToTestDisplayString()); } [Fact] public void WithExprOnStruct_OnRecordStructParameter() { var src = @" var b = new B(1); var b2 = B.M(b); System.Console.Write(b2.X); public record struct B(int X) { public static B M(B b) { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M", @" { // Code size 13 (0xd) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.set"" IL_000b: ldloc.0 IL_000c: ret }"); } [Fact] public void WithExprOnStruct_OnRecordStructParameter_Readonly() { var src = @" var b = new B(1, 2); var b2 = B.M(b); System.Console.Write(b2.X); System.Console.Write(b2.Y); public readonly record struct B(int X, int Y) { public static B M(B b) { return b with { X = 42, Y = 43 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("B.M", @" { // Code size 22 (0x16) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.init"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: call ""void B.Y.init"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple() { var src = @" class C { static void Main() { var b = (1, 2); var b2 = M(b); System.Console.Write(b2.Item1); System.Console.Write(b2.Item2); } static (int, int) M((int, int) b) { return b with { Item1 = 42, Item2 = 43 }; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int>.Item1"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple_WithNames() { var src = @" var b = (1, 2); var b2 = M(b); System.Console.Write(b2.Item1); System.Console.Write(b2.Item2); static (int, int) M((int X, int Y) b) { return b with { X = 42, Y = 43 }; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("Program.<<Main>$>g__M|0_0(System.ValueTuple<int, int>)", @" { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int>.Item1"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple_LongTuple() { var src = @" var b = (1, 2, 3, 4, 5, 6, 7, 8); var b2 = M(b); System.Console.Write(b2.Item7); System.Console.Write(b2.Item8); static (int, int, int, int, int, int, int, int) M((int, int, int, int, int, int, int, int) b) { return b with { Item7 = 42, Item8 = 43 }; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("Program.<<Main>$>g__M|0_0(System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>)", @" { // Code size 27 (0x1b) .maxstack 2 .locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Item7"" IL_000b: ldloca.s V_0 IL_000d: ldflda ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest"" IL_0012: ldc.i4.s 43 IL_0014: stfld ""int System.ValueTuple<int>.Item1"" IL_0019: ldloc.0 IL_001a: ret }"); } [Fact] public void WithExprOnStruct_OnReadonlyField() { var src = @" var b = new B { X = 1 }; // 1 public struct B { public readonly int X; public B M() { return this with { X = 42 }; // 2 } public static B M2(B b) { return b with { X = 42 }; // 3 } public B(int i) { this = default; _ = this with { X = 42 }; // 4 } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,17): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // var b = new B { X = 1 }; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(2, 17), // (9,28): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // return this with { X = 42 }; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(9, 28), // (13,25): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // return b with { X = 42 }; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(13, 25), // (18,25): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = this with { X = 42 }; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(18, 25) ); } [Fact] public void WithExprOnStruct_OnEnum() { var src = @" public enum E { } class C { static E M(E e) { return e with { }; } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void WithExprOnStruct_OnPointer() { var src = @" unsafe class C { static int* M(int* i) { return i with { }; } }"; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (6,16): error CS8858: The receiver type 'int*' is not a valid record type and is not a struct type. // return i with { }; Diagnostic(ErrorCode.ERR_CannotClone, "i").WithArguments("int*").WithLocation(6, 16) ); } [Fact] public void WithExprOnStruct_OnInterface() { var src = @" public interface I { int X { get; set; } } class C { static I M(I i) { return i with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (10,16): error CS8858: The receiver type 'I' is not a valid record type and is not a value type. // return i with { X = 42 }; Diagnostic(ErrorCode.ERR_CannotClone, "i").WithArguments("I").WithLocation(10, 16) ); } [Fact] public void WithExprOnStruct_OnRefStruct() { // Similar to test RefLikeObjInitializers but with `with` expressions var text = @" using System; class Program { static S2 Test1() { S1 outer = default; S1 inner = stackalloc int[1]; // error return new S2() with { Field1 = outer, Field2 = inner }; } static S2 Test2() { S1 outer = default; S1 inner = stackalloc int[1]; S2 result; // error result = new S2() with { Field1 = inner, Field2 = outer }; return result; } static S2 Test3() { S1 outer = default; S1 inner = stackalloc int[1]; return new S2() with { Field1 = outer, Field2 = outer }; } public ref struct S1 { public static implicit operator S1(Span<int> o) => default; } public ref struct S2 { public S1 Field1; public S1 Field2; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (12,48): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // return new S2() with { Field1 = outer, Field2 = inner }; Diagnostic(ErrorCode.ERR_EscapeLocal, "Field2 = inner").WithArguments("inner").WithLocation(12, 48), // (23,34): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // result = new S2() with { Field1 = inner, Field2 = outer }; Diagnostic(ErrorCode.ERR_EscapeLocal, "Field1 = inner").WithArguments("inner").WithLocation(23, 34) ); } [Fact] public void WithExprOnStruct_OnRefStruct_ReceiverMayWrap() { // Similar to test LocalWithNoInitializerEscape but wrapping method is used as receiver for `with` expression var text = @" using System; class Program { static void Main() { S1 sp; Span<int> local = stackalloc int[1]; sp = MayWrap(ref local) with { }; // 1, 2 } static S1 MayWrap(ref Span<int> arg) { return default; } ref struct S1 { public ref int this[int i] => throw null; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (9,26): error CS8352: Cannot use local 'local' in this context because it may expose referenced variables outside of their declaration scope // sp = MayWrap(ref local) with { }; // 1, 2 Diagnostic(ErrorCode.ERR_EscapeLocal, "local").WithArguments("local").WithLocation(9, 26), // (9,14): error CS8347: Cannot use a result of 'Program.MayWrap(ref Span<int>)' in this context because it may expose variables referenced by parameter 'arg' outside of their declaration scope // sp = MayWrap(ref local) with { }; // 1, 2 Diagnostic(ErrorCode.ERR_EscapeCall, "MayWrap(ref local)").WithArguments("Program.MayWrap(ref System.Span<int>)", "arg").WithLocation(9, 14) ); } [Fact] public void WithExprOnStruct_OnRefStruct_ReceiverMayWrap_02() { var text = @" using System; class Program { static void Main() { Span<int> local = stackalloc int[1]; S1 sp = MayWrap(ref local) with { }; } static S1 MayWrap(ref Span<int> arg) { return default; } ref struct S1 { public ref int this[int i] => throw null; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_01() { var src = @" #nullable enable record struct B(int X) { static void M(B b) { string? s = null; _ = b with { X = M(out s) }; s.ToString(); } static int M(out string s) { s = ""a""; return 42; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_02() { var src = @" #nullable enable record struct B(string X) { static void M(B b, string? s) { b.X.ToString(); _ = b with { X = s }; // 1 b.X.ToString(); // 2 } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): warning CS8601: Possible null reference assignment. // _ = b with { X = s }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(8, 26)); } [Fact] public void WithExpr_NullableAnalysis_03() { var src = @" #nullable enable record struct B(string? X) { static void M1(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 1 _ = b with { X = s }; if (flag) { b.X.ToString(); } // 2 } static void M2(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 3 b = b with { X = s }; if (flag) { b.X.ToString(); } } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(7, 21), // (9,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(9, 21), // (14,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(14, 21)); } [Fact, WorkItem(44763, "https://github.com/dotnet/roslyn/issues/44763")] public void WithExpr_NullableAnalysis_05() { var src = @" #nullable enable record struct B(string? X, string? Y) { static void M1(bool flag) { B b = new B(""hello"", null); if (flag) { b.X.ToString(); // shouldn't warn b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); // shouldn't warn b.Y.ToString(); } }"; // records should propagate the nullability of the // constructor arguments to the corresponding properties. // https://github.com/dotnet/roslyn/issues/44763 var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(11, 13), // (15,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(15, 9)); } [Fact] public void WithExpr_NullableAnalysis_06() { var src = @" #nullable enable struct B { public string? X { get; init; } public string? Y { get; init; } static void M1(bool flag) { B b = new B { X = ""hello"", Y = null }; if (flag) { b.X.ToString(); b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); b.Y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(14, 13) ); } [Fact] public void WithExprAssignToRef1() { var src = @" using System; record struct C(int Y) { private readonly int[] _a = new[] { 0 }; public ref int X => ref _a[0]; public static void Main() { var c = new C(0) { X = 5 }; Console.WriteLine(c.X); c = c with { X = 1 }; Console.WriteLine(c.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 5 1").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 59 (0x3b) .maxstack 2 .locals init (C V_0, //c C V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.0 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_1 IL_000a: call ""ref int C.X.get"" IL_000f: ldc.i4.5 IL_0010: stind.i4 IL_0011: ldloc.1 IL_0012: stloc.0 IL_0013: ldloca.s V_0 IL_0015: call ""ref int C.X.get"" IL_001a: ldind.i4 IL_001b: call ""void System.Console.WriteLine(int)"" IL_0020: ldloc.0 IL_0021: stloc.1 IL_0022: ldloca.s V_1 IL_0024: call ""ref int C.X.get"" IL_0029: ldc.i4.1 IL_002a: stind.i4 IL_002b: ldloc.1 IL_002c: stloc.0 IL_002d: ldloca.s V_0 IL_002f: call ""ref int C.X.get"" IL_0034: ldind.i4 IL_0035: call ""void System.Console.WriteLine(int)"" IL_003a: ret }"); } [Fact] public void WithExpressionSameLHS() { var comp = CreateCompilation(@" record struct C(int X) { public static void Main() { var c = new C(0); c = c with { X = 1, X = 2}; } }"); comp.VerifyDiagnostics( // (7,29): error CS1912: Duplicate initialization of member 'X' // c = c with { X = 1, X = 2}; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(7, 29) ); } [Fact] public void WithExpr_AnonymousType_ChangeAllProperties() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { A = Identity(30), B = Identity(40) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) { System.Console.Write($""Identity({t}) ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,17): error CS8773: Feature 'with on anonymous types' is not available in C# 9.0. Please use language version 10.0 or greater. // var b = Identity(a) with { A = Identity(30), B = Identity(40) }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Identity(a) with { A = Identity(30), B = Identity(40) }").WithArguments("with on anonymous types", "10.0").WithLocation(9, 17) ); comp = CreateCompilation(src, parseOptions: TestOptions.Regular10); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "Identity({ A = 10, B = 20 }) Identity(30) Identity(40) { A = 30, B = 40 }"); verifier.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: pop IL_000f: ldc.i4.s 30 IL_0011: call ""int C.Identity<int>(int)"" IL_0016: ldc.i4.s 40 IL_0018: call ""int C.Identity<int>(int)"" IL_001d: stloc.0 IL_001e: ldloc.0 IL_001f: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0024: call ""void System.Console.Write(object)"" IL_0029: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [2] [3] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') 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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(40)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') 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) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... ntity(40) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} } Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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) Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeAllProperties_ReverseOrder() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { B = Identity(40), A = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) { System.Console.Write($""Identity({t}) ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "Identity({ A = 10, B = 20 }) Identity(40) Identity(30) { A = 30, B = 40 }"); verifier.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: pop IL_000f: ldc.i4.s 40 IL_0011: call ""int C.Identity<int>(int)"" IL_0016: stloc.0 IL_0017: ldc.i4.s 30 IL_0019: call ""int C.Identity<int>(int)"" IL_001e: ldloc.0 IL_001f: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0024: call ""void System.Console.Write(object)"" IL_0029: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [2] [3] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') 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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(40)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') 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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} } Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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) Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeNoProperty() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = M2(a) with { }; System.Console.Write(b); }/*</bind>*/ static T M2<T>(T t) { System.Console.Write(""M2 ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "M2 { A = 10, B = 20 }"); verifier.VerifyIL("C.M", @" { // Code size 38 (0x26) .maxstack 2 .locals init (<>f__AnonymousType0<int, int> V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.M2<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0015: ldloc.0 IL_0016: callvirt ""int <>f__AnonymousType0<int, int>.B.get"" IL_001b: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0020: call ""void System.Console.Write(object)"" IL_0025: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.M2<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'M2(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') 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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a) with { }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a) with { }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = M2(a) with { }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = M2(a) with { }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'M2(a) with { }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a) with { }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a) with { }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = a with { B = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); verifier.VerifyIL("C.M", @" { // Code size 34 (0x22) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: ldc.i4.s 30 IL_000b: call ""int C.Identity<int>(int)"" IL_0010: stloc.0 IL_0011: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0016: ldloc.0 IL_0017: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_001c: call ""void System.Console.Write(object)"" IL_0021: ret } "); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var withExpr = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var operation = model.GetOperation(withExpr); VerifyOperationTree(comp, operation, @" IWithOperation (OperationKind.With, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a with { B ... ntity(30) }') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: '{ B = Identity(30) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'B = Identity(30)') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'B') Right: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = a with ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = a with ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a with { B ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithMethodCallForTarget() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { B = 30 }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); verifier.VerifyIL("C.M", @" { // Code size 34 (0x22) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: ldc.i4.s 30 IL_0010: stloc.0 IL_0011: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0016: ldloc.0 IL_0017: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_001c: call ""void System.Console.Write(object)"" IL_0021: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') 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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '30') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... { B = 30 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... { B = 30 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... { B = 30 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithCoalescingExpressionForTarget() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = (Identity(a) ?? Identity2(a)) with { B = 30 }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; static T Identity2<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} {R5} } .locals {R3} { CaptureIds: [4] [5] .locals {R4} { CaptureIds: [2] .locals {R5} { CaptureIds: [3] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') 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) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity(a)') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Leaving: {R5} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B5] Leaving: {R5} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity2(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity2<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity2(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') 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) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '30') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') Next (Regular) Block[B6] Leaving: {R4} } Block[B6] - Block Predecessors: [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = (Identi ... { B = 30 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = (Identi ... { B = 30 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: '(Identity(a ... { B = 30 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') Next (Regular) Block[B7] Leaving: {R3} } Block[B7] - Block Predecessors: [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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) Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithCoalescingExpressionForValue() { var src = @" C.M(""hello"", ""world""); public class C { public static void M(string hello, string world) /*<bind>*/{ var x = new { A = hello, B = string.Empty }; var y = x with { B = Identity(null) ?? Identity2(world) }; System.Console.Write(y); }/*</bind>*/ static string Identity(string t) => t; static string Identity2(string t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "{ A = hello, B = world }"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.String A, System.String B> x] [<anonymous type: System.String A, System.String B> y] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'hello') Value: IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'string.Empty') Value: IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x = new { A ... ing.Empty }') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x = new { A ... ing.Empty }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'new { A = h ... ing.Empty }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'A = hello') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'new { A = h ... ing.Empty }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'hello') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'B = string.Empty') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.B { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'new { A = h ... ing.Empty }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'string.Empty') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [5] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'x') Next (Regular) Block[B3] Entering: {R5} .locals {R5} { CaptureIds: [4] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(null)') Value: IInvocationOperation (System.String C.Identity(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(null)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') 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) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity(null)') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity(null)') Leaving: {R5} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(null)') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity(null)') Next (Regular) Block[B6] Leaving: {R5} } Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity2(world)') Value: IInvocationOperation (System.String C.Identity2(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity2(world)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'world') IParameterReferenceOperation: world (OperationKind.ParameterReference, Type: System.String) (Syntax: 'world') 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) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Value: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') Next (Regular) Block[B7] Leaving: {R4} } Block[B7] - Block Predecessors: [B6] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'y = x with ... y2(world) }') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'y = x with ... y2(world) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'x with { B ... y2(world) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.B { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') Next (Regular) Block[B8] Leaving: {R3} } Block[B8] - Block Predecessors: [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(y);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'y') 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) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ErrorMember() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { Error = Identity(20) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS0117: '<anonymous type: int A>' does not contain a definition for 'Error' // var b = a with { Error = Identity(20) }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("<anonymous type: int A>", "Error").WithLocation(7, 26) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(20)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '20') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') 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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { Er ... ntity(20) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} {R1} } } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ToString() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { ToString = Identity(20) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS1913: Member 'ToString' cannot be initialized. It is not a field or property. // var b = a with { ToString = Identity(20) }; Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "ToString").WithArguments("ToString").WithLocation(7, 26) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(20)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '20') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') 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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { To ... ntity(20) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} {R1} } } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_NestedInitializer() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var nested = new { A = 10 }; var a = new { Nested = nested }; var b = a with { Nested = { A = 20 } }; System.Console.Write(b); }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (10,35): error CS1525: Invalid expression term '{' // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "{").WithArguments("{").WithLocation(10, 35), // (10,35): error CS1513: } expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(10, 35), // (10,35): error CS1002: ; expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(10, 35), // (10,37): error CS0103: The name 'A' does not exist in the current context // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_NameNotInContext, "A").WithArguments("A").WithLocation(10, 37), // (10,44): error CS1002: ; expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(10, 44), // (10,47): error CS1597: Semicolon after method or accessor block is not valid // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(10, 47), // (11,29): error CS1519: Invalid token '(' in class, record, struct, or interface member declaration // System.Console.Write(b); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "(").WithArguments("(").WithLocation(11, 29), // (11,31): error CS8124: Tuple must contain at least two elements. // System.Console.Write(b); Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(11, 31), // (11,32): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // System.Console.Write(b); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(11, 32), // (13,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(13, 1) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> nested] [<anonymous type: <anonymous type: System.Int32 A> Nested> a] [<anonymous type: <anonymous type: System.Int32 A> Nested> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested = new { A = 10 }') Left: ILocalReferenceOperation: nested (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (2) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'nested') Value: ILocalReferenceOperation: nested (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'nested') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a = new { N ... = nested }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a = new { N ... = nested }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>) (Syntax: 'new { Nested = nested }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>) (Syntax: 'Nested = nested') Left: IPropertyReferenceOperation: <anonymous type: System.Int32 A> <anonymous type: <anonymous type: System.Int32 A> Nested>.Nested { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'Nested') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'new { Nested = nested }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested') Next (Regular) Block[B3] Leaving: {R3} Entering: {R4} } .locals {R4} { CaptureIds: [2] Block[B3] - Block Predecessors: [B2] Statements (3) ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>) (Syntax: 'a') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '') Value: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'b = a with { Nested = ') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'b = a with { Nested = ') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid) (Syntax: 'a with { Nested = ') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Left: IPropertyReferenceOperation: <anonymous type: System.Int32 A> <anonymous type: <anonymous type: System.Int32 A> Nested>.Nested { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R4} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'A = 20 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'A = 20') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'A') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_NonAssignmentExpression() { var src = @" public class C { public static void M(int i, int j) /*<bind>*/{ var a = new { A = 10 }; var b = a with { i, j++, M2(), A = 20 }; }/*</bind>*/ static int M2() => 0; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "i").WithLocation(7, 26), // (7,29): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "j++").WithLocation(7, 29), // (7,34): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "M2()").WithLocation(7, 34) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (6) ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'j++') Children(1): IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32, IsInvalid) (Syntax: 'j++') Target: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2()') Children(1): IInvocationOperation (System.Int32 C.M2()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ), A = 20 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ), A = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { i, ... ), A = 20 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R3} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_IndexerAccess() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { [0] = 20 }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (7,26): error CS1513: } expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_RbraceExpected, "[").WithLocation(7, 26), // (7,26): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "[").WithLocation(7, 26), // (7,26): error CS7014: Attributes are not valid in this context. // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[").WithLocation(7, 26), // (7,27): error CS1001: Identifier expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_IdentifierExpected, "0").WithLocation(7, 27), // (7,27): error CS1003: Syntax error, ']' expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SyntaxError, "0").WithArguments("]", "").WithLocation(7, 27), // (7,28): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "]").WithLocation(7, 28), // (7,28): error CS1513: } expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_RbraceExpected, "]").WithLocation(7, 28), // (7,30): error CS1525: Invalid expression term '=' // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(7, 30), // (7,35): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 35), // (7,36): error CS1597: Semicolon after method or accessor block is not valid // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(7, 36), // (9,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(9, 1) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (2) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { ') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with { ') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with { ') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { ') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { ') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '[0') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '= 20 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '= 20') Left: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_CannotSet() { var src = @" public class C { public static void M() { var a = new { A = 10 }; a.A = 20; var b = new { B = a }; b.B.A = 30; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,9): error CS0200: Property or indexer '<anonymous type: int A>.A' cannot be assigned to -- it is read only // a.A = 20; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "a.A").WithArguments("<anonymous type: int A>.A").WithLocation(7, 9), // (10,9): error CS0200: Property or indexer '<anonymous type: int A>.A' cannot be assigned to -- it is read only // b.B.A = 30; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.B.A").WithArguments("<anonymous type: int A>.A").WithLocation(10, 9) ); } [Fact] public void WithExpr_AnonymousType_DuplicateMemberInDeclaration() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10, A = 20 }; var b = Identity(a) with { A = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var expectedDiagnostics = new[] { // (6,31): error CS0833: An anonymous type cannot have multiple properties with the same name // var a = new { A = 10, A = 20 }; Diagnostic(ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, "A = 20").WithLocation(6, 31) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 $1> a] [<anonymous type: System.Int32 A, System.Int32 $1> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20, IsInvalid) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'a = new { A ... 0, A = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'a = new { A ... 0, A = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid) (Syntax: 'new { A = 10, A = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { A = 10, A = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20, IsInvalid) (Syntax: 'A = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { A = 10, A = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsInvalid, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 $1> C.Identity<<anonymous type: System.Int32 A, System.Int32 $1>>(<anonymous type: System.Int32 A, System.Int32 $1> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'a') 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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'Identity(a) ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'b') 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) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_DuplicateInitialization() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = Identity(a) with { A = Identity(30), A = Identity(40) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var expectedDiagnostics = new[] { // (7,54): error CS1912: Duplicate initialization of member 'A' // var b = Identity(a) with { A = Identity(30), A = Identity(40) }; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "A").WithArguments("A").WithLocation(7, 54) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A> C.Identity<<anonymous type: System.Int32 A>>(<anonymous type: System.Int32 A> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') 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) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') 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) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'Identity(a) ... ntity(40) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact, WorkItem(53849, "https://github.com/dotnet/roslyn/issues/53849")] public void WithExpr_AnonymousType_ValueIsLoweredToo() { var src = @" var x = new { Property = 42 }; var adjusted = x with { Property = x.Property + 2 }; System.Console.WriteLine(adjusted); "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(comp, expectedOutput: "{ Property = 44 }"); verifier.VerifyDiagnostics(); } [Fact, WorkItem(53849, "https://github.com/dotnet/roslyn/issues/53849")] public void WithExpr_AnonymousType_ValueIsLoweredToo_NestedWith() { var src = @" var x = new { Property = 42 }; var container = new { Item = x }; var adjusted = container with { Item = x with { Property = x.Property + 2 } }; System.Console.WriteLine(adjusted); "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(comp, expectedOutput: "{ Item = { Property = 44 } }"); verifier.VerifyDiagnostics(); } [Fact] public void AttributesOnPrimaryConstructorParameters_01() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public readonly record struct Test( [field: A] [property: B] [param: C] [D] int P1) { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.RegularPreview, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => a.AttributeClass!.Name is "A" or "B" or "C" or "D")); } } [Fact] public void FieldAsPositionalMember() { var source = @" var a = new A(42); System.Console.Write(a.X); System.Console.Write("" - ""); a.Deconstruct(out int x); System.Console.Write(x); record struct A(int X) { public int X = X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(8, 8), // (8,17): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(8, 17) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42"); verifier.VerifyIL("A.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_Readonly() { var source = @" readonly record struct A(int X) { public int X = X; // 1 } readonly record struct B(int X) { public readonly int X = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS8340: Instance fields of readonly structs must be readonly. // public int X = X; // 1 Diagnostic(ErrorCode.ERR_FieldsInRoStruct, "X").WithLocation(4, 16) ); } [Fact] public void FieldAsPositionalMember_Fixed() { var src = @" unsafe record struct C(int[] P) { public fixed int P[2]; public int[] X = P; }"; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (2,30): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int[]' to match positional parameter 'P'. // unsafe record struct C(int[] P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int[]", "P").WithLocation(2, 30), // (4,22): error CS8908: The type 'int*' may not be used for a field of a record. // public fixed int P[2]; Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P").WithArguments("int*").WithLocation(4, 22) ); } [Fact] public void FieldAsPositionalMember_WrongType() { var source = @" record struct A(int X) { public string X = null; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,21): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record struct A(int X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 21) ); } [Fact] public void FieldAsPositionalMember_DuplicateFields() { var source = @" record struct A(int X) { public int X = 0; public int X = 0; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,16): error CS0102: The type 'A' already contains a definition for 'X' // public int X = 0; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("A", "X").WithLocation(5, 16) ); } [Fact] public void SyntaxFactory_TypeDeclaration() { var expected = @"record struct Point { }"; AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, SyntaxFactory.TypeDeclaration(SyntaxKind.RecordStructDeclaration, "Point").NormalizeWhitespace().ToString()); } [Fact] public void InterfaceWithParameters() { var src = @" public interface I { } record struct R(int X) : I() { } record struct R2(int X) : I(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,27): error CS8861: Unexpected argument list. // record struct R(int X) : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 27), // (10,28): error CS8861: Unexpected argument list. // record struct R2(int X) : I(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 28) ); } [Fact] public void InterfaceWithParameters_NoPrimaryConstructor() { var src = @" public interface I { } record struct R : I() { } record struct R2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,20): error CS8861: Unexpected argument list. // record struct R : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 20), // (10,21): error CS8861: Unexpected argument list. // record struct R2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 21) ); } [Fact] public void InterfaceWithParameters_Struct() { var src = @" public interface I { } struct C : I() { } struct C2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,13): error CS8861: Unexpected argument list. // struct C : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 13), // (10,14): error CS8861: Unexpected argument list. // struct C2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 14) ); } [Fact] public void BaseArguments_Speculation() { var src = @" record struct R1(int X) : Error1(0, 1) { } record struct R2(int X) : Error2() { } record struct R3(int X) : Error3 { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,27): error CS0246: The type or namespace name 'Error1' could not be found (are you missing a using directive or an assembly reference?) // record struct R1(int X) : Error1(0, 1) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error1").WithArguments("Error1").WithLocation(2, 27), // (2,33): error CS8861: Unexpected argument list. // record struct R1(int X) : Error1(0, 1) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0, 1)").WithLocation(2, 33), // (5,27): error CS0246: The type or namespace name 'Error2' could not be found (are you missing a using directive or an assembly reference?) // record struct R2(int X) : Error2() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error2").WithArguments("Error2").WithLocation(5, 27), // (5,33): error CS8861: Unexpected argument list. // record struct R2(int X) : Error2() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(5, 33), // (8,27): error CS0246: The type or namespace name 'Error3' could not be found (are you missing a using directive or an assembly reference?) // record struct R3(int X) : Error3 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error3").WithArguments("Error3").WithLocation(8, 27) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().First(); Assert.Equal("Error1(0, 1)", baseWithargs.ToString()); var speculativeBase = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1))); Assert.Equal("Error1(0)", speculativeBase.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBase, out _)); var baseWithoutargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Skip(1).First(); Assert.Equal("Error2()", baseWithoutargs.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithoutargs.ArgumentList.OpenParenToken.SpanStart, speculativeBase, out _)); var baseWithoutParens = tree.GetRoot().DescendantNodes().OfType<SimpleBaseTypeSyntax>().Single(); Assert.Equal("Error3", baseWithoutParens.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithoutParens.SpanStart + 2, speculativeBase, out _)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using 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.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { [CompilerTrait(CompilerFeature.RecordStructs)] public class RecordStructTests : CompilingTestBase { private static CSharpCompilation CreateCompilation(CSharpTestSource source) => CSharpTestBase.CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); private CompilationVerifier CompileAndVerify( CSharpTestSource src, string? expectedOutput = null, IEnumerable<MetadataReference>? references = null) => base.CompileAndVerify( new[] { src, IsExternalInitTypeDefinition }, expectedOutput: expectedOutput, parseOptions: TestOptions.RegularPreview, references: references, // init-only is unverifiable verify: Verification.Skipped); [Fact] public void StructRecord1() { var src = @" record struct Point(int X, int Y);"; var verifier = CompileAndVerify(src).VerifyDiagnostics(); verifier.VerifyIL("Point.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""Point"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""Point"" IL_000f: call ""readonly bool Point.Equals(Point)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("Point.Equals(Point)", @" { // Code size 49 (0x31) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int Point.<X>k__BackingField"" IL_000b: ldarg.1 IL_000c: ldfld ""int Point.<X>k__BackingField"" IL_0011: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0016: brfalse.s IL_002f IL_0018: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001d: ldarg.0 IL_001e: ldfld ""int Point.<Y>k__BackingField"" IL_0023: ldarg.1 IL_0024: ldfld ""int Point.<Y>k__BackingField"" IL_0029: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002e: ret IL_002f: ldc.i4.0 IL_0030: ret }"); } [Fact] public void StructRecord2() { var src = @" using System; record struct S(int X, int Y) { public static void Main() { var s1 = new S(0, 1); var s2 = new S(0, 1); Console.WriteLine(s1.X); Console.WriteLine(s1.Y); Console.WriteLine(s1.Equals(s2)); Console.WriteLine(s1.Equals(new S(1, 0))); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 1 True False").VerifyDiagnostics(); } [Fact] public void StructRecord3() { var src = @" using System; record struct S(int X, int Y) { public bool Equals(S s) => false; public static void Main() { var s1 = new S(0, 1); Console.WriteLine(s1.Equals(s1)); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"False") .VerifyDiagnostics( // (5,17): warning CS8851: 'S' defines 'Equals' but not 'GetHashCode' // public bool Equals(S s) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("S").WithLocation(5, 17)); verifier.VerifyIL("S.Main", @" { // Code size 23 (0x17) .maxstack 3 .locals init (S V_0) //s1 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""S..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldloc.0 IL_000c: call ""bool S.Equals(S)"" IL_0011: call ""void System.Console.WriteLine(bool)"" IL_0016: ret }"); } [Fact] public void StructRecord5() { var src = @" using System; record struct S(int X, int Y) { public bool Equals(S s) { Console.Write(""s""); return true; } public static void Main() { var s1 = new S(0, 1); s1.Equals((object)s1); s1.Equals(s1); } }"; CompileAndVerify(src, expectedOutput: @"ss") .VerifyDiagnostics( // (5,17): warning CS8851: 'S' defines 'Equals' but not 'GetHashCode' // public bool Equals(S s) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("S").WithLocation(5, 17)); } [Fact] public void StructRecordDefaultCtor() { const string src = @" public record struct S(int X);"; const string src2 = @" class C { public S M() => new S(); }"; var comp = CreateCompilation(src + src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src); var comp2 = CreateCompilation(src2, references: new[] { comp.EmitToImageReference() }); comp2.VerifyDiagnostics(); } [Fact] public void Equality_01() { var source = @"using static System.Console; record struct S; class Program { static void Main() { var x = new S(); var y = new S(); WriteLine(x.Equals(y)); WriteLine(((object)x).Equals(y)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"True True").VerifyDiagnostics(); verifier.VerifyIL("S.Equals(S)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("S.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""S"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""S"" IL_000f: call ""readonly bool S.Equals(S)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); } [Fact] public void RecordStructLanguageVersion() { var src1 = @" struct Point(int x, int y); "; var src2 = @" record struct Point { } "; var src3 = @" record struct Point(int x, int y); "; var comp = CreateCompilation(new[] { src1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,13): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS8803: Top-level statements must precede namespace and type declarations. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS8805: Program using top-level statements must be an executable. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 13), // (2,14): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 14), // (2,14): error CS0165: Use of unassigned local variable 'x' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 14), // (2,21): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 21), // (2,21): error CS0165: Use of unassigned local variable 'y' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 21) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,13): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 13), // (2,13): error CS8803: Top-level statements must precede namespace and type declarations. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS8805: Program using top-level statements must be an executable. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 13), // (2,13): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 13), // (2,14): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 14), // (2,14): error CS0165: Use of unassigned local variable 'x' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 14), // (2,21): error CS8185: A declaration is not allowed in this context. // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 21), // (2,21): error CS0165: Use of unassigned local variable 'y' // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 21) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [Fact] public void RecordStructLanguageVersion_Nested() { var src1 = @" class C { struct Point(int x, int y); } "; var src2 = @" class D { record struct Point { } } "; var src3 = @" struct E { record struct Point(int x, int y); } "; var src4 = @" namespace NS { record struct Point { } } "; var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,17): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 17), // (4,17): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 17), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31) ); comp = CreateCompilation(new[] { src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(new[] { src3, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(src4, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,12): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct Point { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(4, 12) ); comp = CreateCompilation(src1); comp.VerifyDiagnostics( // (4,17): error CS1514: { expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 17), // (4,17): error CS1513: } expected // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 17), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31), // (4,31): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // struct Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 31) ); comp = CreateCompilation(src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src3); comp.VerifyDiagnostics(); comp = CreateCompilation(src4); comp.VerifyDiagnostics(); } [Fact] public void TypeDeclaration_IsStruct() { var src = @" record struct Point(int x, int y); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validateModule, sourceSymbolValidator: validateModule); Assert.True(SyntaxFacts.IsTypeDeclaration(SyntaxKind.RecordStructDeclaration)); static void validateModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var point = module.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsValueType); Assert.False(point.IsReferenceType); Assert.False(point.IsRecord); Assert.Equal(TypeKind.Struct, point.TypeKind); Assert.Equal(SpecialType.System_ValueType, point.BaseTypeNoUseSiteDiagnostics.SpecialType); Assert.Equal("Point", point.ToTestDisplayString()); if (isSourceSymbol) { Assert.True(point is SourceNamedTypeSymbol); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); Assert.Equal("record struct Point", point.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } else { Assert.True(point is PENamedTypeSymbol); Assert.False(point.IsRecordStruct); Assert.False(point.GetPublicSymbol().IsRecord); Assert.Equal("struct Point", point.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } } } [Fact] public void TypeDeclaration_IsStruct_InConstraints() { var src = @" record struct Point(int x, int y); class C<T> where T : struct { void M(C<Point> c) { } } class C2<T> where T : new() { void M(C2<Point> c) { } } class C3<T> where T : class { void M(C3<Point> c) { } // 1 } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (16,22): error CS0452: The type 'Point' must be a reference type in order to use it as parameter 'T' in the generic type or method 'C3<T>' // void M(C3<Point> c) { } // 1 Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "c").WithArguments("C3<T>", "T", "Point").WithLocation(16, 22) ); } [Fact] public void TypeDeclaration_IsStruct_Unmanaged() { var src = @" record struct Point(int x, int y); record struct Point2(string x, string y); class C<T> where T : unmanaged { void M(C<Point> c) { } void M2(C<Point2> c) { } // 1 } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,23): error CS8377: The type 'Point2' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C<T>' // void M2(C<Point2> c) { } // 1 Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "c").WithArguments("C<T>", "T", "Point2").WithLocation(8, 23) ); } [Fact] public void IsRecord_Generic() { var src = @" record struct Point<T>(T x, T y); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validateModule, sourceSymbolValidator: validateModule); static void validateModule(ModuleSymbol module) { var isSourceSymbol = module is SourceModuleSymbol; var point = module.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsValueType); Assert.False(point.IsReferenceType); Assert.False(point.IsRecord); Assert.Equal(TypeKind.Struct, point.TypeKind); Assert.Equal(SpecialType.System_ValueType, point.BaseTypeNoUseSiteDiagnostics.SpecialType); Assert.True(SyntaxFacts.IsTypeDeclaration(SyntaxKind.RecordStructDeclaration)); if (isSourceSymbol) { Assert.True(point is SourceNamedTypeSymbol); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); } else { Assert.True(point is PENamedTypeSymbol); Assert.False(point.IsRecordStruct); Assert.False(point.GetPublicSymbol().IsRecord); } } } [Fact] public void IsRecord_Retargeting() { var src = @" public record struct Point(int x, int y); "; var comp = CreateCompilation(src, targetFramework: TargetFramework.Mscorlib40); var comp2 = CreateCompilation("", targetFramework: TargetFramework.Mscorlib46, references: new[] { comp.ToMetadataReference() }); var point = comp2.GlobalNamespace.GetTypeMember("Point"); Assert.Equal("Point", point.ToTestDisplayString()); Assert.IsType<RetargetingNamedTypeSymbol>(point); Assert.True(point.IsRecordStruct); Assert.True(point.GetPublicSymbol().IsRecord); } [Fact] public void IsRecord_AnonymousType() { var src = @" class C { void M() { var x = new { X = 1 }; } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var creation = tree.GetRoot().DescendantNodes().OfType<AnonymousObjectCreationExpressionSyntax>().Single(); var type = model.GetTypeInfo(creation).Type!; Assert.Equal("<anonymous type: System.Int32 X>", type.ToTestDisplayString()); Assert.IsType<AnonymousTypeManager.AnonymousTypePublicSymbol>(((Symbols.PublicModel.NonErrorNamedTypeSymbol)type).UnderlyingNamedTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_ErrorType() { var src = @" class C { Error M() => throw null; } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.ReturnType; Assert.Equal("Error", type.ToTestDisplayString()); Assert.IsType<ExtendedErrorTypeSymbol>(((Symbols.PublicModel.ErrorTypeSymbol)type).UnderlyingNamedTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_Pointer() { var src = @" class C { int* M() => throw null; } "; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.ReturnType; Assert.Equal("System.Int32*", type.ToTestDisplayString()); Assert.IsType<PointerTypeSymbol>(((Symbols.PublicModel.PointerTypeSymbol)type).UnderlyingTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void IsRecord_Dynamic() { var src = @" class C { void M(dynamic d) { } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); var type = model.GetDeclaredSymbol(method)!.GetParameterType(0); Assert.Equal("dynamic", type.ToTestDisplayString()); Assert.IsType<DynamicTypeSymbol>(((Symbols.PublicModel.DynamicTypeSymbol)type).UnderlyingTypeSymbol); Assert.False(type.IsRecord); } [Fact] public void TypeDeclaration_MayNotHaveBaseType() { var src = @" record struct Point(int x, int y) : object; record struct Point2(int x, int y) : System.ValueType; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,37): error CS0527: Type 'object' in interface list is not an interface // record struct Point(int x, int y) : object; Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "object").WithArguments("object").WithLocation(2, 37), // (3,38): error CS0527: Type 'ValueType' in interface list is not an interface // record struct Point2(int x, int y) : System.ValueType; Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "System.ValueType").WithArguments("System.ValueType").WithLocation(3, 38) ); } [Fact] public void TypeDeclaration_MayNotHaveTypeConstraintsWithoutTypeParameters() { var src = @" record struct Point(int x, int y) where T : struct; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,35): error CS0080: Constraints are not allowed on non-generic declarations // record struct Point(int x, int y) where T : struct; Diagnostic(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, "where").WithLocation(2, 35) ); } [Fact] public void TypeDeclaration_AllowedModifiers() { var src = @" readonly partial record struct S1; public record struct S2; internal record struct S3; public class Base { public int S6; } public class C : Base { private protected record struct S4; protected internal record struct S5; new record struct S6; } unsafe record struct S7; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics(); Assert.Equal(Accessibility.Internal, comp.GlobalNamespace.GetTypeMember("S1").DeclaredAccessibility); Assert.Equal(Accessibility.Public, comp.GlobalNamespace.GetTypeMember("S2").DeclaredAccessibility); Assert.Equal(Accessibility.Internal, comp.GlobalNamespace.GetTypeMember("S3").DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedAndInternal, comp.GlobalNamespace.GetTypeMember("C").GetTypeMember("S4").DeclaredAccessibility); Assert.Equal(Accessibility.ProtectedOrInternal, comp.GlobalNamespace.GetTypeMember("C").GetTypeMember("S5").DeclaredAccessibility); } [Fact] public void TypeDeclaration_DisallowedModifiers() { var src = @" abstract record struct S1; volatile record struct S2; extern record struct S3; virtual record struct S4; override record struct S5; async record struct S6; ref record struct S7; unsafe record struct S8; static record struct S9; sealed record struct S10; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS0106: The modifier 'abstract' is not valid for this item // abstract record struct S1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S1").WithArguments("abstract").WithLocation(2, 24), // (3,24): error CS0106: The modifier 'volatile' is not valid for this item // volatile record struct S2; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S2").WithArguments("volatile").WithLocation(3, 24), // (4,22): error CS0106: The modifier 'extern' is not valid for this item // extern record struct S3; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S3").WithArguments("extern").WithLocation(4, 22), // (5,23): error CS0106: The modifier 'virtual' is not valid for this item // virtual record struct S4; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S4").WithArguments("virtual").WithLocation(5, 23), // (6,24): error CS0106: The modifier 'override' is not valid for this item // override record struct S5; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S5").WithArguments("override").WithLocation(6, 24), // (7,21): error CS0106: The modifier 'async' is not valid for this item // async record struct S6; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S6").WithArguments("async").WithLocation(7, 21), // (8,19): error CS0106: The modifier 'ref' is not valid for this item // ref record struct S7; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S7").WithArguments("ref").WithLocation(8, 19), // (9,22): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe record struct S8; Diagnostic(ErrorCode.ERR_IllegalUnsafe, "S8").WithLocation(9, 22), // (10,22): error CS0106: The modifier 'static' is not valid for this item // static record struct S9; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S9").WithArguments("static").WithLocation(10, 22), // (11,22): error CS0106: The modifier 'sealed' is not valid for this item // sealed record struct S10; Diagnostic(ErrorCode.ERR_BadMemberFlag, "S10").WithArguments("sealed").WithLocation(11, 22) ); } [Fact] public void TypeDeclaration_DuplicatesModifiers() { var src = @" public public record struct S2; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,8): error CS1004: Duplicate 'public' modifier // public public record struct S2; Diagnostic(ErrorCode.ERR_DuplicateModifier, "public").WithArguments("public").WithLocation(2, 8) ); } [Fact] public void TypeDeclaration_BeforeTopLevelStatement() { var src = @" record struct S; System.Console.WriteLine(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine();").WithLocation(3, 1) ); } [Fact] public void TypeDeclaration_WithTypeParameters() { var src = @" S<string> local = default; local.ToString(); record struct S<T>; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); Assert.Equal(new[] { "T" }, comp.GlobalNamespace.GetTypeMember("S").TypeParameters.ToTestDisplayStrings()); } [Fact] public void TypeDeclaration_AllowedModifiersForMembers() { var src = @" record struct S { protected int Property { get; set; } // 1 internal protected string field; // 2, 3 abstract void M(); // 4 virtual void M2() { } // 5 }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0666: 'S.Property': new protected member declared in struct // protected int Property { get; set; } // 1 Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Property").WithArguments("S.Property").WithLocation(4, 19), // (5,31): error CS0666: 'S.field': new protected member declared in struct // internal protected string field; // 2, 3 Diagnostic(ErrorCode.ERR_ProtectedInStruct, "field").WithArguments("S.field").WithLocation(5, 31), // (5,31): warning CS0649: Field 'S.field' is never assigned to, and will always have its default value null // internal protected string field; // 2, 3 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("S.field", "null").WithLocation(5, 31), // (6,19): error CS0621: 'S.M()': virtual or abstract members cannot be private // abstract void M(); // 4 Diagnostic(ErrorCode.ERR_VirtualPrivate, "M").WithArguments("S.M()").WithLocation(6, 19), // (7,18): error CS0621: 'S.M2()': virtual or abstract members cannot be private // virtual void M2() { } // 5 Diagnostic(ErrorCode.ERR_VirtualPrivate, "M2").WithArguments("S.M2()").WithLocation(7, 18) ); } [Fact] public void TypeDeclaration_ImplementInterface() { var src = @" I i = (I)default(S); System.Console.Write(i.M(""four"")); I i2 = (I)default(S2); System.Console.Write(i2.M(""four"")); interface I { int M(string s); } public record struct S : I { public int M(string s) => s.Length; } public record struct S2 : I { int I.M(string s) => s.Length + 1; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "45"); AssertEx.Equal(new[] { "System.Int32 S.M(System.String s)", "readonly System.String S.ToString()", "readonly System.Boolean S.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean S.op_Inequality(S left, S right)", "System.Boolean S.op_Equality(S left, S right)", "readonly System.Int32 S.GetHashCode()", "readonly System.Boolean S.Equals(System.Object obj)", "readonly System.Boolean S.Equals(S other)", "S..ctor()" }, comp.GetMember<NamedTypeSymbol>("S").GetMembers().ToTestDisplayStrings()); } [Fact] public void TypeDeclaration_SatisfiesStructConstraint() { var src = @" S s = default; System.Console.Write(M(s)); static int M<T>(T t) where T : struct, I => t.Property; public interface I { int Property { get; } } public record struct S : I { public int Property => 42; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void TypeDeclaration_AccessingThis() { var src = @" S s = new S(); System.Console.Write(s.M()); public record struct S { public int Property => 42; public int M() => this.Property; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("S.M", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int S.Property.get"" IL_0006: ret } "); } [Fact] public void TypeDeclaration_NoBaseInitializer() { var src = @" public record struct S { public S(int i) : base() { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,12): error CS0522: 'S': structs cannot call base class constructors // public S(int i) : base() { } Diagnostic(ErrorCode.ERR_StructWithBaseConstructorCall, "S").WithArguments("S").WithLocation(4, 12) ); } [Fact] public void TypeDeclaration_ParameterlessConstructor_01() { var src = @"record struct S0(); record struct S1; record struct S2 { public S2() { } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S0(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(1, 8), // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 8), // (3,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(3, 8), // (5,12): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // public S2() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S2").WithArguments("parameterless struct constructors", "10.0").WithLocation(5, 12)); var verifier = CompileAndVerify(src); verifier.VerifyIL("S0..ctor()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); verifier.VerifyMissing("S1..ctor()"); verifier.VerifyIL("S2..ctor()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [Fact] public void TypeDeclaration_ParameterlessConstructor_02() { var src = @"record struct S1 { S1() { } } record struct S2 { internal S2() { } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(1, 8), // (3,5): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // S1() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S1").WithArguments("parameterless struct constructors", "10.0").WithLocation(3, 5), // (3,5): error CS8938: The parameterless struct constructor must be 'public'. // S1() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S1").WithLocation(3, 5), // (5,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct S2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(5, 8), // (7,14): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // internal S2() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S2").WithArguments("parameterless struct constructors", "10.0").WithLocation(7, 14), // (7,14): error CS8938: The parameterless struct constructor must be 'public'. // internal S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(7, 14)); comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,5): error CS8918: The parameterless struct constructor must be 'public'. // S1() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S1").WithLocation(3, 5), // (7,14): error CS8918: The parameterless struct constructor must be 'public'. // internal S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(7, 14)); } [Fact] public void TypeDeclaration_ParameterlessConstructor_OtherConstructors() { var src = @" record struct S1 { public S1() { } S1(object o) { } // ok because no record parameter list } record struct S2 { S2(object o) { } } record struct S3() { S3(object o) { } // 1 } record struct S4() { S4(object o) : this() { } } record struct S5(object o) { public S5() { } // 2 } record struct S6(object o) { public S6() : this(null) { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,5): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // S3(object o) { } // 1 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "S3").WithLocation(13, 5), // (21,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public S5() { } // 2 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "S5").WithLocation(21, 12) ); } [Fact] public void TypeDeclaration_ParameterlessConstructor_Initializers() { var src = @" var s1 = new S1(); var s2 = new S2(null); var s2b = new S2(); var s3 = new S3(); var s4 = new S4(new object()); var s5 = new S5(); var s6 = new S6(""s6.other""); System.Console.Write((s1.field, s2.field, s2b.field is null, s3.field, s4.field, s5.field, s6.field, s6.other)); record struct S1 { public string field = ""s1""; public S1() { } } record struct S2 { public string field = ""s2""; public S2(object o) { } } record struct S3() { public string field = ""s3""; } record struct S4 { public string field = ""s4""; public S4(object o) : this() { } } record struct S5() { public string field = ""s5""; public S5(object o) : this() { } } record struct S6(string other) { public string field = ""s6.field""; public S6() : this(""ignored"") { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(s1, s2, True, s3, s4, s5, s6.field, s6.other)"); } [Fact] public void TypeDeclaration_InstanceInitializers() { var src = @" public record struct S { public int field = 42; public int Property { get; set; } = 43; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,15): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // public record struct S Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(2, 15), // (4,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int field = 42; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "field").WithArguments("struct field initializers", "10.0").WithLocation(4, 16), // (5,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int Property { get; set; } = 43; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Property").WithArguments("struct field initializers", "10.0").WithLocation(5, 16)); comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void TypeDeclaration_NoDestructor() { var src = @" public record struct S { ~S() { } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,6): error CS0575: Only class types can contain destructors // ~S() { } Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "S").WithArguments("S.~S()").WithLocation(4, 6) ); } [Fact] public void TypeDeclaration_DifferentPartials() { var src = @" partial record struct S1; partial struct S1 { } partial struct S2 { } partial record struct S2; partial record struct S3; partial record S3 { } partial record struct S4; partial record class S4 { } partial record struct S5; partial class S5 { } partial record struct S6; partial interface S6 { } partial record class C1; partial struct C1 { } partial record class C2; partial record struct C2 { } partial record class C3 { } partial record C3; partial record class C4; partial class C4 { } partial record class C5; partial interface C5 { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,16): error CS0261: Partial declarations of 'S1' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial struct S1 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S1").WithArguments("S1").WithLocation(3, 16), // (6,23): error CS0261: Partial declarations of 'S2' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record struct S2; Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S2").WithArguments("S2").WithLocation(6, 23), // (9,16): error CS0261: Partial declarations of 'S3' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record S3 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S3").WithArguments("S3").WithLocation(9, 16), // (12,22): error CS0261: Partial declarations of 'S4' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record class S4 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S4").WithArguments("S4").WithLocation(12, 22), // (15,15): error CS0261: Partial declarations of 'S5' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class S5 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S5").WithArguments("S5").WithLocation(15, 15), // (18,19): error CS0261: Partial declarations of 'S6' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial interface S6 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "S6").WithArguments("S6").WithLocation(18, 19), // (21,16): error CS0261: Partial declarations of 'C1' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial struct C1 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C1").WithArguments("C1").WithLocation(21, 16), // (24,23): error CS0261: Partial declarations of 'C2' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial record struct C2 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C2").WithArguments("C2").WithLocation(24, 23), // (30,15): error CS0261: Partial declarations of 'C4' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class C4 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C4").WithArguments("C4").WithLocation(30, 15), // (33,19): error CS0261: Partial declarations of 'C5' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial interface C5 { } Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C5").WithArguments("C5").WithLocation(33, 19) ); } [Fact] public void PartialRecord_OnlyOnePartialHasParameterList() { var src = @" partial record struct S(int i); partial record struct S(int i); partial record struct S2(int i); partial record struct S2(); partial record struct S3(); partial record struct S3(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,24): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S(int i); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int i)").WithLocation(3, 24), // (6,25): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S2(); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "()").WithLocation(6, 25), // (9,25): error CS8863: Only a single record partial declaration may have a parameter list // partial record struct S3(); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "()").WithLocation(9, 25) ); } [Fact] public void PartialRecord_ParametersInScopeOfBothParts() { var src = @" var c = new C(2); System.Console.Write((c.P1, c.P2)); public partial record struct C(int X) { public int P1 { get; set; } = X; } public partial record struct C { public int P2 { get; set; } = X; } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */) .VerifyDiagnostics( // (5,30): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'C'. To specify an ordering, all instance fields must be in the same declaration. // public partial record struct C(int X) Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "C").WithArguments("C").WithLocation(5, 30) ); } [Fact] public void PartialRecord_DuplicateMemberNames() { var src = @" public partial record struct C(int X) { public void M(int i) { } } public partial record struct C { public void M(string s) { } } "; var comp = CreateCompilation(src); var expectedMemberNames = new string[] { ".ctor", "<X>k__BackingField", "get_X", "set_X", "X", "M", "M", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "Deconstruct", ".ctor", }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordInsideGenericType() { var src = @" var c = new C<int>.Nested(2); System.Console.Write(c.T); public class C<T> { public record struct Nested(T T); } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void PositionalMemberModifiers_RefOrOut() { var src = @" record struct R(ref int P1, out int P2); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,15): error CS0177: The out parameter 'P2' must be assigned to before control leaves the current method // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_ParamUnassigned, "R").WithArguments("P2").WithLocation(2, 15), // (2,17): error CS0631: ref and out are not valid in this context // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(2, 17), // (2,29): error CS0631: ref and out are not valid in this context // record struct R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(2, 29) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_This() { var src = @" record struct R(this int i); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,17): error CS0027: Keyword 'this' is not available in the current context // record struct R(this int i); Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(2, 17) ); } [Fact, WorkItem(45591, "https://github.com/dotnet/roslyn/issues/45591")] public void Clone_DisallowedInSource() { var src = @" record struct C1(string Clone); // 1 record struct C2 { string Clone; // 2 } record struct C3 { string Clone { get; set; } // 3 } record struct C5 { void Clone() { } // 4 void Clone(int i) { } // 5 } record struct C6 { class Clone { } // 6 } record struct C7 { delegate void Clone(); // 7 } record struct C8 { event System.Action Clone; // 8 } record struct Clone { Clone(int i) => throw null; } record struct C9 : System.ICloneable { object System.ICloneable.Clone() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,25): error CS8859: Members named 'Clone' are disallowed in records. // record struct C1(string Clone); // 1 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(2, 25), // (5,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone; // 2 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(5, 12), // (5,12): warning CS0169: The field 'C2.Clone' is never used // string Clone; // 2 Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C2.Clone").WithLocation(5, 12), // (9,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone { get; set; } // 3 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(9, 12), // (13,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone() { } // 4 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(13, 10), // (14,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone(int i) { } // 5 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(14, 10), // (18,11): error CS8859: Members named 'Clone' are disallowed in records. // class Clone { } // 6 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(18, 11), // (22,19): error CS8859: Members named 'Clone' are disallowed in records. // delegate void Clone(); // 7 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(22, 19), // (26,25): error CS8859: Members named 'Clone' are disallowed in records. // event System.Action Clone; // 8 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(26, 25), // (26,25): warning CS0067: The event 'C8.Clone' is never used // event System.Action Clone; // 8 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Clone").WithArguments("C8.Clone").WithLocation(26, 25) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes() { var src = @" class C<T> { } static class C2 { } ref struct RefLike{} unsafe record struct C( // 1 int* P1, // 2 int*[] P2, // 3 C<int*[]> P3, delegate*<int, int> P4, // 4 void P5, // 5 C2 P6, // 6, 7 System.ArgIterator P7, // 8 System.TypedReference P8, // 9 RefLike P9); // 10 "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (6,22): error CS0721: 'C2': static types cannot be used as parameters // unsafe record struct C( // 1 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C").WithArguments("C2").WithLocation(6, 22), // (7,10): error CS8908: The type 'int*' may not be used for a field of a record. // int* P1, // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P1").WithArguments("int*").WithLocation(7, 10), // (8,12): error CS8908: The type 'int*[]' may not be used for a field of a record. // int*[] P2, // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P2").WithArguments("int*[]").WithLocation(8, 12), // (10,25): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // delegate*<int, int> P4, // 4 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P4").WithArguments("delegate*<int, int>").WithLocation(10, 25), // (11,5): error CS1536: Invalid parameter type 'void' // void P5, // 5 Diagnostic(ErrorCode.ERR_NoVoidParameter, "void").WithLocation(11, 5), // (12,8): error CS0722: 'C2': static types cannot be used as return types // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (12,8): error CS0721: 'C2': static types cannot be used as parameters // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (13,5): error CS0610: Field or property cannot be of type 'ArgIterator' // System.ArgIterator P7, // 8 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 5), // (14,5): error CS0610: Field or property cannot be of type 'TypedReference' // System.TypedReference P8, // 9 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 5), // (15,5): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // RefLike P9); // 10 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 5) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record struct C { public int* f1; // 1 public int*[] f2; // 2 public C<int*[]> f3; public delegate*<int, int> f4; // 3 public void f5; // 4 public C2 f6; // 5 public System.ArgIterator f7; // 6 public System.TypedReference f8; // 7 public RefLike f9; // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1; // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2; // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4; // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,12): error CS0670: Field cannot have void type // public void f5; // 4 Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void").WithLocation(12, 12), // (13,15): error CS0723: Cannot declare a variable of static type 'C2' // public C2 f6; // 5 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(13, 15), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7; // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8; // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9; // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers_AutoProperties() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record struct C { public int* f1 { get; set; } // 1 public int*[] f2 { get; set; } // 2 public C<int*[]> f3 { get; set; } public delegate*<int, int> f4 { get; set; } // 3 public void f5 { get; set; } // 4 public C2 f6 { get; set; } // 5, 6 public System.ArgIterator f7 { get; set; } // 6 public System.TypedReference f8 { get; set; } // 7 public RefLike f9 { get; set; } // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1 { get; set; } // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2 { get; set; } // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4 { get; set; } // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,17): error CS0547: 'C.f5': property or indexer cannot have void type // public void f5 { get; set; } // 4 Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "f5").WithArguments("C.f5").WithLocation(12, 17), // (13,20): error CS0722: 'C2': static types cannot be used as return types // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("C2").WithLocation(13, 20), // (13,25): error CS0721: 'C2': static types cannot be used as parameters // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("C2").WithLocation(13, 25), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7 { get; set; } // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8 { get; set; } // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9 { get; set; } // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [Fact] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_PointerTypeAllowedForParameterAndProperty() { var src = @" class C<T> { } unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) { int* P1 { get { System.Console.Write(""P1 ""); return null; } init { } } int*[] P2 { get { System.Console.Write(""P2 ""); return null; } init { } } C<int*[]> P3 { get { System.Console.Write(""P3 ""); return null; } init { } } public unsafe static void Main() { var x = new C(null, null, null); var (x1, x2, x3) = x; System.Console.Write(""RAN""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeDebugExe); comp.VerifyEmitDiagnostics( // (4,29): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(4, 29), // (4,40): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(4, 40), // (4,54): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // unsafe record struct C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(4, 54) ); CompileAndVerify(comp, expectedOutput: "P1 P2 P3 RAN", verify: Verification.Skipped /* pointers */); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_StaticFields() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public static int* f1; public static int*[] f2; public static C<int*[]> f3; public static delegate*<int, int> f4; public static C2 f6; // 1 public static System.ArgIterator f7; // 2 public static System.TypedReference f8; // 3 public static RefLike f9; // 4 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (12,22): error CS0723: Cannot declare a variable of static type 'C2' // public static C2 f6; // 1 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(12, 22), // (13,19): error CS0610: Field or property cannot be of type 'ArgIterator' // public static System.ArgIterator f7; // 2 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 19), // (14,19): error CS0610: Field or property cannot be of type 'TypedReference' // public static System.TypedReference f8; // 3 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 19), // (15,19): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public static RefLike f9; // 4 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 19) ); } [Fact] public void RecordProperties_01() { var src = @" using System; record struct C(int X, int Y) { int Z = 345; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); Console.Write(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"12345").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 26 (0x1a) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4 0x159 IL_0014: stfld ""int C.Z"" IL_0019: ret } "); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); Assert.False(c.IsReadOnly); var x = (IPropertySymbol)c.GetMember("X"); Assert.Equal("readonly System.Int32 C.X.get", x.GetMethod.ToTestDisplayString()); Assert.Equal("void C.X.set", x.SetMethod.ToTestDisplayString()); Assert.False(x.SetMethod!.IsInitOnly); var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField"); Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString()); Assert.False(xBackingField.IsReadOnly); } [Fact] public void RecordProperties_01_EmptyParameterList() { var src = @" using System; record struct C() { int Z = 345; public static void Main() { var c = new C(); Console.Write(c.Z); } }"; CreateCompilation(src).VerifyEmitDiagnostics(); } [Fact] public void RecordProperties_01_Readonly() { var src = @" using System; readonly record struct C(int X, int Y) { readonly int Z = 345; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); Console.Write(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"12345").VerifyDiagnostics(); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); Assert.True(c.IsReadOnly); var x = (IPropertySymbol)c.GetMember("X"); Assert.Equal("System.Int32 C.X.get", x.GetMethod.ToTestDisplayString()); Assert.Equal("void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init", x.SetMethod.ToTestDisplayString()); Assert.True(x.SetMethod!.IsInitOnly); var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField"); Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString()); Assert.True(xBackingField.IsReadOnly); } [Fact] public void RecordProperties_01_ReadonlyMismatch() { var src = @" readonly record struct C(int X) { public int X { get; set; } = X; // 1 } record struct C2(int X) { public int X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,16): error CS8341: Auto-implemented instance properties in readonly structs must be readonly. // public int X { get; set; } = X; // 1 Diagnostic(ErrorCode.ERR_AutoPropsInRoStruct, "X").WithLocation(4, 16) ); } [Fact] public void RecordProperties_02() { var src = @" using System; record struct C(int X, int Y) { public C(int a, int b) { } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } private int X1 = X; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types // public C(int a, int b) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(5, 12), // (5,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public C(int a, int b) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(5, 12), // (11,21): error CS0121: The call is ambiguous between the following methods or properties: 'C.C(int, int)' and 'C.C(int, int)' // var c = new C(1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "C").WithArguments("C.C(int, int)", "C.C(int, int)").WithLocation(11, 21) ); } [Fact] public void RecordProperties_03() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,15): error CS0843: Auto-implemented property 'C.X' must be fully assigned before control is returned to the caller. // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "C").WithArguments("C.X").WithLocation(3, 15), // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_03_InitializedWithY() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } = Y; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); } }"; CompileAndVerify(src, expectedOutput: "22") .VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_04() { var src = @" using System; record struct C(int X, int Y) { public int X { get; } = 3; public static void Main() { var c = new C(1, 2); Console.Write(c.X); Console.Write(c.Y); } }"; CompileAndVerify(src, expectedOutput: "32") .VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); } [Fact] public void RecordProperties_05() { var src = @" record struct C(int X, int X) { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,28): error CS0100: The parameter name 'X' is a duplicate // record struct C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 28), // (2,28): error CS0102: The type 'C' already contains a definition for 'X' // record struct C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 28) ); var expectedMembers = new[] { "System.Int32 C.X { get; set; }", "System.Int32 C.X { get; set; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var expectedMemberNames = new[] { ".ctor", "<X>k__BackingField", "get_X", "set_X", "X", "<X>k__BackingField", "get_X", "set_X", "X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "Deconstruct", ".ctor" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordProperties_06() { var src = @" record struct C(int X, int Y) { public void get_X() { } public void set_X() { } int get_Y(int value) => value; int set_Y(int value) => value; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,21): error CS0082: Type 'C' already reserves a member called 'get_X' with the same parameter types // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "X").WithArguments("get_X", "C").WithLocation(2, 21), // (2,28): error CS0082: Type 'C' already reserves a member called 'set_Y' with the same parameter types // record struct C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "Y").WithArguments("set_Y", "C").WithLocation(2, 28) ); var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "System.Int32 C.<X>k__BackingField", "readonly System.Int32 C.X.get", "void C.X.set", "System.Int32 C.X { get; set; }", "System.Int32 C.<Y>k__BackingField", "readonly System.Int32 C.Y.get", "void C.Y.set", "System.Int32 C.Y { get; set; }", "void C.get_X()", "void C.set_X()", "System.Int32 C.get_Y(System.Int32 value)", "System.Int32 C.set_Y(System.Int32 value)", "readonly System.String C.ToString()", "readonly System.Boolean C.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C left, C right)", "System.Boolean C.op_Equality(C left, C right)", "readonly System.Int32 C.GetHashCode()", "readonly System.Boolean C.Equals(System.Object obj)", "readonly System.Boolean C.Equals(C other)", "readonly void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", "C..ctor()", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void RecordProperties_07() { var comp = CreateCompilation(@" record struct C1(object P, object get_P); record struct C2(object get_P, object P);"); comp.VerifyDiagnostics( // (2,25): error CS0102: The type 'C1' already contains a definition for 'get_P' // record struct C1(object P, object get_P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C1", "get_P").WithLocation(2, 25), // (3,39): error CS0102: The type 'C2' already contains a definition for 'get_P' // record struct C2(object get_P, object P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C2", "get_P").WithLocation(3, 39) ); } [Fact] public void RecordProperties_08() { var comp = CreateCompilation(@" record struct C1(object O1) { public object O1 { get; } = O1; public object O2 { get; } = O1; }"); comp.VerifyDiagnostics(); } [Fact] public void RecordProperties_09() { var src = @" record struct C(object P1, object P2, object P3, object P4) { class P1 { } object P2 = 2; int P3(object o) => 3; int P4<T>(T t) => 4; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS0102: The type 'C' already contains a definition for 'P1' // record struct C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(2, 24), // (2,35): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record struct C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(2, 35), // (6,9): error CS0102: The type 'C' already contains a definition for 'P3' // int P3(object o) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(6, 9), // (7,9): error CS0102: The type 'C' already contains a definition for 'P4' // int P4<T>(T t) => 4; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(7, 9) ); } [Fact] public void RecordProperties_10() { var src = @" record struct C(object P) { const int P = 4; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,24): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'. // record struct C(object P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "object", "P").WithLocation(2, 24), // (2,24): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct C(object P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 24) ); } [Fact] public void RecordProperties_11_UnreadPositionalParameter() { var comp = CreateCompilation(@" record struct C1(object O1, object O2, object O3) // 1, 2 { public object O1 { get; init; } public object O2 { get; init; } = M(O2); public object O3 { get; init; } = M(O3 = null); private static object M(object o) => o; } "); comp.VerifyDiagnostics( // (2,15): error CS0843: Auto-implemented property 'C1.O1' must be fully assigned before control is returned to the caller. // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "C1").WithArguments("C1.O1").WithLocation(2, 15), // (2,25): warning CS8907: Parameter 'O1' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O1").WithArguments("O1").WithLocation(2, 25), // (2,47): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 47) ); } [Fact] public void RecordProperties_11_UnreadPositionalParameter_InRefOut() { var comp = CreateCompilation(@" record struct C1(object O1, object O2, object O3) // 1 { public object O1 { get; init; } = MIn(in O1); public object O2 { get; init; } = MRef(ref O2); public object O3 { get; init; } = MOut(out O3); static object MIn(in object o) => o; static object MRef(ref object o) => o; static object MOut(out object o) => throw null; } "); comp.VerifyDiagnostics( // (2,47): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record struct C1(object O1, object O2, object O3) // 1 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 47) ); } [Fact] public void RecordProperties_SelfContainedStruct() { var comp = CreateCompilation(@" record struct C(C c); "); comp.VerifyDiagnostics( // (2,19): error CS0523: Struct member 'C.c' of type 'C' causes a cycle in the struct layout // record struct C(C c); Diagnostic(ErrorCode.ERR_StructLayoutCycle, "c").WithArguments("C.c", "C").WithLocation(2, 19) ); } [Fact] public void RecordProperties_PropertyInValueType() { var corlib_cs = @" namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public bool X { get; set; } } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var corlibRef = CreateEmptyCompilation(corlib_cs).EmitToImageReference(); { var src = @" record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,22): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 22) ); Assert.Null(comp.GlobalNamespace.GetTypeMember("C").GetMember("X")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().Expression; Assert.Equal("System.Boolean System.ValueType.X { get; set; }", model.GetSymbolInfo(x!).Symbol.ToTestDisplayString()); } { var src = @" readonly record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,31): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // readonly record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 31) ); Assert.Null(comp.GlobalNamespace.GetTypeMember("C").GetMember("X")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().Expression; Assert.Equal("System.Boolean System.ValueType.X { get; set; }", model.GetSymbolInfo(x!).Symbol.ToTestDisplayString()); } } [Fact] public void RecordProperties_PropertyInValueType_Static() { var corlib_cs = @" namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public static bool X { get; set; } } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var corlibRef = CreateEmptyCompilation(corlib_cs).EmitToImageReference(); var src = @" record struct C(bool X) { bool M() { return X; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview, references: new[] { corlibRef }); comp.VerifyEmitDiagnostics( // (2,22): error CS8866: Record member 'System.ValueType.X' must be a readable instance property or field of type 'bool' to match positional parameter 'X'. // record struct C(bool X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("System.ValueType.X", "bool", "X").WithLocation(2, 22), // (2,22): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(bool X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 22) ); } [Fact] public void StaticCtor() { var src = @" record R(int x) { static void Main() { } static R() { System.Console.Write(""static ctor""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "static ctor", verify: Verification.Skipped /* init-only */); } [Fact] public void StaticCtor_ParameterlessPrimaryCtor() { var src = @" record struct R(int I) { static R() { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void StaticCtor_CopyCtor() { var src = @" record struct R(int I) { static R(R r) { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,12): error CS0132: 'R.R(R)': a static constructor must be parameterless // static R(R r) { } Diagnostic(ErrorCode.ERR_StaticConstParam, "R").WithArguments("R.R(R)").WithLocation(4, 12) ); } [Fact] public void InterfaceImplementation_NotReadonly() { var source = @" I r = new R(42); r.P2 = 43; r.P3 = 44; System.Console.Write((r.P1, r.P2, r.P3)); interface I { int P1 { get; set; } int P2 { get; set; } int P3 { get; set; } } record struct R(int P1) : I { public int P2 { get; set; } = 0; int I.P3 { get; set; } = 0; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44)"); } [Fact] public void InterfaceImplementation_NotReadonly_InitOnlyInterface() { var source = @" interface I { int P1 { get; init; } } record struct R(int P1) : I; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,27): error CS8854: 'R' does not implement interface member 'I.P1.init'. 'R.P1.set' cannot implement 'I.P1.init'. // record struct R(int P1) : I; Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("R", "I.P1.init", "R.P1.set").WithLocation(6, 27) ); } [Fact] public void InterfaceImplementation_Readonly() { var source = @" I r = new R(42) { P2 = 43 }; System.Console.Write((r.P1, r.P2)); interface I { int P1 { get; init; } int P2 { get; init; } } readonly record struct R(int P1) : I { public int P2 { get; init; } = 0; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43)", verify: Verification.Skipped /* init-only */); } [Fact] public void InterfaceImplementation_Readonly_SetInterface() { var source = @" interface I { int P1 { get; set; } } readonly record struct R(int P1) : I; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,36): error CS8854: 'R' does not implement interface member 'I.P1.set'. 'R.P1.init' cannot implement 'I.P1.set'. // readonly record struct R(int P1) : I; Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "I").WithArguments("R", "I.P1.set", "R.P1.init").WithLocation(6, 36) ); } [Fact] public void InterfaceImplementation_Readonly_PrivateImplementation() { var source = @" I r = new R(42) { P2 = 43, P3 = 44 }; System.Console.Write((r.P1, r.P2, r.P3)); interface I { int P1 { get; init; } int P2 { get; init; } int P3 { get; init; } } readonly record struct R(int P1) : I { public int P2 { get; init; } = 0; int I.P3 { get; init; } = 0; // not practically initializable } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,28): error CS0117: 'R' does not contain a definition for 'P3' // I r = new R(42) { P2 = 43, P3 = 44 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "P3").WithArguments("R", "P3").WithLocation(2, 28) ); } [Fact] public void Initializers_01() { var src = @" using System; record struct C(int X) { int Z = X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Single(); Assert.Equal("C", recordDeclaration.Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclaration)); } [Fact] public void Initializers_02() { var src = @" record struct C(int X) { static int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,20): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // static int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 20) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; set; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_03() { var src = @" record struct C(int X) { const int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // const int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 19) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; set; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_04() { var src = @" using System; record struct C(int X) { Func<int> Z = () => X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z()); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("() => X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("lambda expression", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void SynthesizedRecordPointerProperty() { var src = @" record struct R(int P1, int* P2, delegate*<int> P3);"; var comp = CreateCompilation(src); var p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P1"); Assert.False(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P2"); Assert.True(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P3"); Assert.True(p.HasPointerType); } [Fact] public void PositionalMemberModifiers_In() { var src = @" var r = new R(42); int i = 43; var r2 = new R(in i); System.Console.Write((r.P1, r2.P1)); record struct R(in int P1); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "(42, 43)"); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(in System.Int32 P1)", "R..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void PositionalMemberModifiers_Params() { var src = @" var r = new R(42, 43); var r2 = new R(new[] { 44, 45 }); System.Console.Write((r.Array[0], r.Array[1], r2.Array[0], r2.Array[1])); record struct R(params int[] Array); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44, 45)"); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(params System.Int32[] Array)", "R..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void PositionalMemberDefaultValue() { var src = @" var r = new R(); // This uses the parameterless constructor System.Console.Write(r.P); record struct R(int P = 42); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "0"); } [Fact] public void PositionalMemberDefaultValue_PassingOneArgument() { var src = @" var r = new R(41); System.Console.Write(r.O); System.Console.Write("" ""); System.Console.Write(r.P); record struct R(int O, int P = 42); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "41 42"); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithInitializer() { var src = @" var r = new R(0); System.Console.Write(r.P); record struct R(int O, int P = 1) { public int P { get; init; } = 42; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,28): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int O, int P = 1) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(5, 28) ); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int, int)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<O>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldc.i4.s 42 IL_000a: stfld ""int R.<P>k__BackingField"" IL_000f: ret }"); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithoutInitializer() { var src = @" record struct R(int P = 42) { public int P { get; init; } public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): error CS0843: Auto-implemented property 'R.P' must be fully assigned before control is returned to the caller. // record struct R(int P = 42) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "R").WithArguments("R.P").WithLocation(2, 15), // (2,21): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int P = 42) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 21) ); } [Fact] public void PositionalMemberDefaultValue_AndPropertyWithInitializer_CopyingParameter() { var src = @" var r = new R(0); System.Console.Write(r.P); record struct R(int O, int P = 42) { public int P { get; init; } = P; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int, int)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<O>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int R.<P>k__BackingField"" IL_000e: ret }"); } [Fact] public void RecordWithConstraints_NullableWarning() { var src = @" #nullable enable var r = new R<string?>(""R""); var r2 = new R2<string?>(""R2""); System.Console.Write((r.P, r2.P)); record struct R<T>(T P) where T : class; record struct R2<T>(T P) where T : class { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,15): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r = new R<string?>("R"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R<T>", "T", "string?").WithLocation(3, 15), // (4,17): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R2<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r2 = new R2<string?>("R2"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R2<T>", "T", "string?").WithLocation(4, 17) ); CompileAndVerify(comp, expectedOutput: "(R, R2)"); } [Fact] public void RecordWithConstraints_ConstraintError() { var src = @" record struct R<T>(T P) where T : class; record struct R2<T>(T P) where T : class { } public class C { public static void Main() { _ = new R<int>(1); _ = new R2<int>(2); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,19): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R<T>' // _ = new R<int>(1); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R<T>", "T", "int").WithLocation(9, 19), // (10,20): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R2<T>' // _ = new R2<int>(2); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R2<T>", "T", "int").WithLocation(10, 20) ); } [Fact] public void CyclicBases4() { var text = @" record struct A<T> : B<A<T>> { } record struct B<T> : A<B<T>> { A<T> F() { return null; } } "; var comp = CreateCompilation(text); comp.GetDeclarationDiagnostics().Verify( // (3,22): error CS0527: Type 'A<B<T>>' in interface list is not an interface // record struct B<T> : A<B<T>> Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "A<B<T>>").WithArguments("A<B<T>>").WithLocation(3, 22), // (2,22): error CS0527: Type 'B<A<T>>' in interface list is not an interface // record struct A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "B<A<T>>").WithArguments("B<A<T>>").WithLocation(2, 22) ); } [Fact] public void PartialClassWithDifferentTupleNamesInImplementedInterfaces() { var source = @" public interface I<T> { } public partial record C1 : I<(int a, int b)> { } public partial record C1 : I<(int notA, int notB)> { } public partial record C2 : I<(int a, int b)> { } public partial record C2 : I<(int, int)> { } public partial record C3 : I<(int a, int b)> { } public partial record C3 : I<(int a, int b)> { } public partial record C4 : I<(int a, int b)> { } public partial record C4 : I<(int b, int a)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,23): error CS8140: 'I<(int notA, int notB)>' is already listed in the interface list on type 'C1' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C1 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C1").WithArguments("I<(int notA, int notB)>", "I<(int a, int b)>", "C1").WithLocation(3, 23), // (6,23): error CS8140: 'I<(int, int)>' is already listed in the interface list on type 'C2' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C2 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C2").WithArguments("I<(int, int)>", "I<(int a, int b)>", "C2").WithLocation(6, 23), // (12,23): error CS8140: 'I<(int b, int a)>' is already listed in the interface list on type 'C4' with different tuple element names, as 'I<(int a, int b)>'. // public partial record C4 : I<(int a, int b)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C4").WithArguments("I<(int b, int a)>", "I<(int a, int b)>", "C4").WithLocation(12, 23) ); } [Fact] public void CS0267ERR_PartialMisplaced() { var test = @" partial public record struct C // CS0267 { } "; CreateCompilation(test).VerifyDiagnostics( // (2,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial public record struct C // CS0267 Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1) ); } [Fact] public void SealedStaticRecord() { var source = @" sealed static record struct R; "; CreateCompilation(source).VerifyDiagnostics( // (2,29): error CS0106: The modifier 'sealed' is not valid for this item // sealed static record struct R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("sealed").WithLocation(2, 29), // (2,29): error CS0106: The modifier 'static' is not valid for this item // sealed static record struct R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 29) ); } [Fact] public void CS0513ERR_AbstractInConcreteClass02() { var text = @" record struct C { public abstract event System.Action E; public abstract int this[int x] { get; set; } } "; CreateCompilation(text).VerifyDiagnostics( // (5,25): error CS0106: The modifier 'abstract' is not valid for this item // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(5, 25), // (4,41): error CS0106: The modifier 'abstract' is not valid for this item // public abstract event System.Action E; Diagnostic(ErrorCode.ERR_BadMemberFlag, "E").WithArguments("abstract").WithLocation(4, 41) ); } [Fact] public void CS0574ERR_BadDestructorName() { var test = @" public record struct iii { ~iiii(){} } "; CreateCompilation(test).VerifyDiagnostics( // (4,6): error CS0574: Name of destructor must match name of type // ~iiii(){} Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(4, 6), // (4,6): error CS0575: Only class types can contain destructors // ~iiii(){} Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "iiii").WithArguments("iii.~iii()").WithLocation(4, 6) ); } [Fact] public void StaticRecordWithConstructorAndDestructor() { var text = @" static record struct R(int I) { public R() : this(0) { } ~R() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,22): error CS0106: The modifier 'static' is not valid for this item // static record struct R(int I) Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 22), // (5,6): error CS0575: Only class types can contain destructors // ~R() { } Diagnostic(ErrorCode.ERR_OnlyClassesCanContainDestructors, "R").WithArguments("R.~R()").WithLocation(5, 6) ); } [Fact] public void RecordWithPartialMethodExplicitImplementation() { var source = @"record struct R { partial void M(); }"; CreateCompilation(source).VerifyDiagnostics( // (3,18): error CS0751: A partial method must be declared within a partial type // partial void M(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 18) ); } [Fact] public void RecordWithPartialMethodRequiringBody() { var source = @"partial record struct R { public partial int M(); }"; CreateCompilation(source).VerifyDiagnostics( // (3,24): error CS8795: Partial method 'R.M()' must have an implementation part because it has accessibility modifiers. // public partial int M(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "M").WithArguments("R.M()").WithLocation(3, 24) ); } [Fact] public void CanDeclareIteratorInRecord() { var source = @" using System.Collections.Generic; foreach(var i in new X(42).GetItems()) { System.Console.Write(i); } public record struct X(int a) { public IEnumerable<int> GetItems() { yield return a; yield return a + 1; } }"; var comp = CreateCompilation(source).VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "4243"); } [Fact] public void ParameterlessConstructor() { var src = @" System.Console.Write(new C().Property); record struct C() { public int Property { get; set; } = 42; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void XmlDoc() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record struct C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact] public void XmlDoc_Cref() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for <see cref=""I1""/></param> public record struct C(int I1) { /// <summary>Summary</summary> /// <param name=""x"">Description for <see cref=""x""/></param> public void M(int x) { } } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,52): warning CS1574: XML comment has cref attribute 'x' that could not be resolved // /// <param name="x">Description for <see cref="x"/></param> Diagnostic(ErrorCode.WRN_BadXMLRef, "x").WithArguments("x").WithLocation(7, 52) ); var tree = comp.SyntaxTrees.Single(); var docComments = tree.GetCompilationUnitRoot().DescendantTrivia().Select(trivia => trivia.GetStructure()).OfType<DocumentationCommentTriviaSyntax>(); var cref = docComments.First().DescendantNodes().OfType<XmlCrefAttributeSyntax>().First().Cref; Assert.Equal("I1", cref.ToString()); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal(SymbolKind.Property, model.GetSymbolInfo(cref).Symbol!.Kind); } [Fact] public void Deconstruct_Simple() { var source = @"using System; record struct B(int X, int Y) { public static void Main() { M(new B(1, 2)); } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""readonly int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""readonly int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); var deconstruct = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("B.Deconstruct"); Assert.Equal(2, deconstruct.ParameterCount); Assert.Equal(RefKind.Out, deconstruct.Parameters[0].RefKind); Assert.Equal("X", deconstruct.Parameters[0].Name); Assert.Equal(RefKind.Out, deconstruct.Parameters[1].RefKind); Assert.Equal("Y", deconstruct.Parameters[1].Name); Assert.True(deconstruct.ReturnsVoid); Assert.False(deconstruct.IsVirtual); Assert.False(deconstruct.IsStatic); Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility); } [Fact] public void Deconstruct_PositionalAndNominalProperty() { var source = @"using System; record struct B(int X) { public int Y { get; init; } = 0; public static void Main() { M(new B(1)); } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal( "readonly void B.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Nested() { var source = @"using System; record struct B(int X, int Y); record struct C(B B, int Z) { public static void Main() { M(new C(new B(1, 2), 3)); } static void M(C c) { switch (c) { case C(B(int x, int y), int z): Console.Write(x); Console.Write(y); Console.Write(z); break; } } } "; var verifier = CompileAndVerify(source, expectedOutput: "123"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""readonly int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""readonly int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""readonly B C.B.get"" IL_0007: stobj ""B"" IL_000c: ldarg.2 IL_000d: ldarg.0 IL_000e: call ""readonly int C.Z.get"" IL_0013: stind.i4 IL_0014: ret }"); } [Fact] public void Deconstruct_PropertyCollision() { var source = @"using System; record struct B(int X, int Y) { public int X => 3; static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "32"); verifier.VerifyDiagnostics( // (3,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct B(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 21) ); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_01() { var source = @" record struct B(int X, int Y) { public int X() => 3; static void M(B b) { switch (b) { case B(int x, int y): break; } } static void Main() { M(new B(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS0102: The type 'B' already contains a definition for 'X' // public int X() => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("B", "X").WithLocation(4, 16) ); Assert.Equal( "readonly void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_FieldCollision() { var source = @" using System; record struct C(int X) { int X = 0; static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(0)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 21), // (6,9): warning CS0414: The field 'C.X' is assigned but its value is never used // int X = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "X").WithArguments("C.X").WithLocation(6, 9)); Assert.Equal( "readonly void C.Deconstruct(out System.Int32 X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty() { var source = @" record struct C { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); Assert.Null(comp.GetMember("C.Deconstruct")); } [Fact] public void Deconstruct_Conversion_02() { var source = @" #nullable enable using System; record struct C(string? X, string Y) { public string X { get; init; } = null!; public string? Y { get; init; } = string.Empty; static void M(C c) { switch (c) { case C(var x, string y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(""a"", ""b"")); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,25): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record struct C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 25), // (5,35): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record struct C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 35) ); Assert.Equal( "readonly void C.Deconstruct(out System.String? X, out System.String Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty_WithParameterList() { var source = @" record struct C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); AssertEx.Equal(new[] { "C..ctor()", "void C.M(C c)", "void C.Main()", "readonly System.String C.ToString()", "readonly System.Boolean C.PrintMembers(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C left, C right)", "System.Boolean C.op_Equality(C left, C right)", "readonly System.Int32 C.GetHashCode()", "readonly System.Boolean C.Equals(System.Object obj)", "readonly System.Boolean C.Equals(C other)" }, comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings()); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_01() { var source = @"using System; record struct C(int I) { public void Deconstruct() { } static void M(C c) { switch (c) { case C(): Console.Write(12); break; } } public static void Main() { M(new C(42)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordDeconstruct>("A.Deconstruct"); Assert.True(method.IsDeclaredReadOnly); } [Fact] public void Deconstruct_WihtNonReadOnlyGetter_GeneratedAsNonReadOnly() { var src = @" record struct A(int I, string S) { public int I { get => 0; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // record struct A(int I, string S) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 21)); var method = comp.GetMember<SynthesizedRecordDeconstruct>("A.Deconstruct"); Assert.False(method.IsDeclaredReadOnly); } [Fact] public void Deconstruct_UserDefined() { var source = @"using System; record struct B(int X, int Y) { public void Deconstruct(out int X, out int Y) { X = this.X + 1; Y = this.Y + 2; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(0, 0)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_02() { var source = @"using System; record struct B(int X) { public int Deconstruct(out int a) => throw null; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,16): error CS8874: Record member 'B.Deconstruct(out int)' must return 'void'. // public int Deconstruct(out int a) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Deconstruct").WithArguments("B.Deconstruct(out int)", "void").WithLocation(5, 16), // (11,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'B', with 1 out parameters and a void return type. // case B(int x): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int x)").WithArguments("B", "1").WithLocation(11, 19)); Assert.Equal("System.Int32 B.Deconstruct(out System.Int32 a)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] public void Deconstruct_UserDefined_Accessibility_07(string accessibility) { var source = $@" record struct A(int X) {{ { accessibility } void Deconstruct(out int a) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,11): error CS8873: Record member 'A.Deconstruct(out int)' must be public. // void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 11 + accessibility.Length) ); } [Fact] public void Deconstruct_UserDefined_Static_08() { var source = @" record struct A(int X) { public static void Deconstruct(out int a) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS8877: Record member 'A.Deconstruct(out int)' may not be static. // public static void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 24) ); } [Fact] public void OutVarInPositionalParameterDefaultValue() { var source = @" record struct A(int X = A.M(out int a) + a) { public static int M(out int a) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,25): error CS1736: Default parameter value for 'X' must be a compile-time constant // record struct A(int X = A.M(out int a) + a) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "A.M(out int a) + a").WithArguments("X").WithLocation(2, 25) ); } [Fact] public void FieldConsideredUnassignedIfInitializationViaProperty() { var source = @" record struct Pos(int X) { private int x; public int X { get { return x; } set { x = value; } } = X; } record struct Pos2(int X) { private int x = X; // value isn't validated by setter public int X { get { return x; } set { x = value; } } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0171: Field 'Pos.x' must be fully assigned before control is returned to the caller // record struct Pos(int X) Diagnostic(ErrorCode.ERR_UnassignedThis, "Pos").WithArguments("Pos.x").WithLocation(2, 15), // (5,16): error CS8050: Only auto-implemented properties can have initializers. // public int X { get { return x; } set { x = value; } } = X; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "X").WithArguments("Pos.X").WithLocation(5, 16) ); } [Fact] public void IEquatableT_01() { var source = @"record struct A<T>; class Program { static void F<T>(System.IEquatable<T> t) { } static void M<T>() { F(new A<T>()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( ); } [Fact] public void IEquatableT_02() { var source = @"using System; record struct A; record struct B<T>; class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "TrueTrue").VerifyDiagnostics(); } [Fact] public void IEquatableT_02_ImplicitImplementation() { var source = @"using System; record struct A { public bool Equals(A other) { System.Console.Write(""A.Equals(A) ""); return false; } } record struct B<T> { public bool Equals(B<T> other) { System.Console.Write(""B.Equals(B) ""); return true; } } class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write("" ""); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "A.Equals(A) False B.Equals(B) True").VerifyDiagnostics( // (4,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 17), // (12,17): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public bool Equals(B<T> other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(12, 17) ); } [Fact] public void IEquatableT_02_ExplicitImplementation() { var source = @"using System; record struct A { bool IEquatable<A>.Equals(A other) { System.Console.Write(""A.Equals(A) ""); return false; } } record struct B<T> { bool IEquatable<B<T>>.Equals(B<T> other) { System.Console.Write(""B.Equals(B) ""); return true; } } class Program { static bool F<T>(IEquatable<T> t, T t2) { return t.Equals(t2); } static void Main() { Console.Write(F(new A(), new A())); Console.Write("" ""); Console.Write(F(new B<int>(), new B<int>())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "A.Equals(A) False B.Equals(B) True").VerifyDiagnostics(); } [Fact] public void IEquatableT_03() { var source = @" record struct A<T> : System.IEquatable<A<T>>; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_MissingIEquatable() { var source = @" record struct A<T>; "; var comp = CreateCompilation(source); comp.MakeTypeMissing(WellKnownType.System_IEquatable_T); comp.VerifyEmitDiagnostics( // (2,15): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record struct A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record struct A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 15) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void RecordEquals_01() { var source = @" var a1 = new B(); var a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); record struct B { public bool Equals(B other) { System.Console.WriteLine(""B.Equals(B)""); return false; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,17): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public bool Equals(B other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(8, 17) ); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False "); } [Fact] public void RecordEquals_01_NoInParameters() { var source = @" var a1 = new B(); var a2 = new B(); System.Console.WriteLine(a1.Equals(in a2)); record struct B; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,39): error CS1615: Argument 1 may not be passed with the 'in' keyword // System.Console.WriteLine(a1.Equals(in a2)); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "a2").WithArguments("1", "in").WithLocation(4, 39) ); } [Theory] [InlineData("protected")] [InlineData("private protected")] [InlineData("internal protected")] public void RecordEquals_10(string accessibility) { var source = $@" record struct A {{ { accessibility } bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,29): error CS0666: 'A.Equals(A)': new protected member declared in struct // internal protected bool Equals(A x) Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,29): error CS8873: Record member 'A.Equals(A)' must be public. // internal protected bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,29): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // internal protected bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 11 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] public void RecordEquals_11(string accessibility) { var source = $@" record struct A {{ { accessibility } bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,...): error CS8873: Record member 'A.Equals(A)' must be public. // { accessibility } bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 11 + accessibility.Length), // (4,11): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 11 + accessibility.Length) ); } [Fact] public void RecordEquals_12() { var source = @" A a1 = new A(); A a2 = new A(); System.Console.Write(a1.Equals(a2)); System.Console.Write(a1.Equals((object)a2)); record struct A { public bool Equals(B other) => throw null; } class B { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueTrue"); verifier.VerifyIL("A.Equals(A)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("A.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""A"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""A"" IL_000f: call ""readonly bool A.Equals(A)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("readonly System.Boolean A.Equals(A other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.False(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); var objectEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordObjEquals>().Single(); Assert.Equal("readonly System.Boolean A.Equals(System.Object obj)", objectEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, objectEquals.DeclaredAccessibility); Assert.False(objectEquals.IsAbstract); Assert.False(objectEquals.IsVirtual); Assert.True(objectEquals.IsOverride); Assert.False(objectEquals.IsSealed); Assert.True(objectEquals.IsImplicitlyDeclared); MethodSymbol gethashCode = comp.GetMembers("A." + WellKnownMemberNames.ObjectGetHashCode).OfType<SynthesizedRecordGetHashCode>().Single(); Assert.Equal("readonly System.Int32 A.GetHashCode()", gethashCode.ToTestDisplayString()); Assert.Equal(Accessibility.Public, gethashCode.DeclaredAccessibility); Assert.False(gethashCode.IsStatic); Assert.False(gethashCode.IsAbstract); Assert.False(gethashCode.IsVirtual); Assert.True(gethashCode.IsOverride); Assert.False(gethashCode.IsSealed); Assert.True(gethashCode.IsImplicitlyDeclared); } [Fact] public void RecordEquals_13() { var source = @" record struct A { public int Equals(A other) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,16): error CS8874: Record member 'A.Equals(A)' must return 'bool'. // public int Equals(A other) Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 16), // (4,16): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public int Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 16) ); } [Fact] public void RecordEquals_14() { var source = @" record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record struct A { public bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record struct A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 15), // (4,12): error CS0518: Predefined type 'System.Boolean' is not defined or imported // public bool Equals(A other) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(4, 12), // (4,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 17) ); } [Fact] public void RecordEquals_19() { var source = @" record struct A { public static bool Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is static. // record struct A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 15), // (4,24): error CS8877: Record member 'A.Equals(A)' may not be static. // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void RecordEquals_RecordEqualsInValueType() { var src = @" public record struct A; namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual int GetHashCode() => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public bool Equals(A x) => throw null; } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) ); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("readonly System.Boolean A.Equals(A other)", recordEquals.ToTestDisplayString()); } [Fact] public void RecordEquals_FourFields() { var source = @" A a1 = new A(1, ""hello""); System.Console.Write(a1.Equals(a1)); System.Console.Write(a1.Equals((object)a1)); System.Console.Write("" - ""); A a2 = new A(1, ""hello"") { fieldI = 100 }; System.Console.Write(a1.Equals(a2)); System.Console.Write(a1.Equals((object)a2)); System.Console.Write(a2.Equals(a1)); System.Console.Write(a2.Equals((object)a1)); System.Console.Write("" - ""); A a3 = new A(1, ""world""); System.Console.Write(a1.Equals(a3)); System.Console.Write(a1.Equals((object)a3)); System.Console.Write(a3.Equals(a1)); System.Console.Write(a3.Equals((object)a1)); record struct A(int I, string S) { public int fieldI = 42; public string fieldS = ""hello""; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueTrue - FalseFalseFalseFalse - FalseFalseFalseFalse"); verifier.VerifyIL("A.Equals(A)", @" { // Code size 97 (0x61) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int A.<I>k__BackingField"" IL_000b: ldarg.1 IL_000c: ldfld ""int A.<I>k__BackingField"" IL_0011: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0016: brfalse.s IL_005f IL_0018: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_001d: ldarg.0 IL_001e: ldfld ""string A.<S>k__BackingField"" IL_0023: ldarg.1 IL_0024: ldfld ""string A.<S>k__BackingField"" IL_0029: callvirt ""bool System.Collections.Generic.EqualityComparer<string>.Equals(string, string)"" IL_002e: brfalse.s IL_005f IL_0030: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0035: ldarg.0 IL_0036: ldfld ""int A.fieldI"" IL_003b: ldarg.1 IL_003c: ldfld ""int A.fieldI"" IL_0041: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0046: brfalse.s IL_005f IL_0048: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_004d: ldarg.0 IL_004e: ldfld ""string A.fieldS"" IL_0053: ldarg.1 IL_0054: ldfld ""string A.fieldS"" IL_0059: callvirt ""bool System.Collections.Generic.EqualityComparer<string>.Equals(string, string)"" IL_005e: ret IL_005f: ldc.i4.0 IL_0060: ret }"); verifier.VerifyIL("A.Equals(object)", @" { // Code size 23 (0x17) .maxstack 2 IL_0000: ldarg.1 IL_0001: isinst ""A"" IL_0006: brfalse.s IL_0015 IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: unbox.any ""A"" IL_000f: call ""readonly bool A.Equals(A)"" IL_0014: ret IL_0015: ldc.i4.0 IL_0016: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 86 (0x56) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0005: ldarg.0 IL_0006: ldfld ""int A.<I>k__BackingField"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_0010: ldc.i4 0xa5555529 IL_0015: mul IL_0016: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""string A.<S>k__BackingField"" IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<string>.GetHashCode(string)"" IL_0026: add IL_0027: ldc.i4 0xa5555529 IL_002c: mul IL_002d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0032: ldarg.0 IL_0033: ldfld ""int A.fieldI"" IL_0038: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_003d: add IL_003e: ldc.i4 0xa5555529 IL_0043: mul IL_0044: call ""System.Collections.Generic.EqualityComparer<string> System.Collections.Generic.EqualityComparer<string>.Default.get"" IL_0049: ldarg.0 IL_004a: ldfld ""string A.fieldS"" IL_004f: callvirt ""int System.Collections.Generic.EqualityComparer<string>.GetHashCode(string)"" IL_0054: add IL_0055: ret }"); } [Fact] public void RecordEquals_StaticField() { var source = @" record struct A { public static int field = 42; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("A.Equals(A)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: ret }"); verifier.VerifyIL("A.GetHashCode()", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); } [Fact] public void RecordEquals_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.True(recordEquals.IsDeclaredReadOnly); } [Fact] public void ObjectEquals_06() { var source = @" record struct A { public static new bool Equals(object obj) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,28): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public static new bool Equals(object obj) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(4, 28) ); } [Fact] public void ObjectEquals_UserDefined() { var source = @" record struct A { public override bool Equals(object obj) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,26): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public override bool Equals(object obj) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(4, 26) ); } [Fact] public void ObjectEquals_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var objectEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordObjEquals>().Single(); Assert.True(objectEquals.IsDeclaredReadOnly); } [Fact] public void GetHashCode_UserDefined() { var source = @" System.Console.Write(new A().GetHashCode()); record struct A { public override int GetHashCode() => 42; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [Fact] public void GetHashCode_GetHashCodeInValueType() { var src = @" public record struct A; namespace System { public class Object { public virtual bool Equals(object x) => throw null; public virtual string ToString() => throw null; } public class Exception { } public class ValueType { public virtual int GetHashCode() => throw null; } public class Attribute { } public class String { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { } } namespace System.Collections.Generic { public abstract class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null; public abstract int GetHashCode(T t); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (2,22): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public record struct A; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "A").WithArguments("A.GetHashCode()").WithLocation(2, 22) ); } [Fact] public void GetHashCode_MissingEqualityComparer_EmptyRecord() { var src = @" public record struct A; "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Collections_Generic_EqualityComparer_T); comp.VerifyEmitDiagnostics(); } [Fact] public void GetHashCode_MissingEqualityComparer_NonEmptyRecord() { var src = @" public record struct A(int I); "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Collections_Generic_EqualityComparer_T); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // public record struct A(int I); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "public record struct A(int I);").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // public record struct A(int I); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "public record struct A(int I);").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1) ); } [Fact] public void GetHashCode_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordGetHashCode>("A.GetHashCode"); Assert.True(method.IsDeclaredReadOnly); } [Fact] public void GetHashCodeIsDefinedButEqualsIsNot() { var src = @" public record struct C { public object Data; public override int GetHashCode() { return 0; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void EqualsIsDefinedButGetHashCodeIsNot() { var src = @" public record struct C { public object Data; public bool Equals(C c) { return false; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public bool Equals(C c) { return false; } Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(5, 17)); } [Fact] public void EqualityOperators_01() { var source = @" record struct A(int X) { public bool Equals(ref A other) => throw null; static void Main() { Test(default, default); Test(default, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); var a = new A(11); Test(a, a); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } "; var verifier = CompileAndVerify(source, expectedOutput: @" True True False False True True False False True True False False False False True True True True False False ").VerifyDiagnostics(); var comp = (CSharpCompilation)verifier.Compilation; MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(); Assert.Equal("System.Boolean A.op_Equality(A left, A right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single(); Assert.Equal("System.Boolean A.op_Inequality(A left, A right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); verifier.VerifyIL("bool A.op_Equality(A, A)", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: ldarg.1 IL_0003: call ""readonly bool A.Equals(A)"" IL_0008: ret } "); verifier.VerifyIL("bool A.op_Inequality(A, A)", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool A.op_Equality(A, A)"" IL_0007: ldc.i4.0 IL_0008: ceq IL_000a: ret } "); } [Fact] public void EqualityOperators_03() { var source = @" record struct A { public static bool operator==(A r1, A r2) => throw null; public static bool operator==(A r1, string r2) => throw null; public static bool operator!=(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool operator==(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "==").WithArguments("op_Equality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_04() { var source = @" record struct A { public static bool operator!=(A r1, A r2) => throw null; public static bool operator!=(string r1, A r2) => throw null; public static bool operator==(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool operator!=(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "!=").WithArguments("op_Inequality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_05() { var source = @" record struct A { public static bool op_Equality(A r1, A r2) => throw null; public static bool op_Equality(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool op_Equality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Equality").WithArguments("op_Equality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_06() { var source = @" record struct A { public static bool op_Inequality(A r1, A r2) => throw null; public static bool op_Inequality(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool op_Inequality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Inequality").WithArguments("op_Inequality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_07() { var source = @" record struct A { public static bool Equals(A other) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is static. // record struct A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 15), // (4,24): error CS8877: Record member 'A.Equals(A)' may not be static. // public static bool Equals(A other) Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Theory] [CombinatorialData] public void EqualityOperators_09(bool useImageReference) { var source1 = @" public record struct A(int X); "; var comp1 = CreateCompilation(source1); var source2 = @" class Program { static void Main() { Test(default, default); Test(default, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } "; CompileAndVerify(source2, references: new[] { useImageReference ? comp1.EmitToImageReference() : comp1.ToMetadataReference() }, expectedOutput: @" True True False False True True False False True True False False False False True True ").VerifyDiagnostics(); } [Fact] public void GetSimpleNonTypeMembers_DirectApiCheck() { var src = @" public record struct RecordB(); "; var comp = CreateCompilation(src); var b = comp.GlobalNamespace.GetTypeMember("RecordB"); AssertEx.SetEqual(new[] { "System.Boolean RecordB.op_Equality(RecordB left, RecordB right)" }, b.GetSimpleNonTypeMembers("op_Equality").ToTestDisplayStrings()); } [Fact] public void ToString_NestedRecord() { var src = @" var c1 = new Outer.C1(42); System.Console.Write(c1.ToString()); public class Outer { public record struct C1(int I1); } "; var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }"); compDebug.VerifyEmitDiagnostics(); CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }"); compRelease.VerifyEmitDiagnostics(); } [Fact] public void ToString_TopLevelRecord_Empty() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: call ""readonly bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilder() { var src = @" record struct C1; "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Text_StringBuilder); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record struct C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "record struct C1;").WithArguments("System.Text.StringBuilder").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record struct C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C1").WithArguments("System.Text.StringBuilder").WithLocation(2, 15) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderCtor() { var src = @" record struct C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__ctor); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderAppendString() { var src = @" record struct C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record struct C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1;").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendString() { var src = @" record struct C1(int P); "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record struct C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record struct C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record struct C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_RecordWithIndexer() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); record struct C1(int I1) { private int field = 44; public int this[int i] => 0; public int PropertyWithoutGetter { set { } } public int P2 { get => 43; } public event System.Action a = null; private int field1 = 100; internal int field2 = 100; private int Property1 { get; set; } = 100; internal int Property2 { get; set; } = 100; } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "C1 { I1 = 42, P2 = 43 }"); comp.VerifyEmitDiagnostics( // (7,17): warning CS0414: The field 'C1.field' is assigned but its value is never used // private int field = 44; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C1.field").WithLocation(7, 17), // (11,32): warning CS0414: The field 'C1.a' is assigned but its value is never used // public event System.Action a = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("C1.a").WithLocation(11, 32), // (13,17): warning CS0414: The field 'C1.field1' is assigned but its value is never used // private int field1 = 100; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field1").WithArguments("C1.field1").WithLocation(13, 17) ); } [Fact] public void ToString_PrivateGetter() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1 { public int P1 { private get => 43; set => throw null; } } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "C1 { P1 = 43 }"); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_TopLevelRecord_OneField_ValueType() { var src = @" var c1 = new C1() { field = 42 }; System.Console.Write(c1.ToString()); record struct C1 { public int field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 38 (0x26) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""field = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldflda ""int C1.field"" IL_0013: constrained. ""int"" IL_0019: callvirt ""string object.ToString()"" IL_001e: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0023: pop IL_0024: ldc.i4.1 IL_0025: ret } "); } [Fact] public void ToString_TopLevelRecord_OneField_ConstrainedValueType() { var src = @" var c1 = new C1<int>() { field = 42 }; System.Console.Write(c1.ToString()); record struct C1<T> where T : struct { public T field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 41 (0x29) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.1 IL_0001: ldstr ""field = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldfld ""T C1<T>.field"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""T"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldc.i4.1 IL_0028: ret } "); } [Fact] public void ToString_TopLevelRecord_OneField_ReferenceType() { var src = @" var c1 = new C1() { field = ""hello"" }; System.Console.Write(c1.ToString()); record struct C1 { public string field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""field = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldfld ""string C1.field"" IL_0013: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0018: pop IL_0019: ldc.i4.1 IL_001a: ret } "); } [Fact] public void ToString_TopLevelRecord_TwoFields_ReferenceType() { var src = @" var c1 = new C1(42) { field1 = ""hi"", field2 = null }; System.Console.Write(c1.ToString()); record struct C1(int I) { public string field1 = null; public string field2 = null; private string field3 = null; internal string field4 = null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (10,20): warning CS0414: The field 'C1.field3' is assigned but its value is never used // private string field3 = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field3").WithArguments("C1.field3").WithLocation(10, 20) ); var v = CompileAndVerify(comp, expectedOutput: "C1 { I = 42, field1 = hi, field2 = }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 91 (0x5b) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldstr ""I = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: call ""readonly int C1.I.get"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""int"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldarg.1 IL_0028: ldstr "", field1 = "" IL_002d: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0032: pop IL_0033: ldarg.1 IL_0034: ldarg.0 IL_0035: ldfld ""string C1.field1"" IL_003a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_003f: pop IL_0040: ldarg.1 IL_0041: ldstr "", field2 = "" IL_0046: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_004b: pop IL_004c: ldarg.1 IL_004d: ldarg.0 IL_004e: ldfld ""string C1.field2"" IL_0053: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0058: pop IL_0059: ldc.i4.1 IL_005a: ret } "); } [Fact] public void ToString_TopLevelRecord_Readonly() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); readonly record struct C1(int I); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { I = 42 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 41 (0x29) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldstr ""I = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: call ""int C1.I.get"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: constrained. ""int"" IL_001c: callvirt ""string object.ToString()"" IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0026: pop IL_0027: ldc.i4.1 IL_0028: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: call ""bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record struct C1 { public override string ToString() => ""RAN""; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal("readonly System.Boolean C1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", print.ToTestDisplayString()); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_New() { var src = @" record struct C1 { public new string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,23): error CS8869: 'C1.ToString()' does not override expected method from 'object'. // public new string ToString() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "ToString").WithArguments("C1.ToString()").WithLocation(4, 23) ); } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_Sealed() { var src = @" record struct C1 { public sealed override string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,35): error CS0106: The modifier 'sealed' is not valid for this item // public sealed override string ToString() => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "ToString").WithArguments("sealed").WithLocation(4, 35) ); } [Fact] public void ToString_UserDefinedPrintMembers_WithNullableStringBuilder() { var src = @" #nullable enable record struct C1 { private bool PrintMembers(System.Text.StringBuilder? builder) => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_ErrorReturnType() { var src = @" record struct C1 { private Error PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,13): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // private Error PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 13) ); } [Fact] public void ToString_UserDefinedPrintMembers_WrongReturnType() { var src = @" record struct C1 { private int PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,17): error CS8874: Record member 'C1.PrintMembers(StringBuilder)' must return 'bool'. // private int PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "bool").WithLocation(4, 17) ); } [Fact] public void ToString_UserDefinedPrintMembers() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); System.Console.Write("" - ""); c1.M(); record struct C1 { private bool PrintMembers(System.Text.StringBuilder builder) { builder.Append(""RAN""); return true; } public void M() { var builder = new System.Text.StringBuilder(); if (PrintMembers(builder)) { System.Console.Write(builder.ToString()); } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { RAN } - RAN"); } [Fact] public void ToString_CallingSynthesizedPrintMembers() { var src = @" var c1 = new C1(1, 2, 3); System.Console.Write(c1.ToString()); System.Console.Write("" - ""); c1.M(); record struct C1(int I, int I2, int I3) { public void M() { var builder = new System.Text.StringBuilder(); if (PrintMembers(builder)) { System.Console.Write(builder.ToString()); } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { I = 1, I2 = 2, I3 = 3 } - I = 1, I2 = 2, I3 = 3"); } [Fact] public void ToString_UserDefinedPrintMembers_WrongAccessibility() { var src = @" var c = new C1(); System.Console.Write(c.ToString()); record struct C1 { internal bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (7,19): error CS8879: Record member 'C1.PrintMembers(StringBuilder)' must be private. // internal bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(7, 19) ); } [Fact] public void ToString_UserDefinedPrintMembers_Static() { var src = @" record struct C1 { static private bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,25): error CS8877: Record member 'C1.PrintMembers(StringBuilder)' may not be static. // static private bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25) ); } [Fact] public void ToString_GeneratedAsReadOnly() { var src = @" record struct A(int I, string S); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordToString>("A.ToString"); Assert.True(method.IsDeclaredReadOnly); } [Fact] public void ToString_WihtNonReadOnlyGetter_GeneratedAsNonReadOnly() { var src = @" record struct A(int I, string S) { public double T => 0.1; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var method = comp.GetMember<SynthesizedRecordToString>("A.ToString"); Assert.False(method.IsDeclaredReadOnly); } [Fact] public void AmbigCtor_WithPropertyInitializer() { // Scenario causes ambiguous ctor for record class, but not record struct var src = @" record struct R(R X) { public R X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,14): error CS0523: Struct member 'R.X' of type 'R' causes a cycle in the struct layout // public R X { get; init; } = X; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "X").WithArguments("R.X", "R").WithLocation(4, 14) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var parameterSyntax = tree.GetRoot().DescendantNodes().OfType<ParameterSyntax>().Single(); var parameter = model.GetDeclaredSymbol(parameterSyntax)!; Assert.Equal("R X", parameter.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, parameter.Kind); Assert.Equal("R..ctor(R X)", parameter.ContainingSymbol.ToTestDisplayString()); var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); var initializer = model.GetSymbolInfo(initializerSyntax.Value).Symbol!; Assert.Equal("R X", initializer.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, initializer.Kind); Assert.Equal("R..ctor(R X)", initializer.ContainingSymbol.ToTestDisplayString()); var src2 = @" record struct R(R X); "; var comp2 = CreateCompilation(src2); comp2.VerifyEmitDiagnostics( // (2,19): error CS0523: Struct member 'R.X' of type 'R' causes a cycle in the struct layout // record struct R(R X); Diagnostic(ErrorCode.ERR_StructLayoutCycle, "X").WithArguments("R.X", "R").WithLocation(2, 19) ); } [Fact] public void GetDeclaredSymbolOnAnOutLocalInPropertyInitializer() { var src = @" record struct R(int I) { public int I { get; init; } = M(out int i); static int M(out int i) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // record struct R(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 21) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var outVarSyntax = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Single(); var outVar = model.GetDeclaredSymbol(outVarSyntax)!; Assert.Equal("System.Int32 i", outVar.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, outVar.Kind); Assert.Equal("System.Int32 R.<I>k__BackingField", outVar.ContainingSymbol.ToTestDisplayString()); } [Fact] public void AnalyzerActions_01() { // Test RegisterSyntaxNodeAction var text1 = @" record struct A([Attr1]int X = 0) : I1 { private int M() => 3; A(string S) : this(4) => throw null; } interface I1 {} class Attr1 : System.Attribute {} "; var analyzer = new AnalyzerActions_01_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(1, analyzer.FireCountRecordStructDeclarationA); Assert.Equal(1, analyzer.FireCountRecordStructDeclarationACtor); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCountSimpleBaseTypeI1onA); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCountParameterListAPrimaryCtor); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCountConstructorDeclaration); Assert.Equal(1, analyzer.FireCountStringParameterList); Assert.Equal(1, analyzer.FireCountThisConstructorInitializer); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); } private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer { public int FireCount0; public int FireCountRecordStructDeclarationA; public int FireCountRecordStructDeclarationACtor; public int FireCount3; public int FireCountSimpleBaseTypeI1onA; public int FireCount5; public int FireCountParameterListAPrimaryCtor; public int FireCount7; public int FireCountConstructorDeclaration; public int FireCountStringParameterList; public int FireCountThisConstructorInitializer; public int FireCount11; public int FireCount12; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.ThisConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordStructDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); } protected void Handle1(SyntaxNodeAnalysisContext context) { var literal = (LiteralExpressionSyntax)context.Node; switch (literal.ToString()) { case "0": Interlocked.Increment(ref FireCount0); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "3": Interlocked.Increment(ref FireCount7); Assert.Equal("System.Int32 A.M()", context.ContainingSymbol.ToTestDisplayString()); break; case "4": Interlocked.Increment(ref FireCount12); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(literal.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle2(SyntaxNodeAnalysisContext context) { var equalsValue = (EqualsValueClauseSyntax)context.Node; switch (equalsValue.ToString()) { case "= 0": Interlocked.Increment(ref FireCount3); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(equalsValue.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle3(SyntaxNodeAnalysisContext context) { var initializer = (ConstructorInitializerSyntax)context.Node; switch (initializer.ToString()) { case ": this(4)": Interlocked.Increment(ref FireCountThisConstructorInitializer); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(initializer.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle4(SyntaxNodeAnalysisContext context) { Interlocked.Increment(ref FireCountConstructorDeclaration); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); } protected void Fail(SyntaxNodeAnalysisContext context) { Assert.True(false); } protected void Handle6(SyntaxNodeAnalysisContext context) { var record = (RecordDeclarationSyntax)context.Node; Assert.Equal(SyntaxKind.RecordStructDeclaration, record.Kind()); switch (context.ContainingSymbol.ToTestDisplayString()) { case "A": Interlocked.Increment(ref FireCountRecordStructDeclarationA); break; case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCountRecordStructDeclarationACtor); break; default: Assert.True(false); break; } Assert.Same(record.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle7(SyntaxNodeAnalysisContext context) { var identifier = (IdentifierNameSyntax)context.Node; switch (identifier.Identifier.ValueText) { case "Attr1": Interlocked.Increment(ref FireCount5); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; } } protected void Handle8(SyntaxNodeAnalysisContext context) { var baseType = (SimpleBaseTypeSyntax)context.Node; switch (baseType.ToString()) { case "I1": switch (context.ContainingSymbol.ToTestDisplayString()) { case "A": Interlocked.Increment(ref FireCountSimpleBaseTypeI1onA); break; default: Assert.True(false); break; } break; case "System.Attribute": break; default: Assert.True(false); break; } } protected void Handle9(SyntaxNodeAnalysisContext context) { var parameterList = (ParameterListSyntax)context.Node; switch (parameterList.ToString()) { case "([Attr1]int X = 0)": Interlocked.Increment(ref FireCountParameterListAPrimaryCtor); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "(string S)": Interlocked.Increment(ref FireCountStringParameterList); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; case "()": break; default: Assert.True(false); break; } } protected void Handle10(SyntaxNodeAnalysisContext context) { var argumentList = (ArgumentListSyntax)context.Node; switch (argumentList.ToString()) { case "(4)": Interlocked.Increment(ref FireCount11); Assert.Equal("A..ctor(System.String S)", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_02() { // Test RegisterSymbolAction var text1 = @" record struct A(int X = 0) {} record struct C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_02_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); } private class AnalyzerActions_02_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.Method); context.RegisterSymbolAction(Handle, SymbolKind.Property); context.RegisterSymbolAction(Handle, SymbolKind.Parameter); context.RegisterSymbolAction(Handle, SymbolKind.NamedType); } private void Handle(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "System.Int32 A.X { get; set; }": Interlocked.Increment(ref FireCount2); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount6); break; case "C": Interlocked.Increment(ref FireCount7); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_03() { // Test RegisterSymbolStartAction var text1 = @" readonly record struct A(int X = 0) {} readonly record struct C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_03_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(0, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(0, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); } private class AnalyzerActions_03_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolStartAction(Handle1, SymbolKind.Method); context.RegisterSymbolStartAction(Handle1, SymbolKind.Property); context.RegisterSymbolStartAction(Handle1, SymbolKind.Parameter); context.RegisterSymbolStartAction(Handle1, SymbolKind.NamedType); } private void Handle1(SymbolStartAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); context.RegisterSymbolEndAction(Handle2); break; case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount2); context.RegisterSymbolEndAction(Handle3); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); context.RegisterSymbolEndAction(Handle4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount9); Assert.Equal(0, FireCount1); Assert.Equal(0, FireCount2); Assert.Equal(0, FireCount6); Assert.Equal(0, FireCount7); context.RegisterSymbolEndAction(Handle5); break; case "C": Interlocked.Increment(ref FireCount10); Assert.Equal(0, FireCount4); Assert.Equal(0, FireCount8); context.RegisterSymbolEndAction(Handle6); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { Assert.Equal("A..ctor([System.Int32 X = 0])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); } private void Handle3(SymbolAnalysisContext context) { Assert.Equal("System.Int32 A.X { get; init; }", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); } private void Handle4(SymbolAnalysisContext context) { Assert.Equal("C..ctor([System.Int32 Z = 4])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); } private void Handle5(SymbolAnalysisContext context) { Assert.Equal("A", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount11); Assert.Equal(1, FireCount1); Assert.Equal(1, FireCount2); Assert.Equal(1, FireCount6); Assert.Equal(1, FireCount7); } private void Handle6(SymbolAnalysisContext context) { Assert.Equal("C", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount12); Assert.Equal(1, FireCount4); Assert.Equal(1, FireCount8); } } [Fact] public void AnalyzerActions_04() { // Test RegisterOperationAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 {} interface I1 {} "; var analyzer = new AnalyzerActions_04_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(0, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount14); } private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount6; public int FireCount7; public int FireCount14; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationAction(HandleConstructorBody, OperationKind.ConstructorBody); context.RegisterOperationAction(HandleInvocation, OperationKind.Invocation); context.RegisterOperationAction(HandleLiteral, OperationKind.Literal); context.RegisterOperationAction(HandleParameterInitializer, OperationKind.ParameterInitializer); context.RegisterOperationAction(Fail, OperationKind.PropertyInitializer); context.RegisterOperationAction(Fail, OperationKind.FieldInitializer); } protected void HandleConstructorBody(OperationAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind()); VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation, @""); break; default: Assert.True(false); break; } } protected void HandleInvocation(OperationAnalysisContext context) { Assert.True(false); } protected void HandleLiteral(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "100": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); break; case "0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); break; default: Assert.True(false); break; } } protected void HandleParameterInitializer(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "= 0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount14); break; default: Assert.True(false); break; } } protected void Fail(OperationAnalysisContext context) { Assert.True(false); } } [Fact] public void AnalyzerActions_05() { // Test RegisterOperationBlockAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 {} interface I1 {} "; var analyzer = new AnalyzerActions_05_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); } private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer { public int FireCount1; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockAction(Handle); } private void Handle(OperationBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_07() { // Test RegisterCodeBlockAction var text1 = @" record struct A([Attr1(100)]int X = 0) : I1 { int M() => 3; } interface I1 {} "; var analyzer = new AnalyzerActions_07_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(Handle); } private void Handle(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1); break; default: Assert.True(false); break; } break; case "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_08() { // Test RegisterCodeBlockStartAction var text1 = @" record struct A([Attr1]int X = 0) : I1 { private int M() => 3; A(string S) : this(4) => throw null; } interface I1 {} "; var analyzer = new AnalyzerActions_08_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount100); Assert.Equal(1, analyzer.FireCount400); Assert.Equal(1, analyzer.FireCount500); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(0, analyzer.FireCountRecordStructDeclarationA); Assert.Equal(0, analyzer.FireCountRecordStructDeclarationACtor); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(0, analyzer.FireCountSimpleBaseTypeI1onA); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(0, analyzer.FireCountParameterListAPrimaryCtor); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(0, analyzer.FireCountConstructorDeclaration); Assert.Equal(0, analyzer.FireCountStringParameterList); Assert.Equal(1, analyzer.FireCountThisConstructorInitializer); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount1000); Assert.Equal(1, analyzer.FireCount4000); Assert.Equal(1, analyzer.FireCount5000); } private class AnalyzerActions_08_Analyzer : AnalyzerActions_01_Analyzer { public int FireCount100; public int FireCount400; public int FireCount500; public int FireCount1000; public int FireCount4000; public int FireCount5000; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(Handle); } private void Handle(CodeBlockStartAnalysisContext<SyntaxKind> context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount100); break; default: Assert.True(false); break; } break; case "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount400); break; default: Assert.True(false); break; } break; case "A..ctor(System.String S)": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount500); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.ThisConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Fail, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordStructDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); context.RegisterCodeBlockEndAction(Handle11); } private void Handle11(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1000); break; default: Assert.True(false); break; } break; case "System.Int32 A.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4000); break; default: Assert.True(false); break; } break; case "A..ctor(System.String S)": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount5000); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_09() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_09_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); } private class AnalyzerActions_09_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle1, SymbolKind.Method); context.RegisterSymbolAction(Handle2, SymbolKind.Property); context.RegisterSymbolAction(Handle3, SymbolKind.Parameter); } private void Handle1(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount5); break; case "System.Int32 B.Y { get; init; }": Interlocked.Increment(ref FireCount6); break; default: Assert.True(false); break; } } private void Handle3(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount7); break; case "[System.Int32 Y = 1]": Interlocked.Increment(ref FireCount8); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount9); break; default: Assert.True(false); break; } } } [Fact] public void WithExprOnStruct_LangVersion() { var src = @" var b = new B() { X = 1 }; var b2 = b.M(); System.Console.Write(b2.X); System.Console.Write("" ""); System.Console.Write(b.X); public struct B { public int X { get; set; } public B M() /*<bind>*/{ return this with { X = 42 }; }/*</bind>*/ }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (13,16): error CS8773: Feature 'with on structs' is not available in C# 9.0. Please use language version 10.0 or greater. // return this with { X = 42 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "this with { X = 42 }").WithArguments("with on structs", "10.0").WithLocation(13, 16) ); comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 1"); verifier.VerifyIL("B.M", @" { // Code size 18 (0x12) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: ldobj ""B"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: ldc.i4.s 42 IL_000b: call ""void B.X.set"" IL_0010: ldloc.0 IL_0011: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var with = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var type = model.GetTypeInfo(with); Assert.Equal("B", type.Type.ToTestDisplayString()); var operation = model.GetOperation(with); VerifyOperationTree(comp, operation, @" IWithOperation (OperationKind.With, Type: B) (Syntax: 'this with { X = 42 }') Operand: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: B) (Syntax: '{ X = 42 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'X') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_DuplicateInitialization() { var src = @" public struct B { public int X { get; set; } public B M() /*<bind>*/{ return this with { X = 42, X = 43 }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (8,36): error CS1912: Duplicate initialization of member 'X' // return this with { X = 42, X = 43 }; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(8, 36) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 42') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'X = 43') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 43) (Syntax: '43') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_NestedInitializer() { var src = @" public struct C { public int Y { get; set; } } public struct B { public C X { get; set; } public B M() /*<bind>*/{ return this with { X = { Y = 1 } }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (12,32): error CS1525: Invalid expression term '{' // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "{").WithArguments("{").WithLocation(12, 32), // (12,32): error CS1513: } expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(12, 32), // (12,32): error CS1002: ; expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(12, 32), // (12,34): error CS0103: The name 'Y' does not exist in the current context // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_NameNotInContext, "Y").WithArguments("Y").WithLocation(12, 34), // (12,34): warning CS0162: Unreachable code detected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.WRN_UnreachableCode, "Y").WithLocation(12, 34), // (12,40): error CS1002: ; expected // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(12, 40), // (12,43): error CS1597: Semicolon after method or accessor block is not valid // return this with { X = { Y = 1 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(12, 43), // (14,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(14, 1) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsInvalid) (Syntax: 'X = ') Left: IPropertyReferenceOperation: C B.X { get; set; } (OperationKind.PropertyReference, Type: C) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Next (Return) Block[B3] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Y = 1 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Y = 1') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Y') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_ControlFlow_NonAssignmentExpression() { var src = @" public struct B { public int X { get; set; } public B M(int i, int j) /*<bind>*/{ return this with { i, j++, M2(), X = 2}; }/*</bind>*/ static int M2() => 0; }"; var expectedDiagnostics = new[] { // (8,28): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "i").WithLocation(8, 28), // (8,31): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "j++").WithLocation(8, 31), // (8,36): error CS0747: Invalid initializer member declarator // return this with { i, j++, M2(), X = 2}; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "M2()").WithLocation(8, 36) }; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'j++') Children(1): IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32, IsInvalid) (Syntax: 'j++') Target: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2()') Children(1): IInvocationOperation (System.Int32 B.M2()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 B.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Return) Block[B2] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'this') Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void ObjectCreationInitializer_ControlFlow_WithCoalescingExpressionForValue() { var src = @" public struct B { public string X; public void M(string hello) /*<bind>*/{ var x = new B() { X = Identity((string)null) ?? Identity(hello) }; }/*</bind>*/ T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [B x] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Value: IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B) (Syntax: 'new B() { X ... ty(hello) }') Arguments(0) Initializer: null 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: 'Identity((string)null)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity((string)null)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '(string)null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') 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) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity((string)null)') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(hello)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(hello)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'hello') IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') 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) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'X = Identit ... tity(hello)') Left: IFieldReferenceOperation: System.String B.X (OperationKind.FieldReference, Type: System.String) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((s ... tity(hello)') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: B, IsImplicit) (Syntax: 'x = new B() ... ty(hello) }') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: B, IsImplicit) (Syntax: 'x = new B() ... ty(hello) }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'new B() { X ... ty(hello) }') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics); } [Fact] public void WithExprOnStruct_ControlFlow_WithCoalescingExpressionForValue() { var src = @" var b = new B() { X = string.Empty }; var b2 = b.M(""hello""); System.Console.Write(b2.X); public struct B { public string X; public B M(string hello) /*<bind>*/{ return Identity(this) with { X = Identity((string)null) ?? Identity(hello) }; }/*</bind>*/ T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "hello"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(this)') Value: IInvocationOperation ( B B.Identity<B>(B t)) (OperationKind.Invocation, Type: B) (Syntax: 'Identity(this)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'this') IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B) (Syntax: 'this') 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) 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: 'Identity((string)null)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity((string)null)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '(string)null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null) (Syntax: '(string)null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') 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) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity((string)null)') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity((string)null)') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((string)null)') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(hello)') Value: IInvocationOperation ( System.String B.Identity<System.String>(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(hello)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Identity') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'hello') IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') 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) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'X = Identit ... tity(hello)') Left: IFieldReferenceOperation: System.String B.X (OperationKind.FieldReference, Type: System.String) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'Identity(this)') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity((s ... tity(hello)') Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (0) Next (Return) Block[B7] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: B, IsImplicit) (Syntax: 'Identity(this)') Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExprOnStruct_OnParameter() { var src = @" var b = new B() { X = 1 }; var b2 = B.M(b); System.Console.Write(b2.X); public struct B { public int X { get; set; } public static B M(B b) { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M", @" { // Code size 13 (0xd) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.set"" IL_000b: ldloc.0 IL_000c: ret }"); } [Fact] public void WithExprOnStruct_OnThis() { var src = @" record struct C { public int X { get; set; } C(string ignored) { _ = this with { X = 42 }; // 1 this = default; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS0188: The 'this' object cannot be used before all of its fields have been assigned // _ = this with { X = 42 }; // 1 Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this").WithLocation(8, 13) ); } [Fact] public void WithExprOnStruct_OnTStructParameter() { var src = @" var b = new B() { X = 1 }; var b2 = B.M(b); System.Console.Write(b2.X); public interface I { int X { get; set; } } public struct B : I { public int X { get; set; } public static T M<T>(T b) where T : struct, I { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M<T>(T)", @" { // Code size 19 (0x13) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: constrained. ""T"" IL_000c: callvirt ""void I.X.set"" IL_0011: ldloc.0 IL_0012: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var with = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var type = model.GetTypeInfo(with); Assert.Equal("T", type.Type.ToTestDisplayString()); } [Fact] public void WithExprOnStruct_OnRecordStructParameter() { var src = @" var b = new B(1); var b2 = B.M(b); System.Console.Write(b2.X); public record struct B(int X) { public static B M(B b) { return b with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("B.M", @" { // Code size 13 (0xd) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.set"" IL_000b: ldloc.0 IL_000c: ret }"); } [Fact] public void WithExprOnStruct_OnRecordStructParameter_Readonly() { var src = @" var b = new B(1, 2); var b2 = B.M(b); System.Console.Write(b2.X); System.Console.Write(b2.Y); public readonly record struct B(int X, int Y) { public static B M(B b) { return b with { X = 42, Y = 43 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("B.M", @" { // Code size 22 (0x16) .maxstack 2 .locals init (B V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: call ""void B.X.init"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: call ""void B.Y.init"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple() { var src = @" class C { static void Main() { var b = (1, 2); var b2 = M(b); System.Console.Write(b2.Item1); System.Console.Write(b2.Item2); } static (int, int) M((int, int) b) { return b with { Item1 = 42, Item2 = 43 }; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int>.Item1"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple_WithNames() { var src = @" var b = (1, 2); var b2 = M(b); System.Console.Write(b2.Item1); System.Console.Write(b2.Item2); static (int, int) M((int X, int Y) b) { return b with { X = 42, Y = 43 }; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("Program.<<Main>$>g__M|0_0(System.ValueTuple<int, int>)", @" { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int>.Item1"" IL_000b: ldloca.s V_0 IL_000d: ldc.i4.s 43 IL_000f: stfld ""int System.ValueTuple<int, int>.Item2"" IL_0014: ldloc.0 IL_0015: ret }"); } [Fact] public void WithExprOnStruct_OnTuple_LongTuple() { var src = @" var b = (1, 2, 3, 4, 5, 6, 7, 8); var b2 = M(b); System.Console.Write(b2.Item7); System.Console.Write(b2.Item8); static (int, int, int, int, int, int, int, int) M((int, int, int, int, int, int, int, int) b) { return b with { Item7 = 42, Item8 = 43 }; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "4243"); verifier.VerifyIL("Program.<<Main>$>g__M|0_0(System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>)", @" { // Code size 27 (0x1b) .maxstack 2 .locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: ldc.i4.s 42 IL_0006: stfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Item7"" IL_000b: ldloca.s V_0 IL_000d: ldflda ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest"" IL_0012: ldc.i4.s 43 IL_0014: stfld ""int System.ValueTuple<int>.Item1"" IL_0019: ldloc.0 IL_001a: ret }"); } [Fact] public void WithExprOnStruct_OnReadonlyField() { var src = @" var b = new B { X = 1 }; // 1 public struct B { public readonly int X; public B M() { return this with { X = 42 }; // 2 } public static B M2(B b) { return b with { X = 42 }; // 3 } public B(int i) { this = default; _ = this with { X = 42 }; // 4 } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,17): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // var b = new B { X = 1 }; // 1 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(2, 17), // (9,28): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // return this with { X = 42 }; // 2 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(9, 28), // (13,25): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // return b with { X = 42 }; // 3 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(13, 25), // (18,25): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) // _ = this with { X = 42 }; // 4 Diagnostic(ErrorCode.ERR_AssgReadonly, "X").WithLocation(18, 25) ); } [Fact] public void WithExprOnStruct_OnEnum() { var src = @" public enum E { } class C { static E M(E e) { return e with { }; } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void WithExprOnStruct_OnPointer() { var src = @" unsafe class C { static int* M(int* i) { return i with { }; } }"; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (6,16): error CS8858: The receiver type 'int*' is not a valid record type and is not a struct type. // return i with { }; Diagnostic(ErrorCode.ERR_CannotClone, "i").WithArguments("int*").WithLocation(6, 16) ); } [Fact] public void WithExprOnStruct_OnInterface() { var src = @" public interface I { int X { get; set; } } class C { static I M(I i) { return i with { X = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (10,16): error CS8858: The receiver type 'I' is not a valid record type and is not a value type. // return i with { X = 42 }; Diagnostic(ErrorCode.ERR_CannotClone, "i").WithArguments("I").WithLocation(10, 16) ); } [Fact] public void WithExprOnStruct_OnRefStruct() { // Similar to test RefLikeObjInitializers but with `with` expressions var text = @" using System; class Program { static S2 Test1() { S1 outer = default; S1 inner = stackalloc int[1]; // error return new S2() with { Field1 = outer, Field2 = inner }; } static S2 Test2() { S1 outer = default; S1 inner = stackalloc int[1]; S2 result; // error result = new S2() with { Field1 = inner, Field2 = outer }; return result; } static S2 Test3() { S1 outer = default; S1 inner = stackalloc int[1]; return new S2() with { Field1 = outer, Field2 = outer }; } public ref struct S1 { public static implicit operator S1(Span<int> o) => default; } public ref struct S2 { public S1 Field1; public S1 Field2; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (12,48): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // return new S2() with { Field1 = outer, Field2 = inner }; Diagnostic(ErrorCode.ERR_EscapeLocal, "Field2 = inner").WithArguments("inner").WithLocation(12, 48), // (23,34): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // result = new S2() with { Field1 = inner, Field2 = outer }; Diagnostic(ErrorCode.ERR_EscapeLocal, "Field1 = inner").WithArguments("inner").WithLocation(23, 34) ); } [Fact] public void WithExprOnStruct_OnRefStruct_ReceiverMayWrap() { // Similar to test LocalWithNoInitializerEscape but wrapping method is used as receiver for `with` expression var text = @" using System; class Program { static void Main() { S1 sp; Span<int> local = stackalloc int[1]; sp = MayWrap(ref local) with { }; // 1, 2 } static S1 MayWrap(ref Span<int> arg) { return default; } ref struct S1 { public ref int this[int i] => throw null; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (9,26): error CS8352: Cannot use local 'local' in this context because it may expose referenced variables outside of their declaration scope // sp = MayWrap(ref local) with { }; // 1, 2 Diagnostic(ErrorCode.ERR_EscapeLocal, "local").WithArguments("local").WithLocation(9, 26), // (9,14): error CS8347: Cannot use a result of 'Program.MayWrap(ref Span<int>)' in this context because it may expose variables referenced by parameter 'arg' outside of their declaration scope // sp = MayWrap(ref local) with { }; // 1, 2 Diagnostic(ErrorCode.ERR_EscapeCall, "MayWrap(ref local)").WithArguments("Program.MayWrap(ref System.Span<int>)", "arg").WithLocation(9, 14) ); } [Fact] public void WithExprOnStruct_OnRefStruct_ReceiverMayWrap_02() { var text = @" using System; class Program { static void Main() { Span<int> local = stackalloc int[1]; S1 sp = MayWrap(ref local) with { }; } static S1 MayWrap(ref Span<int> arg) { return default; } ref struct S1 { public ref int this[int i] => throw null; } } "; CreateCompilationWithMscorlibAndSpan(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_01() { var src = @" #nullable enable record struct B(int X) { static void M(B b) { string? s = null; _ = b with { X = M(out s) }; s.ToString(); } static int M(out string s) { s = ""a""; return 42; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_02() { var src = @" #nullable enable record struct B(string X) { static void M(B b, string? s) { b.X.ToString(); _ = b with { X = s }; // 1 b.X.ToString(); // 2 } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): warning CS8601: Possible null reference assignment. // _ = b with { X = s }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(8, 26)); } [Fact] public void WithExpr_NullableAnalysis_03() { var src = @" #nullable enable record struct B(string? X) { static void M1(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 1 _ = b with { X = s }; if (flag) { b.X.ToString(); } // 2 } static void M2(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 3 b = b with { X = s }; if (flag) { b.X.ToString(); } } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(7, 21), // (9,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(9, 21), // (14,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(14, 21)); } [Fact, WorkItem(44763, "https://github.com/dotnet/roslyn/issues/44763")] public void WithExpr_NullableAnalysis_05() { var src = @" #nullable enable record struct B(string? X, string? Y) { static void M1(bool flag) { B b = new B(""hello"", null); if (flag) { b.X.ToString(); // shouldn't warn b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); // shouldn't warn b.Y.ToString(); } }"; // records should propagate the nullability of the // constructor arguments to the corresponding properties. // https://github.com/dotnet/roslyn/issues/44763 var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(11, 13), // (15,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(15, 9)); } [Fact] public void WithExpr_NullableAnalysis_06() { var src = @" #nullable enable struct B { public string? X { get; init; } public string? Y { get; init; } static void M1(bool flag) { B b = new B { X = ""hello"", Y = null }; if (flag) { b.X.ToString(); b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); b.Y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(14, 13) ); } [Fact] public void WithExprAssignToRef1() { var src = @" using System; record struct C(int Y) { private readonly int[] _a = new[] { 0 }; public ref int X => ref _a[0]; public static void Main() { var c = new C(0) { X = 5 }; Console.WriteLine(c.X); c = c with { X = 1 }; Console.WriteLine(c.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 5 1").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 59 (0x3b) .maxstack 2 .locals init (C V_0, //c C V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.0 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_1 IL_000a: call ""ref int C.X.get"" IL_000f: ldc.i4.5 IL_0010: stind.i4 IL_0011: ldloc.1 IL_0012: stloc.0 IL_0013: ldloca.s V_0 IL_0015: call ""ref int C.X.get"" IL_001a: ldind.i4 IL_001b: call ""void System.Console.WriteLine(int)"" IL_0020: ldloc.0 IL_0021: stloc.1 IL_0022: ldloca.s V_1 IL_0024: call ""ref int C.X.get"" IL_0029: ldc.i4.1 IL_002a: stind.i4 IL_002b: ldloc.1 IL_002c: stloc.0 IL_002d: ldloca.s V_0 IL_002f: call ""ref int C.X.get"" IL_0034: ldind.i4 IL_0035: call ""void System.Console.WriteLine(int)"" IL_003a: ret }"); } [Fact] public void WithExpressionSameLHS() { var comp = CreateCompilation(@" record struct C(int X) { public static void Main() { var c = new C(0); c = c with { X = 1, X = 2}; } }"); comp.VerifyDiagnostics( // (7,29): error CS1912: Duplicate initialization of member 'X' // c = c with { X = 1, X = 2}; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(7, 29) ); } [Fact] public void WithExpr_AnonymousType_ChangeAllProperties() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { A = Identity(30), B = Identity(40) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) { System.Console.Write($""Identity({t}) ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,17): error CS8773: Feature 'with on anonymous types' is not available in C# 9.0. Please use language version 10.0 or greater. // var b = Identity(a) with { A = Identity(30), B = Identity(40) }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Identity(a) with { A = Identity(30), B = Identity(40) }").WithArguments("with on anonymous types", "10.0").WithLocation(9, 17) ); comp = CreateCompilation(src, parseOptions: TestOptions.Regular10); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "Identity({ A = 10, B = 20 }) Identity(30) Identity(40) { A = 30, B = 40 }"); verifier.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: pop IL_000f: ldc.i4.s 30 IL_0011: call ""int C.Identity<int>(int)"" IL_0016: ldc.i4.s 40 IL_0018: call ""int C.Identity<int>(int)"" IL_001d: stloc.0 IL_001e: ldloc.0 IL_001f: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0024: call ""void System.Console.Write(object)"" IL_0029: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [2] [3] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') 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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(40)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') 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) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... ntity(40) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} } Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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) Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeAllProperties_ReverseOrder() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { B = Identity(40), A = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) { System.Console.Write($""Identity({t}) ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "Identity({ A = 10, B = 20 }) Identity(40) Identity(30) { A = 30, B = 40 }"); verifier.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: pop IL_000f: ldc.i4.s 40 IL_0011: call ""int C.Identity<int>(int)"" IL_0016: stloc.0 IL_0017: ldc.i4.s 30 IL_0019: call ""int C.Identity<int>(int)"" IL_001e: ldloc.0 IL_001f: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0024: call ""void System.Console.Write(object)"" IL_0029: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [2] [3] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') 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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(40)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') 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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} } Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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) Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeNoProperty() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = M2(a) with { }; System.Console.Write(b); }/*</bind>*/ static T M2<T>(T t) { System.Console.Write(""M2 ""); return t; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "M2 { A = 10, B = 20 }"); verifier.VerifyIL("C.M", @" { // Code size 38 (0x26) .maxstack 2 .locals init (<>f__AnonymousType0<int, int> V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.M2<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0015: ldloc.0 IL_0016: callvirt ""int <>f__AnonymousType0<int, int>.B.get"" IL_001b: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0020: call ""void System.Console.Write(object)"" IL_0025: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.M2<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'M2(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') 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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a) with { }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(a) with { }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = M2(a) with { }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = M2(a) with { }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'M2(a) with { }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a) with { }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'M2(a) with { }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a) with { }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'M2(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = a with { B = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); verifier.VerifyIL("C.M", @" { // Code size 34 (0x22) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: ldc.i4.s 30 IL_000b: call ""int C.Identity<int>(int)"" IL_0010: stloc.0 IL_0011: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0016: ldloc.0 IL_0017: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_001c: call ""void System.Console.Write(object)"" IL_0021: ret } "); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var withExpr = tree.GetRoot().DescendantNodes().OfType<WithExpressionSyntax>().Single(); var operation = model.GetOperation(withExpr); VerifyOperationTree(comp, operation, @" IWithOperation (OperationKind.With, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a with { B ... ntity(30) }') Operand: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: '{ B = Identity(30) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'B = Identity(30)') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'B') Right: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = a with ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = a with ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a with { B ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a with { B ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithMethodCallForTarget() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = Identity(a) with { B = 30 }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); verifier.VerifyIL("C.M", @" { // Code size 34 (0x22) .maxstack 2 .locals init (int V_0) IL_0000: ldc.i4.s 10 IL_0002: ldc.i4.s 20 IL_0004: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_0009: call ""<anonymous type: int A, int B> C.Identity<<anonymous type: int A, int B>>(<anonymous type: int A, int B>)"" IL_000e: ldc.i4.s 30 IL_0010: stloc.0 IL_0011: callvirt ""int <>f__AnonymousType0<int, int>.A.get"" IL_0016: ldloc.0 IL_0017: newobj ""<>f__AnonymousType0<int, int>..ctor(int, int)"" IL_001c: call ""void System.Console.Write(object)"" IL_0021: ret } "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') 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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '30') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... { B = 30 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = Identit ... { B = 30 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a) ... { B = 30 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithCoalescingExpressionForTarget() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var a = new { A = 10, B = 20 }; var b = (Identity(a) ?? Identity2(a)) with { B = 30 }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; static T Identity2<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "{ A = 10, B = 30 }"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 B> a] [<anonymous type: System.Int32 A, System.Int32 B> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'a = new { A ... 0, B = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'new { A = 10, B = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20) (Syntax: 'B = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'new { A = 10, B = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} {R5} } .locals {R3} { CaptureIds: [4] [5] .locals {R4} { CaptureIds: [2] .locals {R5} { CaptureIds: [3] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') 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) Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity(a)') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Leaving: {R5} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B5] Leaving: {R5} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity2(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 B> C.Identity2<<anonymous type: System.Int32 A, System.Int32 B>>(<anonymous type: System.Int32 A, System.Int32 B> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'Identity2(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'a') 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) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (2) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '30') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') Next (Regular) Block[B6] Leaving: {R4} } Block[B6] - Block Predecessors: [B5] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = (Identi ... { B = 30 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'b = (Identi ... { B = 30 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: '(Identity(a ... { B = 30 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 B>.B { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: '(Identity(a ... { B = 30 }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 B>, IsImplicit) (Syntax: 'Identity(a) ... dentity2(a)') Next (Regular) Block[B7] Leaving: {R3} } Block[B7] - Block Predecessors: [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 B>) (Syntax: 'b') 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) Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ChangeOneProperty_WithCoalescingExpressionForValue() { var src = @" C.M(""hello"", ""world""); public class C { public static void M(string hello, string world) /*<bind>*/{ var x = new { A = hello, B = string.Empty }; var y = x with { B = Identity(null) ?? Identity2(world) }; System.Console.Write(y); }/*</bind>*/ static string Identity(string t) => t; static string Identity2(string t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "{ A = hello, B = world }"); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.String A, System.String B> x] [<anonymous type: System.String A, System.String B> y] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'hello') Value: IParameterReferenceOperation: hello (OperationKind.ParameterReference, Type: System.String) (Syntax: 'hello') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'string.Empty') Value: IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x = new { A ... ing.Empty }') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x = new { A ... ing.Empty }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'new { A = h ... ing.Empty }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'A = hello') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'new { A = h ... ing.Empty }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'hello') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 'B = string.Empty') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.B { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'B') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'new { A = h ... ing.Empty }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'string.Empty') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [5] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'x') Next (Regular) Block[B3] Entering: {R5} .locals {R5} { CaptureIds: [4] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(null)') Value: IInvocationOperation (System.String C.Identity(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity(null)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'null') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') 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) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'Identity(null)') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity(null)') Leaving: {R5} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(null)') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Identity(null)') Next (Regular) Block[B6] Leaving: {R5} } Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity2(world)') Value: IInvocationOperation (System.String C.Identity2(System.String t)) (OperationKind.Invocation, Type: System.String) (Syntax: 'Identity2(world)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'world') IParameterReferenceOperation: world (OperationKind.ParameterReference, Type: System.String) (Syntax: 'world') 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) Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Value: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') Next (Regular) Block[B7] Leaving: {R4} } Block[B7] - Block Predecessors: [B6] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'y = x with ... y2(world) }') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'y = x with ... y2(world) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'x with { B ... y2(world) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.A { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Left: IPropertyReferenceOperation: System.String <anonymous type: System.String A, System.String B>.B { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x with { B ... y2(world) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.String A, System.String B>, IsImplicit) (Syntax: 'x') Next (Regular) Block[B8] Leaving: {R3} } Block[B8] - Block Predecessors: [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(y);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(y)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: <anonymous type: System.String A, System.String B>) (Syntax: 'y') 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) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ErrorMember() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { Error = Identity(20) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS0117: '<anonymous type: int A>' does not contain a definition for 'Error' // var b = a with { Error = Identity(20) }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("<anonymous type: int A>", "Error").WithLocation(7, 26) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(20)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '20') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') 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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { Er ... ntity(20) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Er ... ntity(20) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} {R1} } } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_ToString() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { ToString = Identity(20) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS1913: Member 'ToString' cannot be initialized. It is not a field or property. // var b = a with { ToString = Identity(20) }; Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "ToString").WithArguments("ToString").WithLocation(7, 26) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(20)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '20') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') 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) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ntity(20) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { To ... ntity(20) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { To ... ntity(20) }') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} {R1} } } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_NestedInitializer() { var src = @" C.M(); public class C { public static void M() /*<bind>*/{ var nested = new { A = 10 }; var a = new { Nested = nested }; var b = a with { Nested = { A = 20 } }; System.Console.Write(b); }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (10,35): error CS1525: Invalid expression term '{' // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "{").WithArguments("{").WithLocation(10, 35), // (10,35): error CS1513: } expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(10, 35), // (10,35): error CS1002: ; expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(10, 35), // (10,37): error CS0103: The name 'A' does not exist in the current context // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_NameNotInContext, "A").WithArguments("A").WithLocation(10, 37), // (10,44): error CS1002: ; expected // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(10, 44), // (10,47): error CS1597: Semicolon after method or accessor block is not valid // var b = a with { Nested = { A = 20 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(10, 47), // (11,29): error CS1519: Invalid token '(' in class, record, struct, or interface member declaration // System.Console.Write(b); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "(").WithArguments("(").WithLocation(11, 29), // (11,31): error CS8124: Tuple must contain at least two elements. // System.Console.Write(b); Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(11, 31), // (11,32): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // System.Console.Write(b); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(11, 32), // (13,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(13, 1) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> nested] [<anonymous type: <anonymous type: System.Int32 A> Nested> a] [<anonymous type: <anonymous type: System.Int32 A> Nested> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested = new { A = 10 }') Left: ILocalReferenceOperation: nested (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (2) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'nested') Value: ILocalReferenceOperation: nested (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'nested') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a = new { N ... = nested }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a = new { N ... = nested }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>) (Syntax: 'new { Nested = nested }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>) (Syntax: 'Nested = nested') Left: IPropertyReferenceOperation: <anonymous type: System.Int32 A> <anonymous type: <anonymous type: System.Int32 A> Nested>.Nested { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'Nested') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'new { Nested = nested }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'nested') Next (Regular) Block[B3] Leaving: {R3} Entering: {R4} } .locals {R4} { CaptureIds: [2] Block[B3] - Block Predecessors: [B2] Statements (3) ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>) (Syntax: 'a') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '') Value: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'b = a with { Nested = ') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'b = a with { Nested = ') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid) (Syntax: 'a with { Nested = ') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Left: IPropertyReferenceOperation: <anonymous type: System.Int32 A> <anonymous type: <anonymous type: System.Int32 A> Nested>.Nested { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsInvalid, IsImplicit) (Syntax: 'a with { Nested = ') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: <anonymous type: System.Int32 A> Nested>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R4} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'A = 20 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'A = 20') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'A') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_NonAssignmentExpression() { var src = @" public class C { public static void M(int i, int j) /*<bind>*/{ var a = new { A = 10 }; var b = a with { i, j++, M2(), A = 20 }; }/*</bind>*/ static int M2() => 0; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var expectedDiagnostics = new[] { // (7,26): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "i").WithLocation(7, 26), // (7,29): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "j++").WithLocation(7, 29), // (7,34): error CS0747: Invalid initializer member declarator // var b = a with { i, j++, M2(), A = 20 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "M2()").WithLocation(7, 34) }; comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (6) ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Children(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'j++') Children(1): IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32, IsInvalid) (Syntax: 'j++') Target: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2()') Children(1): IInvocationOperation (System.Int32 C.M2()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ), A = 20 }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with ... ), A = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { i, ... ), A = 20 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { i, ... ), A = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R3} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_IndexerAccess() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = a with { [0] = 20 }; }/*</bind>*/ }"; var expectedDiagnostics = new[] { // (7,26): error CS1513: } expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_RbraceExpected, "[").WithLocation(7, 26), // (7,26): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "[").WithLocation(7, 26), // (7,26): error CS7014: Attributes are not valid in this context. // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[").WithLocation(7, 26), // (7,27): error CS1001: Identifier expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_IdentifierExpected, "0").WithLocation(7, 27), // (7,27): error CS1003: Syntax error, ']' expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SyntaxError, "0").WithArguments("]", "").WithLocation(7, 27), // (7,28): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "]").WithLocation(7, 28), // (7,28): error CS1513: } expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_RbraceExpected, "]").WithLocation(7, 28), // (7,30): error CS1525: Invalid expression term '=' // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(7, 30), // (7,35): error CS1002: ; expected // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 35), // (7,36): error CS1597: Semicolon after method or accessor block is not valid // var b = a with { [0] = 20 }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(7, 36), // (9,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(9, 1) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [2] .locals {R4} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (2) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a with { ') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with { ') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = a with { ') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'a with { ') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a with { ') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'a with { ') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '[0') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '= 20 ') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '= 20') Left: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_CannotSet() { var src = @" public class C { public static void M() { var a = new { A = 10 }; a.A = 20; var b = new { B = a }; b.B.A = 30; } }"; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (7,9): error CS0200: Property or indexer '<anonymous type: int A>.A' cannot be assigned to -- it is read only // a.A = 20; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "a.A").WithArguments("<anonymous type: int A>.A").WithLocation(7, 9), // (10,9): error CS0200: Property or indexer '<anonymous type: int A>.A' cannot be assigned to -- it is read only // b.B.A = 30; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.B.A").WithArguments("<anonymous type: int A>.A").WithLocation(10, 9) ); } [Fact] public void WithExpr_AnonymousType_DuplicateMemberInDeclaration() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10, A = 20 }; var b = Identity(a) with { A = Identity(30) }; System.Console.Write(b); }/*</bind>*/ static T Identity<T>(T t) => t; }"; var expectedDiagnostics = new[] { // (6,31): error CS0833: An anonymous type cannot have multiple properties with the same name // var a = new { A = 10, A = 20 }; Diagnostic(ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, "A = 20").WithLocation(6, 31) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A, System.Int32 $1> a] [<anonymous type: System.Int32 A, System.Int32 $1> b] .locals {R2} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '20') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20, IsInvalid) (Syntax: '20') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'a = new { A ... 0, A = 20 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'a = new { A ... 0, A = 20 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid) (Syntax: 'new { A = 10, A = 20 }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { A = 10, A = 20 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 20, IsInvalid) (Syntax: 'A = 20') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { A = 10, A = 20 }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 20, IsInvalid, IsImplicit) (Syntax: '20') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} {R4} } .locals {R3} { CaptureIds: [3] [4] .locals {R4} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (3) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a)') Value: IInvocationOperation (<anonymous type: System.Int32 A, System.Int32 $1> C.Identity<<anonymous type: System.Int32 A, System.Int32 $1>>(<anonymous type: System.Int32 A, System.Int32 $1> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'a') 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) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Value: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'b = Identit ... ntity(30) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'Identity(a) ... ntity(30) }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a) ... ntity(30) }') Right: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B4] Leaving: {R3} } Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(b);') Expression: IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'b') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A, System.Int32 $1>) (Syntax: 'b') 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) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact] public void WithExpr_AnonymousType_DuplicateInitialization() { var src = @" public class C { public static void M() /*<bind>*/{ var a = new { A = 10 }; var b = Identity(a) with { A = Identity(30), A = Identity(40) }; }/*</bind>*/ static T Identity<T>(T t) => t; }"; var expectedDiagnostics = new[] { // (7,54): error CS1912: Duplicate initialization of member 'A' // var b = Identity(a) with { A = Identity(30), A = Identity(40) }; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "A").WithArguments("A").WithLocation(7, 54) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expectedDiagnostics); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [<anonymous type: System.Int32 A> a] [<anonymous type: System.Int32 A> b] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Left: ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'a = new { A = 10 }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>) (Syntax: 'new { A = 10 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, Constant: 10) (Syntax: 'A = 10') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'A') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'new { A = 10 }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: '10') Next (Regular) Block[B2] Leaving: {R2} Entering: {R3} } .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (4) IInvocationOperation (<anonymous type: System.Int32 A> C.Identity<<anonymous type: System.Int32 A>>(<anonymous type: System.Int32 A> t)) (OperationKind.Invocation, Type: <anonymous type: System.Int32 A>) (Syntax: 'Identity(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>) (Syntax: 'a') 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) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Identity(30)') Value: IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(30)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '30') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30') 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) IInvocationOperation (System.Int32 C.Identity<System.Int32>(System.Int32 t)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Identity(40)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: t) (OperationKind.Argument, Type: null) (Syntax: '40') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 40) (Syntax: '40') 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) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Left: ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'b = Identit ... ntity(40) }') Right: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 A>, IsInvalid) (Syntax: 'Identity(a) ... ntity(40) }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Left: IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 A>.A { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 A>, IsInvalid, IsImplicit) (Syntax: 'Identity(a) ... ntity(40) }') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 A>, IsImplicit) (Syntax: 'Identity(a)') Next (Regular) Block[B3] Leaving: {R3} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview); } [Fact, WorkItem(53849, "https://github.com/dotnet/roslyn/issues/53849")] public void WithExpr_AnonymousType_ValueIsLoweredToo() { var src = @" var x = new { Property = 42 }; var adjusted = x with { Property = x.Property + 2 }; System.Console.WriteLine(adjusted); "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(comp, expectedOutput: "{ Property = 44 }"); verifier.VerifyDiagnostics(); } [Fact, WorkItem(53849, "https://github.com/dotnet/roslyn/issues/53849")] public void WithExpr_AnonymousType_ValueIsLoweredToo_NestedWith() { var src = @" var x = new { Property = 42 }; var container = new { Item = x }; var adjusted = container with { Item = x with { Property = x.Property + 2 } }; System.Console.WriteLine(adjusted); "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); var verifier = CompileAndVerify(comp, expectedOutput: "{ Item = { Property = 44 } }"); verifier.VerifyDiagnostics(); } [Fact] public void AttributesOnPrimaryConstructorParameters_01() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public readonly record struct Test( [field: A] [property: B] [param: C] [D] int P1) { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.RegularPreview, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => a.AttributeClass!.Name is "A" or "B" or "C" or "D")); } } [Fact] public void FieldAsPositionalMember() { var source = @" var a = new A(42); System.Console.Write(a.X); System.Console.Write("" - ""); a.Deconstruct(out int x); System.Console.Write(x); record struct A(int X) { public int X = X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "struct").WithArguments("record structs", "10.0").WithLocation(8, 8), // (8,17): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record struct A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(8, 17) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42"); verifier.VerifyIL("A.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_Readonly() { var source = @" readonly record struct A(int X) { public int X = X; // 1 } readonly record struct B(int X) { public readonly int X = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS8340: Instance fields of readonly structs must be readonly. // public int X = X; // 1 Diagnostic(ErrorCode.ERR_FieldsInRoStruct, "X").WithLocation(4, 16) ); } [Fact] public void FieldAsPositionalMember_Fixed() { var src = @" unsafe record struct C(int[] P) { public fixed int P[2]; public int[] X = P; }"; var comp = CreateCompilation(src, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (2,30): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int[]' to match positional parameter 'P'. // unsafe record struct C(int[] P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int[]", "P").WithLocation(2, 30), // (4,22): error CS8908: The type 'int*' may not be used for a field of a record. // public fixed int P[2]; Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P").WithArguments("int*").WithLocation(4, 22) ); } [Fact] public void FieldAsPositionalMember_WrongType() { var source = @" record struct A(int X) { public string X = null; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,21): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record struct A(int X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 21) ); } [Fact] public void FieldAsPositionalMember_DuplicateFields() { var source = @" record struct A(int X) { public int X = 0; public int X = 0; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,16): error CS0102: The type 'A' already contains a definition for 'X' // public int X = 0; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("A", "X").WithLocation(5, 16) ); } [Fact] public void SyntaxFactory_TypeDeclaration() { var expected = @"record struct Point { }"; AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, SyntaxFactory.TypeDeclaration(SyntaxKind.RecordStructDeclaration, "Point").NormalizeWhitespace().ToString()); } [Fact] public void InterfaceWithParameters() { var src = @" public interface I { } record struct R(int X) : I() { } record struct R2(int X) : I(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,27): error CS8861: Unexpected argument list. // record struct R(int X) : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 27), // (10,28): error CS8861: Unexpected argument list. // record struct R2(int X) : I(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 28) ); } [Fact] public void InterfaceWithParameters_NoPrimaryConstructor() { var src = @" public interface I { } record struct R : I() { } record struct R2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,20): error CS8861: Unexpected argument list. // record struct R : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 20), // (10,21): error CS8861: Unexpected argument list. // record struct R2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 21) ); } [Fact] public void InterfaceWithParameters_Struct() { var src = @" public interface I { } struct C : I() { } struct C2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,13): error CS8861: Unexpected argument list. // struct C : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 13), // (10,14): error CS8861: Unexpected argument list. // struct C2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 14) ); } [Fact] public void BaseArguments_Speculation() { var src = @" record struct R1(int X) : Error1(0, 1) { } record struct R2(int X) : Error2() { } record struct R3(int X) : Error3 { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,27): error CS0246: The type or namespace name 'Error1' could not be found (are you missing a using directive or an assembly reference?) // record struct R1(int X) : Error1(0, 1) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error1").WithArguments("Error1").WithLocation(2, 27), // (2,33): error CS8861: Unexpected argument list. // record struct R1(int X) : Error1(0, 1) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0, 1)").WithLocation(2, 33), // (5,27): error CS0246: The type or namespace name 'Error2' could not be found (are you missing a using directive or an assembly reference?) // record struct R2(int X) : Error2() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error2").WithArguments("Error2").WithLocation(5, 27), // (5,33): error CS8861: Unexpected argument list. // record struct R2(int X) : Error2() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(5, 33), // (8,27): error CS0246: The type or namespace name 'Error3' could not be found (are you missing a using directive or an assembly reference?) // record struct R3(int X) : Error3 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error3").WithArguments("Error3").WithLocation(8, 27) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().First(); Assert.Equal("Error1(0, 1)", baseWithargs.ToString()); var speculativeBase = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1))); Assert.Equal("Error1(0)", speculativeBase.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBase, out _)); var baseWithoutargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Skip(1).First(); Assert.Equal("Error2()", baseWithoutargs.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithoutargs.ArgumentList.OpenParenToken.SpanStart, speculativeBase, out _)); var baseWithoutParens = tree.GetRoot().DescendantNodes().OfType<SimpleBaseTypeSyntax>().Single(); Assert.Equal("Error3", baseWithoutParens.ToString()); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithoutParens.SpanStart + 2, speculativeBase, out _)); } [Fact, WorkItem(54413, "https://github.com/dotnet/roslyn/issues/54413")] public void ValueTypeCopyConstructorLike_NoThisInitializer() { var src = @" record struct Value(string Text) { private Value(int X) { } // 1 private Value(Value original) { } // 2 } record class Boxed(string Text) { private Boxed(int X) { } // 3 private Boxed(Boxed original) { } // 4 } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,13): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // private Value(int X) { } // 1 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "Value").WithLocation(4, 13), // (5,13): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // private Value(Value original) { } // 2 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "Value").WithLocation(5, 13), // (10,13): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // private Boxed(int X) { } // 3 Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "Boxed").WithLocation(10, 13), // (11,13): error CS8878: A copy constructor 'Boxed.Boxed(Boxed)' must be public or protected because the record is not sealed. // private Boxed(Boxed original) { } // 4 Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "Boxed").WithArguments("Boxed.Boxed(Boxed)").WithLocation(11, 13) ); } [Fact] public void ValueTypeCopyConstructorLike() { var src = @" System.Console.Write(new Value(new Value(0))); record struct Value(int I) { public Value(Value original) : this(42) { } } "; var comp = CreateCompilation(src); CompileAndVerify(comp, expectedOutput: "Value { I = 42 }"); } } }
1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/CSharp/Test/Semantic/Semantics/RecordTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class RecordTests : CompilingTestBase { private static CSharpCompilation CreateCompilation(CSharpTestSource source) => CSharpTestBase.CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); private CompilationVerifier CompileAndVerify( CSharpTestSource src, string? expectedOutput = null, IEnumerable<MetadataReference>? references = null) => base.CompileAndVerify( new[] { src, IsExternalInitTypeDefinition }, expectedOutput: expectedOutput, parseOptions: TestOptions.RegularPreview, references: references, // init-only is unverifiable verify: Verification.Skipped); [Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")] public void RecordLanguageVersion() { var src1 = @" class Point(int x, int y); "; var src2 = @" record Point { } "; var src3 = @" record Point(int x, int y); "; var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,12): error CS8805: Program using top-level statements must be an executable. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 12), // (2,12): error CS8803: Top-level statements must precede namespace and type declarations. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // class Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 12), // (2,13): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 13), // (2,13): error CS0165: Use of unassigned local variable 'x' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 13), // (2,20): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 20), // (2,20): error CS0165: Use of unassigned local variable 'y' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 20) ); comp = CreateCompilation(src2, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,1): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(2, 1), // (2,8): error CS0116: A namespace cannot directly contain members such as fields or methods // record Point { } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Point").WithLocation(2, 8), // (2,8): error CS0548: '<invalid-global-code>.Point': property or indexer must have at least one accessor // record Point { } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "Point").WithArguments("<invalid-global-code>.Point").WithLocation(2, 8) ); comp = CreateCompilation(src3, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,1): error CS8805: Program using top-level statements must be an executable. // record Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "record Point(int x, int y);").WithLocation(2, 1), // (2,1): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // record Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "record Point(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 1), // (2,1): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point(int x, int y); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(2, 1), // (2,8): error CS8112: Local function 'Point(int, int)' must declare a body because it is not marked 'static extern'. // record Point(int x, int y); Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Point").WithArguments("Point(int, int)").WithLocation(2, 8), // (2,8): warning CS8321: The local function 'Point' is declared but never used // record Point(int x, int y); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Point").WithArguments("Point").WithLocation(2, 8) ); comp = CreateCompilation(src1, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,12): error CS8805: Program using top-level statements must be an executable. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS8803: Top-level statements must precede namespace and type declarations. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // class Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 12), // (2,13): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 13), // (2,13): error CS0165: Use of unassigned local variable 'x' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 13), // (2,20): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 20), // (2,20): error CS0165: Use of unassigned local variable 'y' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 20) ); comp = CreateCompilation(src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src3); comp.VerifyDiagnostics(); var point = comp.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsReferenceType); Assert.False(point.IsValueType); Assert.Equal(TypeKind.Class, point.TypeKind); Assert.Equal(SpecialType.System_Object, point.BaseTypeNoUseSiteDiagnostics.SpecialType); } [Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")] public void RecordLanguageVersion_Nested() { var src1 = @" class C { class Point(int x, int y); } "; var src2 = @" class D { record Point { } } "; var src3 = @" class E { record Point(int x, int y); } "; var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,16): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 16), // (4,16): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 16), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30) ); comp = CreateCompilation(src2, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(4, 5), // (4,12): error CS0548: 'D.Point': property or indexer must have at least one accessor // record Point { } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "Point").WithArguments("D.Point").WithLocation(4, 12) ); comp = CreateCompilation(src3, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point(int x, int y); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(4, 5), // (4,12): error CS0501: 'E.Point(int, int)' must declare a body because it is not marked abstract, extern, or partial // record Point(int x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "Point").WithArguments("E.Point(int, int)").WithLocation(4, 12) ); comp = CreateCompilation(src1); comp.VerifyDiagnostics( // (4,16): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 16), // (4,16): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 16), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30) ); comp = CreateCompilation(src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src3); comp.VerifyDiagnostics(); } [Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")] public void RecordClassLanguageVersion() { var src = @" record class Point(int x, int y); "; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,1): error CS0116: A namespace cannot directly contain members such as fields or methods // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "record").WithLocation(2, 1), // (2,19): error CS1514: { expected // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 19), // (2,19): error CS1513: } expected // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 19), // (2,19): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 19), // (2,19): error CS8803: Top-level statements must precede namespace and type declarations. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 19), // (2,19): error CS8805: Program using top-level statements must be an executable. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 19), // (2,19): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 19), // (2,20): error CS8185: A declaration is not allowed in this context. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 20), // (2,20): error CS0165: Use of unassigned local variable 'x' // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 20), // (2,27): error CS8185: A declaration is not allowed in this context. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 27), // (2,27): error CS0165: Use of unassigned local variable 'y' // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 27) ); comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "class").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [CombinatorialData] [Theory, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")] public void GetSimpleNonTypeMembers(bool useCompilationReference) { var lib_src = @" public record RecordA(RecordB B); public record RecordB(int C); "; var lib_comp = CreateCompilation(lib_src); var src = @" class C { void M(RecordA a, RecordB b) { _ = a.B == b; } } "; var comp = CreateCompilation(src, references: new[] { AsReference(lib_comp, useCompilationReference) }); comp.VerifyEmitDiagnostics(); } [Fact, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")] public void GetSimpleNonTypeMembers_SingleCompilation() { var src = @" public record RecordA(RecordB B); public record RecordB(int C); class C { void M(RecordA a, RecordB b) { _ = a.B == b; } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); Assert.Equal("System.Boolean RecordB.op_Equality(RecordB? left, RecordB? right)", model.GetSymbolInfo(node).Symbol.ToTestDisplayString()); } [Fact, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")] public void GetSimpleNonTypeMembers_DirectApiCheck() { var src = @" public record RecordB(); "; var comp = CreateCompilation(src); var b = comp.GlobalNamespace.GetTypeMember("RecordB"); AssertEx.SetEqual(new[] { "System.Boolean RecordB.op_Equality(RecordB? left, RecordB? right)" }, b.GetSimpleNonTypeMembers("op_Equality").ToTestDisplayStrings()); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor() { var src = @" record R(R x); #nullable enable record R2(R2? x) { } record R3([System.Diagnostics.CodeAnalysis.NotNull] R3 x); "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyEmitDiagnostics( // (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R(R x); Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8), // (5,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R2(R2? x) { } Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R2").WithLocation(5, 8), // (7,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R3([System.Diagnostics.CodeAnalysis.NotNull] R3 x); Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R3").WithLocation(7, 8) ); var r = comp.GlobalNamespace.GetTypeMember("R"); Assert.Equal(new[] { "R..ctor(R x)", "R..ctor(R original)" }, r.GetMembers(".ctor").ToTestDisplayStrings()); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_Generic() { var src = @" record R<T>(R<T> x); #nullable enable record R2<T>(R2<T?> x) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R<T>(R<T> x); Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8), // (5,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R2<T>(R2<T?> x) { } Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R2").WithLocation(5, 8) ); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_WithExplicitCopyCtor() { var src = @" record R(R x) { public R(R x) => throw null; } "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyEmitDiagnostics( // (4,12): error CS0111: Type 'R' already defines a member called 'R' with the same parameter types // public R(R x) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R").WithArguments("R", "R").WithLocation(4, 12) ); var r = comp.GlobalNamespace.GetTypeMember("R"); Assert.Equal(new[] { "R..ctor(R x)", "R..ctor(R x)" }, r.GetMembers(".ctor").ToTestDisplayStrings()); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_WithBase() { var src = @" record Base; record R(R x) : Base; // 1 record Derived(Derived y) : R(y) // 2 { public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 } record Derived2(Derived2 y) : R(y); // 6, 7, 8 record R2(R2 x) : Base { public R2(R2 x) => throw null; // 9, 10 } record R3(R3 x) : Base { public R3(R3 x) : base(x) => throw null; // 11 } "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyEmitDiagnostics( // (4,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R(R x) : Base; // 1 Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(4, 8), // (6,30): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)' // record Derived(Derived y) : R(y) // 2 Diagnostic(ErrorCode.ERR_AmbigCall, "(y)").WithArguments("R.R(R)", "R.R(R)").WithLocation(6, 30), // (8,12): error CS0111: Type 'Derived' already defines a member called 'Derived' with the same parameter types // public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Derived").WithArguments("Derived", "Derived").WithLocation(8, 12), // (8,33): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)' // public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 Diagnostic(ErrorCode.ERR_AmbigCall, "base").WithArguments("R.R(R)", "R.R(R)").WithLocation(8, 33), // (8,33): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(8, 33), // (11,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record Derived2(Derived2 y) : R(y); // 6, 7, 8 Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "Derived2").WithLocation(11, 8), // (11,8): error CS8867: No accessible copy constructor found in base type 'R'. // record Derived2(Derived2 y) : R(y); // 6, 7, 8 Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "Derived2").WithArguments("R").WithLocation(11, 8), // (11,32): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)' // record Derived2(Derived2 y) : R(y); // 6, 7, 8 Diagnostic(ErrorCode.ERR_AmbigCall, "(y)").WithArguments("R.R(R)", "R.R(R)").WithLocation(11, 32), // (15,12): error CS0111: Type 'R2' already defines a member called 'R2' with the same parameter types // public R2(R2 x) => throw null; // 9, 10 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R2").WithArguments("R2", "R2").WithLocation(15, 12), // (15,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public R2(R2 x) => throw null; // 9, 10 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "R2").WithLocation(15, 12), // (20,12): error CS0111: Type 'R3' already defines a member called 'R3' with the same parameter types // public R3(R3 x) : base(x) => throw null; // 11 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R3").WithArguments("R3", "R3").WithLocation(20, 12) ); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_WithPropertyInitializer() { var src = @" record R(R X) { public R X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R(R X) Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var parameterSyntax = tree.GetRoot().DescendantNodes().OfType<ParameterSyntax>().Single(); var parameter = model.GetDeclaredSymbol(parameterSyntax)!; Assert.Equal("R X", parameter.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, parameter.Kind); Assert.Equal("R..ctor(R X)", parameter.ContainingSymbol.ToTestDisplayString()); var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); var initializer = model.GetSymbolInfo(initializerSyntax.Value).Symbol!; Assert.Equal("R X", initializer.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, initializer.Kind); Assert.Equal("R..ctor(R X)", initializer.ContainingSymbol.ToTestDisplayString()); } [Fact] public void GetDeclaredSymbolOnAnOutLocalInPropertyInitializer() { var src = @" record R(int I) { public int I { get; init; } = M(out int i) ? i : 0; static bool M(out int i) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,14): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // record R(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 14) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var outVarSyntax = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Single(); var outVar = model.GetDeclaredSymbol(outVarSyntax)!; Assert.Equal("System.Int32 i", outVar.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, outVar.Kind); Assert.Equal("System.Int32 R.<I>k__BackingField", outVar.ContainingSymbol.ToTestDisplayString()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord() { string source = @" public record A(int i,) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,23): error CS1031: Type expected // public record A(int i,) { } Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(2, 23), // (2,23): error CS1001: Identifier expected // public record A(int i,) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 23) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A.i { get; init; }", "? A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); AssertEx.Equal(new[] { "A..ctor(System.Int32 i, ?)", "A..ctor(A original)" }, comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings()); var primaryCtor = comp.GetMember<NamedTypeSymbol>("A").Constructors.First(); Assert.Equal("A..ctor(System.Int32 i, ?)", primaryCtor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTrivia() { string source = @" public record A(int i, // A // B , /* C */ ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,23): error CS1031: Type expected // public record A(int i, // A Diagnostic(ErrorCode.ERR_TypeExpected, "").WithLocation(2, 23), // (2,23): error CS1001: Identifier expected // public record A(int i, // A Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(2, 23), // (4,15): error CS1031: Type expected // , /* C */ ) { } Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(4, 15), // (4,15): error CS1001: Identifier expected // , /* C */ ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 15), // (4,15): error CS0102: The type 'A' already contains a definition for '' // , /* C */ ) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(4, 15) ); var primaryCtor = comp.GetMember<NamedTypeSymbol>("A").Constructors.First(); Assert.Equal("A..ctor(System.Int32 i, ?, ?)", primaryCtor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[0].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[2].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompleteConstructor() { string source = @" public class C { C(int i, ) { } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,14): error CS1031: Type expected // C(int i, ) { } Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(4, 14), // (4,14): error CS1001: Identifier expected // C(int i, ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 14) ); var ctor = comp.GetMember<NamedTypeSymbol>("C").Constructors.Single(); Assert.Equal("C..ctor(System.Int32 i, ?)", ctor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(0, ctor.Parameters[1].Locations.Single().SourceSpan.Length); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithType() { string source = @" public record A(int i, int ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,28): error CS1001: Identifier expected // public record A(int i, int ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 28) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A.i { get; init; }", "System.Int32 A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var ctor = comp.GetMember<NamedTypeSymbol>("A").Constructors[0]; Assert.Equal("A..ctor(System.Int32 i, System.Int32)", ctor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(0, ctor.Parameters[1].Locations.Single().SourceSpan.Length); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTwoTypes() { string source = @" public record A(int, string ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,20): error CS1001: Identifier expected // public record A(int, string ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(2, 20), // (2,29): error CS1001: Identifier expected // public record A(int, string ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 29), // (2,29): error CS0102: The type 'A' already contains a definition for '' // public record A(int, string ) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(2, 29) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A. { get; init; }", "System.String A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); AssertEx.Equal(new[] { "A..ctor(System.Int32, System.String)", "A..ctor(A original)" }, comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings()); Assert.IsType<ParameterSyntax>(comp.GetMember<NamedTypeSymbol>("A").Constructors[0].Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTwoTypes_SameType() { string source = @" public record A(int, int ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,20): error CS1001: Identifier expected // public record A(int, int ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(2, 20), // (2,26): error CS1001: Identifier expected // public record A(int, int ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 26), // (2,26): error CS0102: The type 'A' already contains a definition for '' // public record A(int, int ) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(2, 26) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A. { get; init; }", "System.Int32 A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); AssertEx.Equal(new[] { "A..ctor(System.Int32, System.Int32)", "A..ctor(A original)" }, comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings()); Assert.IsType<ParameterSyntax>(comp.GetMember<NamedTypeSymbol>("A").Constructors[0].Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTwoTypes_WithTrivia() { string source = @" public record A(int // A // B , int /* C */) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,20): error CS1001: Identifier expected // public record A(int // A Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(2, 20), // (4,18): error CS1001: Identifier expected // , int /* C */) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 18), // (4,18): error CS0102: The type 'A' already contains a definition for '' // , int /* C */) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(4, 18) ); var ctor = comp.GetMember<NamedTypeSymbol>("A").Constructors[0]; Assert.IsType<ParameterSyntax>(ctor.Parameters[0].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46083, "https://github.com/dotnet/roslyn/issues/46083")] public void IncompletePositionalRecord_SingleParameter() { string source = @" record A(x) "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,10): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?) // record A(x) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(2, 10), // (2,11): error CS1001: Identifier expected // record A(x) Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 11), // (2,12): error CS1514: { expected // record A(x) Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(2, 12), // (2,12): error CS1513: } expected // record A(x) Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(2, 12) ); } [Fact] public void TestWithInExpressionTree() { var source = @" using System; using System.Linq.Expressions; public record C(int i) { public static void M() { Expression<Func<C, C>> expr = c => c with { i = 5 }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,44): error CS8849: An expression tree may not contain a with-expression. // Expression<Func<C, C>> expr = c => c with { i = 5 }; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsWithExpression, "c with { i = 5 }").WithLocation(8, 44) ); } [Fact] public void PartialRecord_MixedWithClass() { var src = @" partial record C(int X, int Y) { } partial class C { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,15): error CS0261: Partial declarations of 'C' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class C Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C").WithArguments("C").WithLocation(5, 15) ); } [Fact] public void PartialRecord_ParametersInScopeOfBothParts() { var src = @" var c = new C(2); System.Console.Write((c.P1, c.P2)); public partial record C(int X) { public int P1 { get; set; } = X; } public partial record C { public int P2 { get; set; } = X; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */).VerifyDiagnostics(); } [Fact] public void PartialRecord_ParametersInScopeOfBothParts_RecordClass() { var src = @" var c = new C(2); System.Console.Write((c.P1, c.P2)); public partial record C(int X) { public int P1 { get; set; } = X; } public partial record class C { public int P2 { get; set; } = X; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */).VerifyDiagnostics(); } [Fact] public void PartialRecord_DuplicateMemberNames() { var src = @" public partial record C(int X) { public void M(int i) { } } public partial record C { public void M(string s) { } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }); var expectedMemberNames = new string[] { ".ctor", "get_EqualityContract", "EqualityContract", "<X>k__BackingField", "get_X", "set_X", "X", "M", "M", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordInsideGenericType() { var src = @" var c = new C<int>.Nested(2); System.Console.Write(c.T); public class C<T> { public record Nested(T T); } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2", verify: Verification.Skipped /* init-only */); } [Fact] public void RecordProperties_01() { var src = @" using System; record C(int X, int Y) { int Z = 123; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); Console.WriteLine(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2 123").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.s 123 IL_0011: stfld ""int C.Z"" IL_0016: ldarg.0 IL_0017: call ""object..ctor()"" IL_001c: ret } "); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); var x = (IPropertySymbol)c.GetMember("X"); Assert.Equal("System.Int32 C.X.get", x.GetMethod.ToTestDisplayString()); Assert.Equal("void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init", x.SetMethod.ToTestDisplayString()); Assert.True(x.SetMethod!.IsInitOnly); var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField"); Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString()); Assert.True(xBackingField.IsReadOnly); } [Fact] public void RecordProperties_02() { var src = @" using System; record C(int X, int Y) { public C(int a, int b) { } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } private int X1 = X; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types // public C(int a, int b) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(5, 12), // (5,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public C(int a, int b) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(5, 12), // (11,21): error CS0121: The call is ambiguous between the following methods or properties: 'C.C(int, int)' and 'C.C(int, int)' // var c = new C(1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "C").WithArguments("C.C(int, int)", "C.C(int, int)").WithLocation(11, 21) ); } [Fact] public void RecordProperties_03() { var src = @" using System; record C(int X, int Y) { public int X { get; } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } }"; CompileAndVerify(src, expectedOutput: @" 0 2").VerifyDiagnostics( // (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14) ); } [Fact] public void RecordProperties_04() { var src = @" using System; record C(int X, int Y) { public int X { get; } = 3; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } }"; CompileAndVerify(src, expectedOutput: @" 3 2").VerifyDiagnostics( // (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14) ); } [Fact, WorkItem(48947, "https://github.com/dotnet/roslyn/issues/48947")] public void RecordProperties_05() { var src = @" record C(int X, int X) { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,21): error CS0100: The parameter name 'X' is a duplicate // record C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 21), // (2,21): error CS0102: The type 'C' already contains a definition for 'X' // record C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 21) ); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; init; }", "System.Int32 C.X { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var expectedMemberNames = new[] { ".ctor", "get_EqualityContract", "EqualityContract", "<X>k__BackingField", "get_X", "set_X", "X", "<X>k__BackingField", "get_X", "set_X", "X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordProperties_05_RecordClass() { var src = @" record class C(int X, int X) { }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (2,27): error CS0100: The parameter name 'X' is a duplicate // record class C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 27), // (2,27): error CS0102: The type 'C' already contains a definition for 'X' // record class C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 27) ); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; init; }", "System.Int32 C.X { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var expectedMemberNames = new[] { ".ctor", "get_EqualityContract", "EqualityContract", "<X>k__BackingField", "get_X", "set_X", "X", "<X>k__BackingField", "get_X", "set_X", "X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordProperties_06() { var src = @" record C(int X, int Y) { public void get_X() { } public void set_X() { } int get_Y(int value) => value; int set_Y(int value) => value; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,14): error CS0082: Type 'C' already reserves a member called 'get_X' with the same parameter types // record C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "X").WithArguments("get_X", "C").WithLocation(2, 14), // (2,21): error CS0082: Type 'C' already reserves a member called 'set_Y' with the same parameter types // record C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "Y").WithArguments("set_Y", "C").WithLocation(2, 21)); var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.Int32 C.<X>k__BackingField", "System.Int32 C.X.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init", "System.Int32 C.X { get; init; }", "System.Int32 C.<Y>k__BackingField", "System.Int32 C.Y.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.Y.init", "System.Int32 C.Y { get; init; }", "void C.get_X()", "void C.set_X()", "System.Int32 C.get_Y(System.Int32 value)", "System.Int32 C.set_Y(System.Int32 value)", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void RecordProperties_07() { var comp = CreateCompilation(@" record C1(object P, object get_P); record C2(object get_P, object P);"); comp.VerifyDiagnostics( // (2,18): error CS0102: The type 'C1' already contains a definition for 'get_P' // record C1(object P, object get_P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C1", "get_P").WithLocation(2, 18), // (3,32): error CS0102: The type 'C2' already contains a definition for 'get_P' // record C2(object get_P, object P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C2", "get_P").WithLocation(3, 32) ); } [Fact] public void RecordProperties_08() { var comp = CreateCompilation(@" record C1(object O1) { public object O1 { get; } = O1; public object O2 { get; } = O1; }"); comp.VerifyDiagnostics(); } [Fact] public void RecordProperties_09() { var src = @"record C(object P1, object P2, object P3, object P4) { class P1 { } object P2 = 2; int P3(object o) => 3; int P4<T>(T t) => 4; }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,17): error CS0102: The type 'C' already contains a definition for 'P1' // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(1, 17), // (1,21): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object P2").WithArguments("positional fields in records", "10.0").WithLocation(1, 21), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (5,9): error CS0102: The type 'C' already contains a definition for 'P3' // int P3(object o) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(5, 9), // (6,9): error CS0102: The type 'C' already contains a definition for 'P4' // int P4<T>(T t) => 4; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(6, 9) ); comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (1,17): error CS0102: The type 'C' already contains a definition for 'P1' // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(1, 17), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (5,9): error CS0102: The type 'C' already contains a definition for 'P3' // int P3(object o) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(5, 9), // (6,9): error CS0102: The type 'C' already contains a definition for 'P4' // int P4<T>(T t) => 4; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(6, 9) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes() { var src = @" class C<T> { } static class C2 { } ref struct RefLike{} unsafe record C( // 1 int* P1, // 2 int*[] P2, // 3 C<int*[]> P3, delegate*<int, int> P4, // 4 void P5, // 5 C2 P6, // 6, 7 System.ArgIterator P7, // 8 System.TypedReference P8, // 9 RefLike P9); // 10 "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (6,15): error CS0721: 'C2': static types cannot be used as parameters // unsafe record C( // 1 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C").WithArguments("C2").WithLocation(6, 15), // (7,10): error CS8908: The type 'int*' may not be used for a field of a record. // int* P1, // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P1").WithArguments("int*").WithLocation(7, 10), // (8,12): error CS8908: The type 'int*[]' may not be used for a field of a record. // int*[] P2, // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P2").WithArguments("int*[]").WithLocation(8, 12), // (10,25): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // delegate*<int, int> P4, // 4 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P4").WithArguments("delegate*<int, int>").WithLocation(10, 25), // (11,5): error CS1536: Invalid parameter type 'void' // void P5, // 5 Diagnostic(ErrorCode.ERR_NoVoidParameter, "void").WithLocation(11, 5), // (12,8): error CS0722: 'C2': static types cannot be used as return types // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (12,8): error CS0721: 'C2': static types cannot be used as parameters // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (13,5): error CS0610: Field or property cannot be of type 'ArgIterator' // System.ArgIterator P7, // 8 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 5), // (14,5): error CS0610: Field or property cannot be of type 'TypedReference' // System.TypedReference P8, // 9 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 5), // (15,5): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // RefLike P9); // 10 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 5) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public int* f1; // 1 public int*[] f2; // 2 public C<int*[]> f3; public delegate*<int, int> f4; // 3 public void f5; // 4 public C2 f6; // 5 public System.ArgIterator f7; // 6 public System.TypedReference f8; // 7 public RefLike f9; // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1; // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2; // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4; // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,12): error CS0670: Field cannot have void type // public void f5; // 4 Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void").WithLocation(12, 12), // (13,15): error CS0723: Cannot declare a variable of static type 'C2' // public C2 f6; // 5 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(13, 15), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7; // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8; // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9; // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers_AutoProperties() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public int* f1 { get; set; } // 1 public int*[] f2 { get; set; } // 2 public C<int*[]> f3 { get; set; } public delegate*<int, int> f4 { get; set; } // 3 public void f5 { get; set; } // 4 public C2 f6 { get; set; } // 5, 6 public System.ArgIterator f7 { get; set; } // 6 public System.TypedReference f8 { get; set; } // 7 public RefLike f9 { get; set; } // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1 { get; set; } // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2 { get; set; } // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4 { get; set; } // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,17): error CS0547: 'C.f5': property or indexer cannot have void type // public void f5 { get; set; } // 4 Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "f5").WithArguments("C.f5").WithLocation(12, 17), // (13,20): error CS0722: 'C2': static types cannot be used as return types // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("C2").WithLocation(13, 20), // (13,25): error CS0721: 'C2': static types cannot be used as parameters // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("C2").WithLocation(13, 25), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7 { get; set; } // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8 { get; set; } // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9 { get; set; } // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [Fact] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_PointerTypeAllowedForParameterAndProperty() { var src = @" class C<T> { } unsafe record C(int* P1, int*[] P2, C<int*[]> P3) { int* P1 { get { System.Console.Write(""P1 ""); return null; } init { } } int*[] P2 { get { System.Console.Write(""P2 ""); return null; } init { } } C<int*[]> P3 { get { System.Console.Write(""P3 ""); return null; } init { } } public unsafe static void Main() { var x = new C(null, null, null); var (x1, x2, x3) = x; System.Console.Write(""RAN""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugExe); comp.VerifyEmitDiagnostics( // (4,22): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // unsafe record C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(4, 22), // (4,33): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // unsafe record C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(4, 33), // (4,47): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // unsafe record C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(4, 47) ); CompileAndVerify(comp, expectedOutput: "P1 P2 P3 RAN", verify: Verification.Skipped /* pointers */); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_StaticFields() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public static int* f1; public static int*[] f2; public static C<int*[]> f3; public static delegate*<int, int> f4; public static C2 f6; // 1 public static System.ArgIterator f7; // 2 public static System.TypedReference f8; // 3 public static RefLike f9; // 4 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (12,22): error CS0723: Cannot declare a variable of static type 'C2' // public static C2 f6; // 1 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(12, 22), // (13,19): error CS0610: Field or property cannot be of type 'ArgIterator' // public static System.ArgIterator f7; // 2 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 19), // (14,19): error CS0610: Field or property cannot be of type 'TypedReference' // public static System.TypedReference f8; // 3 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 19), // (15,19): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public static RefLike f9; // 4 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 19) ); } [Fact, WorkItem(48584, "https://github.com/dotnet/roslyn/issues/48584")] public void RecordProperties_11_UnreadPositionalParameter() { var comp = CreateCompilation(@" record C1(object O1, object O2, object O3) // 1, 2 { public object O1 { get; init; } public object O2 { get; init; } = M(O2); public object O3 { get; init; } = M(O3 = null); private static object M(object o) => o; } record Base(object O); record C2(object O4) : Base(O4) // we didn't complain because the parameter is read { public object O4 { get; init; } } record C3(object O5) : Base((System.Func<object, object>)(x => x)) // 3 { public object O5 { get; init; } } record C4(object O6) : Base((System.Func<object, object>)(_ => O6)) { public object O6 { get; init; } } record C5(object O7) : Base((System.Func<object, object>)(_ => (O7 = 42) )) // 4 { public object O7 { get; init; } } "); comp.VerifyDiagnostics( // (2,18): warning CS8907: Parameter 'O1' is unread. Did you forget to use it to initialize the property with that name? // record C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O1").WithArguments("O1").WithLocation(2, 18), // (2,40): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 40), // (16,18): warning CS8907: Parameter 'O5' is unread. Did you forget to use it to initialize the property with that name? // record C3(object O5) : Base((System.Func<object, object>)(x => x)) // 3 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O5").WithArguments("O5").WithLocation(16, 18), // (26,18): warning CS8907: Parameter 'O7' is unread. Did you forget to use it to initialize the property with that name? // record C5(object O7) : Base((System.Func<object, object>)(_ => (O7 = 42) )) // 4 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O7").WithArguments("O7").WithLocation(26, 18) ); } [Fact, WorkItem(48584, "https://github.com/dotnet/roslyn/issues/48584")] public void RecordProperties_11_UnreadPositionalParameter_InRefOut() { var comp = CreateCompilation(@" record C1(object O1, object O2, object O3) // 1 { public object O1 { get; init; } = MIn(in O1); public object O2 { get; init; } = MRef(ref O2); public object O3 { get; init; } = MOut(out O3); static object MIn(in object o) => o; static object MRef(ref object o) => o; static object MOut(out object o) => throw null; } "); comp.VerifyDiagnostics( // (2,40): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record C1(object O1, object O2, object O3) // 1 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 40) ); } [Fact] public void EmptyRecord_01() { var src = @" record C(); class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); var comp = (CSharpCompilation)verifier.Compilation; var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor()", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void EmptyRecord_01_RecordClass() { var src = @" record class C(); class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True", parseOptions: TestOptions.Regular10); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); var comp = (CSharpCompilation)verifier.Compilation; var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor()", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void EmptyRecord_02() { var src = @" record C() { C(int x) {} } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,5): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // C(int x) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C", isSuppressed: false).WithLocation(4, 5) ); } [Fact] public void EmptyRecord_03() { var src = @" record B { public B(int x) { System.Console.WriteLine(x); } } record C() : B(12) { C(int x) : this() {} } class Program { static void Main() { _ = new C(); } } "; var verifier = CompileAndVerify(src, expectedOutput: "12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 12 IL_0003: call ""B..ctor(int)"" IL_0008: ret } "); } [Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")] public void StaticCtor() { var src = @" record R(int x) { static void Main() { } static R() { System.Console.Write(""static ctor""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); // [ : R::set_x] Cannot change initonly field outside its .ctor. CompileAndVerify(comp, expectedOutput: "static ctor", verify: Verification.Skipped); } [Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")] public void StaticCtor_ParameterlessPrimaryCtor() { var src = @" record R() { static R() { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")] public void StaticCtor_CopyCtor() { var src = @" record R() { static R(R r) { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,12): error CS0132: 'R.R(R)': a static constructor must be parameterless // static R(R r) { } Diagnostic(ErrorCode.ERR_StaticConstParam, "R").WithArguments("R.R(R)").WithLocation(4, 12) ); } [Fact] public void WithExpr1() { var src = @" record C(int X) { public static void Main() { var c = new C(0); _ = Main() with { }; _ = default with { }; _ = null with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,13): error CS8802: The receiver of a `with` expression must have a valid non-void type. // _ = Main() with { }; Diagnostic(ErrorCode.ERR_InvalidWithReceiverType, "Main()").WithLocation(7, 13), // (8,13): error CS8716: There is no target type for the default literal. // _ = default with { }; Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(8, 13), // (9,13): error CS8802: The receiver of a `with` expression must have a valid non-void type. // _ = null with { }; Diagnostic(ErrorCode.ERR_InvalidWithReceiverType, "null").WithLocation(9, 13) ); } [Fact] public void WithExpr2() { var src = @" using System; record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; Console.WriteLine(c1.X); Console.WriteLine(c2.X); } }"; CompileAndVerify(src, expectedOutput: @"1 11").VerifyDiagnostics(); } [Fact] public void WithExpr3() { var src = @" record C(int X) { public static void Main() { var c = new C(0); c = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var root = comp.SyntaxTrees[0].GetRoot(); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0)') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0)') Right: IObjectCreationOperation (Constructor: C..ctor(System.Int32 X)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') 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) Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with { };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with { }') Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Right: IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { }') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr4() { var src = @" class B { public B Clone() => null; } record C(int X) : B { public static void Main() { var c = new C(0); c = c with { }; } public new C Clone() => null; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr6() { var src = @" record B { public int X { get; init; } } record C : B { public static void Main() { var c = new C(); c = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr7() { var src = @" record B { public int X { get; } } record C : B { public new int X { get; init; } public static void Main() { var c = new C(); B b = c; b = b with { X = 0 }; var b2 = c with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (14,22): error CS0200: Property or indexer 'B.X' cannot be assigned to -- it is read only // b = b with { X = 0 }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "X").WithArguments("B.X").WithLocation(14, 22) ); } [Fact] public void WithExpr8() { var src = @" record B { public int X { get; } } record C : B { public string Y { get; } public static void Main() { var c = new C(); B b = c; b = b with { }; b = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr9() { var src = @" record C(int X) { public string Clone() => null; public static void Main() { var c = new C(0); c = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS8859: Members named 'Clone' are disallowed in records. // public string Clone() => null; Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(4, 19) ); } [Fact] public void WithExpr11() { var src = @" record C(int X) { public static void Main() { var c = new C(0); c = c with { X = """"}; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int' // c = c with { X = ""}; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(8, 26) ); } [Fact] public void WithExpr12() { var src = @" using System; record C(int X) { public static void Main() { var c = new C(0); Console.WriteLine(c.X); c = c with { X = 5 }; Console.WriteLine(c.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 5").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 40 (0x28) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: newobj ""C..ctor(int)"" IL_0006: dup IL_0007: callvirt ""int C.X.get"" IL_000c: call ""void System.Console.WriteLine(int)"" IL_0011: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0016: dup IL_0017: ldc.i4.5 IL_0018: callvirt ""void C.X.init"" IL_001d: callvirt ""int C.X.get"" IL_0022: call ""void System.Console.WriteLine(int)"" IL_0027: ret }"); } [Fact] public void WithExpr13() { var src = @" using System; record C(int X, int Y) { public override string ToString() => X + "" "" + Y; public static void Main() { var c = new C(0, 1); Console.WriteLine(c); c = c with { X = 5 }; Console.WriteLine(c); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 1 5 1").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 31 (0x1f) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""C..ctor(int, int)"" IL_0007: dup IL_0008: call ""void System.Console.WriteLine(object)"" IL_000d: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0012: dup IL_0013: ldc.i4.5 IL_0014: callvirt ""void C.X.init"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ret }"); } [Fact] public void WithExpr14() { var src = @" using System; record C(int X, int Y) { public override string ToString() => X + "" "" + Y; public static void Main() { var c = new C(0, 1); Console.WriteLine(c); c = c with { X = 5 }; Console.WriteLine(c); c = c with { Y = 2 }; Console.WriteLine(c); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 1 5 1 5 2").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 49 (0x31) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""C..ctor(int, int)"" IL_0007: dup IL_0008: call ""void System.Console.WriteLine(object)"" IL_000d: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0012: dup IL_0013: ldc.i4.5 IL_0014: callvirt ""void C.X.init"" IL_0019: dup IL_001a: call ""void System.Console.WriteLine(object)"" IL_001f: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0024: dup IL_0025: ldc.i4.2 IL_0026: callvirt ""void C.Y.init"" IL_002b: call ""void System.Console.WriteLine(object)"" IL_0030: ret }"); } [Fact] public void WithExpr15() { var src = @" record C(int X, int Y) { public static void Main() { var c = new C(0, 0); c = c with { = 5 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,22): error CS1525: Invalid expression term '=' // c = c with { = 5 }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(8, 22) ); } [Fact] public void WithExpr16() { var src = @" record C(int X, int Y) { public static void Main() { var c = new C(0, 0); c = c with { X = }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS1525: Invalid expression term '}' // c = c with { X = }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "}").WithArguments("}").WithLocation(8, 26) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr17() { var src = @" record B { public int X { get; } private B Clone() => null; } record C(int X) : B { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8803: The 'with' expression requires the receiver type 'B' to have a single accessible non-inherited instance method named "Clone". // b = b with { }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr18() { var src = @" class B { public int X { get; } protected B Clone() => null; } record C(int X) : B { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8803: The receiver type 'B' does not have an accessible parameterless instance method named "Clone". // b = b with { }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13) ); } [Fact] public void WithExpr19() { var src = @" class B { public int X { get; } protected B Clone() => null; } record C(int X) { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8803: The 'with' expression requires the receiver type 'B' to have a single accessible non-inherited instance method named "Clone". // b = b with { }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13) ); } [Fact] public void WithExpr20() { var src = @" using System; record C { public event Action X; public static void Main() { var c = new C(); c = c with { X = null }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,25): warning CS0067: The event 'C.X' is never used // public event Action X; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "X").WithArguments("C.X").WithLocation(5, 25) ); } [Fact] public void WithExpr21() { var src = @" record B { public class X { } } class C { public static void Main() { var b = new B(); b = b with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,22): error CS0572: 'X': cannot reference a type through an expression; try 'B.X' instead // b = b with { X = 0 }; Diagnostic(ErrorCode.ERR_BadTypeReference, "X").WithArguments("X", "B.X").WithLocation(11, 22), // (11,22): error CS1913: Member 'X' cannot be initialized. It is not a field or property. // b = b with { X = 0 }; Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "X").WithArguments("X").WithLocation(11, 22) ); } [Fact] public void WithExpr22() { var src = @" record B { public int X = 0; } class C { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr23() { var src = @" class B { public int X = 0; public B Clone() => null; } record C(int X) { public static void Main() { var b = new B(); b = b with { Y = 2 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8858: The receiver type 'B' is not a valid record type. // b = b with { Y = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13), // (12,22): error CS0117: 'B' does not contain a definition for 'Y' // b = b with { Y = 2 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Y").WithArguments("B", "Y").WithLocation(12, 22) ); } [Fact] public void WithExpr24_Dynamic() { var src = @" record C(int X) { public static void Main() { dynamic c = new C(1); var x = c with { X = 2 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,17): error CS8858: The receiver type 'dynamic' is not a valid record type. // var x = c with { X = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("dynamic").WithLocation(7, 17) ); } [Fact, WorkItem(46427, "https://github.com/dotnet/roslyn/issues/46427"), WorkItem(46249, "https://github.com/dotnet/roslyn/issues/46249")] public void WithExpr25_TypeParameterWithRecordConstraint() { var src = @" record R(int X); class C { public static T M<T>(T t) where T : R { return t with { X = 2 }; } static void Main() { System.Console.Write(M(new R(-1)).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: "2").VerifyDiagnostics(); verifier.VerifyIL("C.M<T>(T)", @" { // Code size 29 (0x1d) .maxstack 3 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: callvirt ""R R.<Clone>$()"" IL_000b: unbox.any ""T"" IL_0010: dup IL_0011: box ""T"" IL_0016: ldc.i4.2 IL_0017: callvirt ""void R.X.init"" IL_001c: ret } "); } [Fact, WorkItem(46427, "https://github.com/dotnet/roslyn/issues/46427"), WorkItem(46249, "https://github.com/dotnet/roslyn/issues/46249")] public void WithExpr26_TypeParameterWithRecordAndInterfaceConstraint() { var src = @" record R { public int X { get; set; } } interface I { int Property { get; set; } } record T : R, I { public int Property { get; set; } } class C { public static T M<T>(T t) where T : R, I { return t with { X = 2, Property = 3 }; } static void Main() { System.Console.WriteLine(M(new T()).X); System.Console.WriteLine(M(new T()).Property); } }"; var verifier = CompileAndVerify( new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, verify: Verification.Passes, expectedOutput: @"2 3").VerifyDiagnostics(); verifier.VerifyIL("C.M<T>(T)", @" { // Code size 41 (0x29) .maxstack 3 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: callvirt ""R R.<Clone>$()"" IL_000b: unbox.any ""T"" IL_0010: dup IL_0011: box ""T"" IL_0016: ldc.i4.2 IL_0017: callvirt ""void R.X.set"" IL_001c: dup IL_001d: box ""T"" IL_0022: ldc.i4.3 IL_0023: callvirt ""void I.Property.set"" IL_0028: ret } "); } [Fact] public void WithExpr27_InExceptionFilter() { var src = @" var r = new R(1); try { throw new System.Exception(); } catch (System.Exception) when ((r = r with { X = 2 }).X == 2) { System.Console.Write(""RAN ""); System.Console.Write(r.X); } record R(int X); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN 2", verify: Verification.Skipped /* init-only */); } [Fact] public void WithExpr28_WithAwait() { var src = @" var r = new R(1); r = r with { X = await System.Threading.Tasks.Task.FromResult(42) }; System.Console.Write(r.X); record R(int X); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Last().Left; Assert.Equal("X", x.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal("System.Int32 R.X { get; init; }", symbol.ToTestDisplayString()); } [Fact, WorkItem(46465, "https://github.com/dotnet/roslyn/issues/46465")] public void WithExpr29_DisallowedAsExpressionStatement() { var src = @" record R(int X) { void M() { var r = new R(1); r with { X = 2 }; } } "; // Note: we didn't parse the `with` as a `with` expression, but as a broken local declaration // Tracked by https://github.com/dotnet/roslyn/issues/46465 var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (7,9): error CS0118: 'r' is a variable but is used like a type // r with { X = 2 }; Diagnostic(ErrorCode.ERR_BadSKknown, "r").WithArguments("r", "variable", "type").WithLocation(7, 9), // (7,11): warning CS0168: The variable 'with' is declared but never used // r with { X = 2 }; Diagnostic(ErrorCode.WRN_UnreferencedVar, "with").WithArguments("with").WithLocation(7, 11), // (7,16): error CS1002: ; expected // r with { X = 2 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(7, 16), // (7,18): error CS8852: Init-only property or indexer 'R.X' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // r with { X = 2 }; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "X").WithArguments("R.X").WithLocation(7, 18), // (7,24): error CS1002: ; expected // r with { X = 2 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 24) ); } [Fact] public void WithExpr30_TypeParameterNoConstraint() { var src = @" class C { public static void M<T>(T t) { _ = t with { X = 2 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (6,13): error CS8858: The receiver type 'T' is not a valid record type. // _ = t with { X = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(6, 13), // (6,22): error CS0117: 'T' does not contain a definition for 'X' // _ = t with { X = 2 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(6, 22) ); } [Fact] public void WithExpr31_TypeParameterWithInterfaceConstraint() { var src = @" interface I { int Property { get; set; } } class C { public static void M<T>(T t) where T : I { _ = t with { X = 2, Property = 3 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS8858: The receiver type 'T' is not a valid record type. // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(8, 13), // (8,22): error CS0117: 'T' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(8, 22) ); } [Fact] public void WithExpr32_TypeParameterWithInterfaceConstraint() { var ilSource = @" .class interface public auto ansi abstract I { // Methods .method public hidebysig specialname newslot abstract virtual instance class I '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { } // end of method I::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname newslot abstract virtual instance int32 get_Property () cil managed { } // end of method I::get_Property .method public hidebysig specialname newslot abstract virtual instance void set_Property ( int32 'value' ) cil managed { } // end of method I::set_Property // Properties .property instance int32 Property() { .get instance int32 I::get_Property() .set instance void I::set_Property(int32) } } // end of class I "; var src = @" class C { public static void M<T>(T t) where T : I { _ = t with { X = 2, Property = 3 }; } }"; var comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS8858: The receiver type 'T' is not a valid record type. // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(6, 13), // (6,22): error CS0117: 'T' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(6, 22) ); } [Fact] public void WithExpr33_TypeParameterWithStructureConstraint() { var ilSource = @" .class public sequential ansi sealed beforefieldinit S extends System.ValueType { .pack 0 .size 1 // Methods .method public hidebysig instance valuetype S '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { // Method begins at RVA 0x2150 // Code size 2 (0x2) .maxstack 1 .locals init ( [0] valuetype S ) IL_0000: ldnull IL_0001: throw } // end of method S::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname instance int32 get_Property () cil managed { // Method begins at RVA 0x215e // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method S::get_Property .method public hidebysig specialname instance void set_Property ( int32 'value' ) cil managed { // Method begins at RVA 0x215e // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method S::set_Property // Properties .property instance int32 Property() { .get instance int32 S::get_Property() .set instance void S::set_Property(int32) } } // end of class S "; var src = @" abstract class Base<T> { public abstract void M<U>(U t) where U : T; } class C : Base<S> { public override void M<U>(U t) { _ = t with { X = 2, Property = 3 }; } }"; var comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS8773: Feature 'with on structs' is not available in C# 9.0. Please use language version 10.0 or greater. // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "t with { X = 2, Property = 3 }").WithArguments("with on structs", "10.0").WithLocation(11, 13), // (11,22): error CS0117: 'U' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("U", "X").WithLocation(11, 22), // (11,29): error CS0117: 'U' does not contain a definition for 'Property' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("U", "Property").WithLocation(11, 29) ); comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (11,22): error CS0117: 'U' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("U", "X").WithLocation(11, 22), // (11,29): error CS0117: 'U' does not contain a definition for 'Property' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("U", "Property").WithLocation(11, 29) ); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void BothGetHashCodeAndEqualsAreDefined() { var src = @" public sealed record C { public object Data; public bool Equals(C c) { return false; } public override int GetHashCode() { return 0; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void BothGetHashCodeAndEqualsAreNotDefined() { var src = @" public sealed record C { public object Data; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void GetHashCodeIsDefinedButEqualsIsNot() { var src = @" public sealed record C { public object Data; public override int GetHashCode() { return 0; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void EqualsIsDefinedButGetHashCodeIsNot() { var src = @" public sealed record C { public object Data; public bool Equals(C c) { return false; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public bool Equals(C c) { return false; } Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(5, 17)); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord() { var src = @" class record { } class C { record M(record r) => r; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,7): error CS8860: Types and aliases should not be named 'record'. // class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7), // (6,24): error CS1514: { expected // record M(record r) => r; Diagnostic(ErrorCode.ERR_LbraceExpected, "=>").WithLocation(6, 24), // (6,24): error CS1513: } expected // record M(record r) => r; Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(6, 24), // (6,24): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration // record M(record r) => r; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(6, 24), // (6,28): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // record M(record r) => r; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(6, 28), // (6,28): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // record M(record r) => r; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(6, 28) ); comp = CreateCompilation(src, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Struct() { var src = @" struct record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,8): warning CS8860: Types and aliases should not be named 'record'. // struct record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 8) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Interface() { var src = @" interface record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,11): warning CS8860: Types and aliases should not be named 'record'. // interface record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 11) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Enum() { var src = @" enum record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,6): warning CS8860: Types and aliases should not be named 'record'. // enum record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 6) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Delegate() { var src = @" delegate void record(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): warning CS8860: Types and aliases should not be named 'record'. // delegate void record(); Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Delegate_Escaped() { var src = @" delegate void @record(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Alias() { var src = @" using record = System.Console; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using record = System.Console; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using record = System.Console;").WithLocation(2, 1), // (2,7): warning CS8860: Types and aliases should not be named 'record'. // using record = System.Console; Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Alias_Escaped() { var src = @" using @record = System.Console; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using @record = System.Console; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using @record = System.Console;").WithLocation(2, 1) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TypeParameter() { var src = @" class C<record> { } // 1 class C2 { class Nested<record> { } // 2 } class C3 { void Method<record>() { } // 3 void Method2() { void local<record>() // 4 { local<record>(); } } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,9): warning CS8860: Types and aliases should not be named 'record'. // class C<record> { } // 1 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 9), // (5,18): warning CS8860: Types and aliases should not be named 'record'. // class Nested<record> { } // 2 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(5, 18), // (9,17): warning CS8860: Types and aliases should not be named 'record'. // void Method<record>() { } // 3 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(9, 17), // (13,20): warning CS8860: Types and aliases should not be named 'record'. // void local<record>() // 4 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(13, 20) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TypeParameter_Escaped() { var src = @" class C<@record> { } class C2 { class Nested<@record> { } } class C3 { void Method<@record>() { } void Method2() { void local<@record>() { local<record>(); } } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TypeParameter_Escaped_Partial() { var src = @" partial class C<@record> { } partial class C<record> { } // 1 partial class D<record> { } // 2 partial class D<@record> { } partial class D<record> { } // 3 partial class D<record> { } // 4 partial class E<@record> { } partial class E<@record> { } partial class C2 { partial class Nested<record> { } // 5 partial class Nested<@record> { } } partial class C3 { partial void Method<@record>(); partial void Method<record>() { } // 6 partial void Method2<@record>() { } partial void Method2<record>(); // 7 partial void Method3<record>(); // 8 partial void Method3<@record>() { } partial void Method4<record>() { } // 9 partial void Method4<@record>(); } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,17): warning CS8860: Types and aliases should not be named 'record'. // partial class C<record> { } // 1 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 17), // (5,17): warning CS8860: Types and aliases should not be named 'record'. // partial class D<record> { } // 2 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(5, 17), // (8,17): warning CS8860: Types and aliases should not be named 'record'. // partial class D<record> { } // 3 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(8, 17), // (9,17): warning CS8860: Types and aliases should not be named 'record'. // partial class D<record> { } // 4 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(9, 17), // (16,26): warning CS8860: Types and aliases should not be named 'record'. // partial class Nested<record> { } // 5 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(16, 26), // (22,25): warning CS8860: Types and aliases should not be named 'record'. // partial void Method<record>() { } // 6 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(22, 25), // (25,26): warning CS8860: Types and aliases should not be named 'record'. // partial void Method2<record>(); // 7 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(25, 26), // (27,26): warning CS8860: Types and aliases should not be named 'record'. // partial void Method3<record>(); // 8 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(27, 26), // (30,26): warning CS8860: Types and aliases should not be named 'record'. // partial void Method4<record>() { } // 9 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(30, 26) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Record() { var src = @" record record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,8): warning CS8860: Types and aliases should not be named 'record'. // record record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 8) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TwoParts() { var src = @" partial class record { } partial class record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15), // (3,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Escaped() { var src = @" class @record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_MixedEscapedPartial() { var src = @" partial class @record { } partial class record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_MixedEscapedPartial_ReversedOrder() { var src = @" partial class record { } partial class @record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_BothEscapedPartial() { var src = @" partial class @record { } partial class @record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void TypeNamedRecord_EscapedReturnType() { var src = @" class record { } class C { @record M(record r) { System.Console.Write(""RAN""); return r; } public static void Main() { var c = new C(); _ = c.M(new record()); } }"; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (2,7): warning CS8860: Types and aliases should not be named 'record'. // class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7) ); CompileAndVerify(comp, expectedOutput: "RAN"); } [Fact, WorkItem(45591, "https://github.com/dotnet/roslyn/issues/45591")] public void Clone_DisallowedInSource() { var src = @" record C1(string Clone); // 1 record C2 { string Clone; // 2 } record C3 { string Clone { get; set; } // 3 } record C4 { data string Clone; // 4 not yet supported } record C5 { void Clone() { } // 5 void Clone(int i) { } // 6 } record C6 { class Clone { } // 7 } record C7 { delegate void Clone(); // 8 } record C8 { event System.Action Clone; // 9 } record Clone { Clone(int i) => throw null; } record C9 : System.ICloneable { object System.ICloneable.Clone() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,18): error CS8859: Members named 'Clone' are disallowed in records. // record C1(string Clone); // 1 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(2, 18), // (5,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone; // 2 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(5, 12), // (5,12): warning CS0169: The field 'C2.Clone' is never used // string Clone; // 2 Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C2.Clone").WithLocation(5, 12), // (9,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone { get; set; } // 3 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(9, 12), // (13,10): error CS1519: Invalid token 'string' in class, record, struct, or interface member declaration // data string Clone; // 4 not yet supported Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "string").WithArguments("string").WithLocation(13, 10), // (13,17): error CS8859: Members named 'Clone' are disallowed in records. // data string Clone; // 4 not yet supported Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(13, 17), // (13,17): warning CS0169: The field 'C4.Clone' is never used // data string Clone; // 4 not yet supported Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C4.Clone").WithLocation(13, 17), // (17,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone() { } // 5 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(17, 10), // (18,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone(int i) { } // 6 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(18, 10), // (22,11): error CS8859: Members named 'Clone' are disallowed in records. // class Clone { } // 7 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(22, 11), // (26,19): error CS8859: Members named 'Clone' are disallowed in records. // delegate void Clone(); // 8 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(26, 19), // (30,25): error CS8859: Members named 'Clone' are disallowed in records. // event System.Action Clone; // 9 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(30, 25), // (30,25): warning CS0067: The event 'C8.Clone' is never used // event System.Action Clone; // 9 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Clone").WithArguments("C8.Clone").WithLocation(30, 25) ); } [Fact] public void Clone_LoadedFromMetadata() { // IL for ' public record Base(int i);' with a 'void Clone()' method added var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object implements class [mscorlib]System.IEquatable`1<class Base> { .field private initonly int32 '<i>k__BackingField' .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname newslot virtual instance class Base '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldarg.0 IL_0001: newobj instance void Base::.ctor(class Base) IL_0006: ret } .method family hidebysig specialname newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldtoken Base IL_0005: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_000a: ret } .method public hidebysig specialname rtspecialname instance void .ctor ( int32 i ) cil managed { IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld int32 Base::'<i>k__BackingField' IL_0007: ldarg.0 IL_0008: call instance void [mscorlib]System.Object::.ctor() IL_000d: ret } .method public hidebysig specialname instance int32 get_i () cil managed { IL_0000: ldarg.0 IL_0001: ldfld int32 Base::'<i>k__BackingField' IL_0006: ret } .method public hidebysig specialname instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_i ( int32 'value' ) cil managed { IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld int32 Base::'<i>k__BackingField' IL_0007: ret } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<class [mscorlib]System.Type>::get_Default() IL_0005: ldarg.0 IL_0006: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract() IL_000b: callvirt instance int32 class [mscorlib]System.Collections.Generic.EqualityComparer`1<class [mscorlib]System.Type>::GetHashCode(!0) IL_0010: ldc.i4 -1521134295 IL_0015: mul IL_0016: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::get_Default() IL_001b: ldarg.0 IL_001c: ldfld int32 Base::'<i>k__BackingField' IL_0021: callvirt instance int32 class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::GetHashCode(!0) IL_0026: add IL_0027: ret } .method public hidebysig virtual instance bool Equals ( object obj ) cil managed { IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst Base IL_0007: callvirt instance bool Base::Equals(class Base) IL_000c: ret } .method public newslot virtual instance bool Equals ( class Base '' ) cil managed { IL_0000: ldarg.1 IL_0001: brfalse.s IL_002d IL_0003: ldarg.0 IL_0004: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract() IL_0009: ldarg.1 IL_000a: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract() IL_000f: call bool [mscorlib]System.Type::op_Equality(class [mscorlib]System.Type, class [mscorlib]System.Type) IL_0014: brfalse.s IL_002d IL_0016: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::get_Default() IL_001b: ldarg.0 IL_001c: ldfld int32 Base::'<i>k__BackingField' IL_0021: ldarg.1 IL_0022: ldfld int32 Base::'<i>k__BackingField' IL_0027: callvirt instance bool class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::Equals(!0, !0) IL_002c: ret IL_002d: ldc.i4.0 IL_002e: ret } .method family hidebysig specialname rtspecialname instance void .ctor ( class Base '' ) cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld int32 Base::'<i>k__BackingField' IL_000d: stfld int32 Base::'<i>k__BackingField' IL_0012: ret } .method public hidebysig instance void Deconstruct ( [out] int32& i ) cil managed { IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call instance int32 Base::get_i() IL_0007: stind.i4 IL_0008: ret } .method public hidebysig instance void Clone () cil managed { IL_0000: ldstr ""RAN"" IL_0005: call void [mscorlib]System.Console::Write(string) IL_000a: ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type Base::get_EqualityContract() } .property instance int32 i() { .get instance int32 Base::get_i() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) Base::set_i(int32) } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi abstract sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends [mscorlib]System.Object { } "; var src = @" record R(int i) : Base(i); public class C { public static void Main() { var r = new R(1); r.Clone(); } } "; var comp = CreateCompilationWithIL(src, il, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics(); // Note: we do load the Clone method from metadata } [Fact] public void Clone_01() { var src = @" abstract sealed record C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static // abstract sealed record C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24) ); var clone = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1"); Assert.True(namedTypeSymbol.IsRecord); Assert.Equal("record C1", namedTypeSymbol .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_02() { var src = @" sealed abstract record C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static // sealed abstract record C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24) ); var clone = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1"); Assert.True(namedTypeSymbol.IsRecord); Assert.Equal("record C1", namedTypeSymbol .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_03() { var src = @" record C1; abstract sealed record C2 : C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static // abstract sealed record C2 : C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24) ); var clone = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); } [Fact] public void Clone_04() { var src = @" record C1; sealed abstract record C2 : C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static // sealed abstract record C2 : C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24) ); var clone = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1"); Assert.True(namedTypeSymbol.IsRecord); Assert.Equal("record C1", namedTypeSymbol .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_05_IntReturnType_UsedAsBaseType() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_06_IntReturnType_UsedInWith() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A "; var source = @" public class Program { static void Main() { A x = new A() with { }; } } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS8858: The receiver type 'A' is not a valid record type. // A x = new A() with { }; Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_07_Ambiguous_UsedAsBaseType() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_08_Ambiguous_UsedInWith() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A "; var source = @" public class Program { static void Main() { A x = new A() with { }; } } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS8858: The receiver type 'A' is not a valid record type. // A x = new A() with { }; Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_09_AmbiguousReverseOrder_UsedAsBaseType() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_10_AmbiguousReverseOrder_UsedInWith() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A "; var source = @" public class Program { static void Main() { A x = new A() with { }; } } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS8858: The receiver type 'A' is not a valid record type. // A x = new A() with { }; Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_11() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(source1).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" class Program { public static void Main() { var c1 = new B(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; CompileAndVerify(source3, references: new[] { comp1Ref, comp2Ref }, expectedOutput: @"1 11").VerifyDiagnostics(); } [Fact] public void Clone_12() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, assemblyName: "Clone_12", parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" class Program { public static void Main() { var c1 = new B(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; var comp3 = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp2Ref }, parseOptions: TestOptions.Regular9); comp3.VerifyEmitDiagnostics( // (7,18): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_12, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("A", "Clone_12, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18) ); } [Fact] public void Clone_13() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, assemblyName: "Clone_13", references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" public record C(int X) : B(X); "; var comp3Ref = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp2Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source4 = @" class Program { public static void Main() { var c1 = new C(1); var c2 = c1 with { X = 11 }; } } "; var comp4 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp3Ref }, parseOptions: TestOptions.Regular9); comp4.VerifyEmitDiagnostics( // (7,18): error CS8858: The receiver type 'C' is not a valid record type. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_CannotClone, "c1").WithArguments("C").WithLocation(7, 18), // (7,18): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18), // (7,28): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "X").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 28), // (7,28): error CS0117: 'C' does not contain a definition for 'X' // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("C", "X").WithLocation(7, 28) ); var comp5 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp3Ref }, parseOptions: TestOptions.Regular9); comp5.VerifyEmitDiagnostics( // (7,18): error CS8858: The receiver type 'C' is not a valid record type. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_CannotClone, "c1").WithArguments("C").WithLocation(7, 18), // (7,18): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18), // (7,28): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "X").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 28), // (7,28): error CS0117: 'C' does not contain a definition for 'X' // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("C", "X").WithLocation(7, 28) ); } [Fact] public void Clone_14() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(source1).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" record C(int X) : B(X) { public static void Main() { var c1 = new C(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; CompileAndVerify(source3, references: new[] { comp1Ref, comp2Ref }, expectedOutput: @"1 11").VerifyDiagnostics(); } [Fact] public void Clone_15() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, assemblyName: "Clone_15", parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" record C(int X) : B(X) { public static void Main() { var c1 = new C(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; var comp3 = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp2Ref }, parseOptions: TestOptions.Regular9); comp3.VerifyEmitDiagnostics( // (2,8): error CS8869: 'C.Equals(object?)' does not override expected method from 'object'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.Equals(object?)").WithLocation(2, 8), // (2,8): error CS8869: 'C.GetHashCode()' does not override expected method from 'object'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.GetHashCode()").WithLocation(2, 8), // (2,8): error CS8869: 'C.ToString()' does not override expected method from 'object'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.ToString()").WithLocation(2, 8), // (2,8): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 8), // (2,19): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (2,19): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (6,22): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c1 = new C(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22), // (7,18): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18), // (8,9): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine(c1.X); Diagnostic(ErrorCode.ERR_NoTypeDef, "System").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 9), // (9,9): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine(c2.X); Diagnostic(ErrorCode.ERR_NoTypeDef, "System").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 9) ); } [Fact] public void Clone_16() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, assemblyName: "Clone_16", references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" public record C(int X) : B(X); "; var comp3Ref = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp2Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source4 = @" record D(int X) : C(X) { public static void Main() { var c1 = new D(1); var c2 = c1 with { X = 11 }; } } "; var comp4 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp3Ref }, parseOptions: TestOptions.Regular9); comp4.VerifyEmitDiagnostics( // (2,8): error CS8869: 'D.Equals(object?)' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.Equals(object?)").WithLocation(2, 8), // (2,8): error CS8869: 'D.GetHashCode()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.GetHashCode()").WithLocation(2, 8), // (2,8): error CS8869: 'D.ToString()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.ToString()").WithLocation(2, 8), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (2,19): error CS8864: Records may only inherit from object or another record // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_BadRecordBase, "C").WithLocation(2, 19), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (6,22): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c1 = new D(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22) ); var comp5 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp3Ref }, parseOptions: TestOptions.Regular9); comp5.VerifyEmitDiagnostics( // (2,8): error CS8869: 'D.Equals(object?)' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.Equals(object?)").WithLocation(2, 8), // (2,8): error CS8869: 'D.GetHashCode()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.GetHashCode()").WithLocation(2, 8), // (2,8): error CS8869: 'D.ToString()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.ToString()").WithLocation(2, 8), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (2,19): error CS8864: Records may only inherit from object or another record // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_BadRecordBase, "C").WithLocation(2, 19), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (6,22): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c1 = new D(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22) ); } [Fact] public void Clone_17_NonOverridable() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_18_NonOverridable() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual final instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_19() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A .class public auto ansi beforefieldinit B extends A { // Methods .method public hidebysig specialname virtual final instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class B "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0239: 'C.<Clone>$()': cannot override inherited member 'B.<Clone>$()' because it is sealed // public record C : B { Diagnostic(ErrorCode.ERR_CantOverrideSealed, "C").WithArguments("C.<Clone>$()", "B.<Clone>$()").WithLocation(2, 15) ); } [Fact, WorkItem(47093, "https://github.com/dotnet/roslyn/issues/47093")] public void ToString_TopLevelRecord_Empty() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1; "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.True(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: callvirt ""bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_AbstractRecord() { var src = @" var c2 = new C2(); System.Console.Write(c2); abstract record C1; record C2 : C1 { public override string ToString() => base.ToString(); } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.True(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: callvirt ""bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_DerivedRecord_AbstractRecord() { var src = @" var c2 = new C2(); System.Console.Write(c2); record Base; abstract record C1 : Base; record C2 : C1 { public override string ToString() => base.ToString(); } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.True(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool Base.PrintMembers(System.Text.StringBuilder)"" IL_0007: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: callvirt ""bool Base.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilder() { var src = @" record C1; "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Text_StringBuilder); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "record C1;").WithArguments("System.Text.StringBuilder").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1), // (2,8): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C1").WithArguments("System.Text.StringBuilder").WithLocation(2, 8) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderCtor() { var src = @" record C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__ctor); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderAppendString() { var src = @" record C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendString() { var src = @" record C1(int P); "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendStringAndChar() { var src = @" record C1(int P); "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendChar); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_Empty_Sealed() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); sealed record C1; "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); } [Fact] public void ToString_AbstractRecord() { var src = @" var c2 = new C2(42, 43); System.Console.Write(c2.ToString()); abstract record C1(int I1); sealed record C2(int I1, int I2) : C1(I1); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2 { I1 = 42, I2 = 43 }", verify: Verification.Skipped /* init-only */); } [Fact, WorkItem(47672, "https://github.com/dotnet/roslyn/issues/47672")] public void ToString_RecordWithIndexer() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); record C1(int I1) { private int field = 44; public int this[int i] => 0; public int PropertyWithoutGetter { set { } } public int P2 { get => 43; } public ref int P3 { get => ref field; } public event System.Action a; private int field1 = 100; internal int field2 = 100; protected int field3 = 100; private protected int field4 = 100; internal protected int field5 = 100; private int Property1 { get; set; } = 100; internal int Property2 { get; set; } = 100; protected int Property3 { get; set; } = 100; private protected int Property4 { get; set; } = 100; internal protected int Property5 { get; set; } = 100; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "C1 { I1 = 42, P2 = 43, P3 = 44 }", verify: Verification.Skipped /* init-only */); comp.VerifyEmitDiagnostics( // (12,32): warning CS0067: The event 'C1.a' is never used // public event System.Action a; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "a", isSuppressed: false).WithArguments("C1.a").WithLocation(12, 32), // (14,17): warning CS0414: The field 'C1.field1' is assigned but its value is never used // private int field1 = 100; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field1", isSuppressed: false).WithArguments("C1.field1").WithLocation(14, 17) ); } [Fact, WorkItem(47672, "https://github.com/dotnet/roslyn/issues/47672")] public void ToString_PrivateGetter() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1 { public int P1 { private get => 43; set => throw null; } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "C1 { P1 = 43 }"); comp.VerifyEmitDiagnostics(); } [Fact, WorkItem(47797, "https://github.com/dotnet/roslyn/issues/47797")] public void ToString_OverriddenVirtualProperty_NoRepetition() { var src = @" System.Console.WriteLine(new B() { P = 2 }.ToString()); abstract record A { public virtual int P { get; set; } } record B : A { public override int P { get; set; } } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "B { P = 2 }"); } [Fact, WorkItem(47797, "https://github.com/dotnet/roslyn/issues/47797")] public void ToString_OverriddenAbstractProperty_NoRepetition() { var src = @" System.Console.Write(new B1() { P = 1 }); System.Console.Write("" ""); System.Console.Write(new B2(2)); abstract record A1 { public abstract int P { get; set; } } record B1 : A1 { public override int P { get; set; } } abstract record A2(int P); record B2(int P) : A2(P); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "B1 { P = 1 } B2 { P = 2 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_ErrorBase() { var src = @" record C2: Error; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0115: 'C2.ToString()': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'C2.EqualityContract': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'C2.Equals(object?)': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'C2.GetHashCode()': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'C2.PrintMembers(StringBuilder)': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,12): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // record C2: Error; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(2, 12) ); } [Fact, WorkItem(49263, "https://github.com/dotnet/roslyn/issues/49263")] public void ToString_SelfReferentialBase() { var src = @" record R : R; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0146: Circular base type dependency involving 'R' and 'R' // record R : R; Diagnostic(ErrorCode.ERR_CircularBase, "R").WithArguments("R", "R").WithLocation(2, 8), // (2,8): error CS0115: 'R.ToString()': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'R.EqualityContract': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'R.Equals(object?)': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'R.GetHashCode()': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'R.PrintMembers(StringBuilder)': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8) ); } [Fact] public void ToString_TopLevelRecord_Empty_AbstractSealed() { var src = @" abstract sealed record C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static // abstract sealed record C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24) ); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_ValueType() { var src = @" var c1 = new C1() { field = 42 }; System.Console.Write(c1.ToString()); record C1 { public int field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.True(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldflda ""int C1.field"" IL_0018: constrained. ""int"" IL_001e: callvirt ""string object.ToString()"" IL_0023: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0028: pop IL_0029: ldc.i4.1 IL_002a: ret } "); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_ConstrainedValueType() { var src = @" var c1 = new C1<int>() { field = 42 }; System.Console.Write(c1.ToString()); record C1<T> where T : struct { public T field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldflda ""T C1<T>.field"" IL_0018: constrained. ""T"" IL_001e: callvirt ""string object.ToString()"" IL_0023: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0028: pop IL_0029: ldc.i4.1 IL_002a: ret } "); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_ReferenceType() { var src = @" var c1 = new C1() { field = ""hello"" }; System.Console.Write(c1.ToString()); record C1 { public string field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 32 (0x20) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldfld ""string C1.field"" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_001d: pop IL_001e: ldc.i4.1 IL_001f: ret } "); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_Unconstrained() { var src = @" var c1 = new C1<string>() { field = ""hello"" }; System.Console.Write(c1.ToString()); System.Console.Write("" ""); var c2 = new C1<int>() { field = 42 }; System.Console.Write(c2.ToString()); record C1<T> { public T field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello } C1 { field = 42 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 37 (0x25) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldfld ""T C1<T>.field"" IL_0018: box ""T"" IL_001d: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0022: pop IL_0023: ldc.i4.1 IL_0024: ret } "); } [Fact] public void ToString_TopLevelRecord_OneField_ErrorType() { var src = @" record C1 { public Error field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,12): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // public Error field; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 12), // (4,18): warning CS0649: Field 'C1.field' is never assigned to, and will always have its default value null // public Error field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C1.field", "null").WithLocation(4, 18) ); } [Fact] public void ToString_TopLevelRecord_TwoFields_ReferenceType() { var src = @" var c1 = new C1() { field1 = ""hi"", field2 = null }; System.Console.Write(c1.ToString()); record C1 { public string field1; public string field2; private string field3; internal string field4; protected string field5; protected internal string field6; private protected string field7; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (10,20): warning CS0169: The field 'C1.field3' is never used // private string field3; Diagnostic(ErrorCode.WRN_UnreferencedField, "field3").WithArguments("C1.field3").WithLocation(10, 20), // (11,21): warning CS0649: Field 'C1.field4' is never assigned to, and will always have its default value null // internal string field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field4").WithArguments("C1.field4", "null").WithLocation(11, 21), // (12,22): warning CS0649: Field 'C1.field5' is never assigned to, and will always have its default value null // protected string field5; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field5").WithArguments("C1.field5", "null").WithLocation(12, 22), // (13,31): warning CS0649: Field 'C1.field6' is never assigned to, and will always have its default value null // protected internal string field6; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field6").WithArguments("C1.field6", "null").WithLocation(13, 31), // (14,30): warning CS0649: Field 'C1.field7' is never assigned to, and will always have its default value null // private protected string field7; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field7").WithArguments("C1.field7", "null").WithLocation(14, 30) ); var v = CompileAndVerify(comp, expectedOutput: "C1 { field1 = hi, field2 = }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 57 (0x39) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field1 = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldfld ""string C1.field1"" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_001d: pop IL_001e: ldarg.1 IL_001f: ldstr "", field2 = "" IL_0024: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0029: pop IL_002a: ldarg.1 IL_002b: ldarg.0 IL_002c: ldfld ""string C1.field2"" IL_0031: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0036: pop IL_0037: ldc.i4.1 IL_0038: ret } "); } [Fact] public void ToString_TopLevelRecord_OneProperty() { var src = @" var c1 = new C1(Property: 42); System.Console.Write(c1.ToString()); record C1(int Property) { private int Property2; internal int Property3; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,17): warning CS0169: The field 'C1.Property2' is never used // private int Property2; Diagnostic(ErrorCode.WRN_UnreferencedField, "Property2").WithArguments("C1.Property2").WithLocation(7, 17), // (8,18): warning CS0649: Field 'C1.Property3' is never assigned to, and will always have its default value 0 // internal int Property3; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Property3").WithArguments("C1.Property3", "0").WithLocation(8, 18) ); var v = CompileAndVerify(comp, expectedOutput: "C1 { Property = 42 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 46 (0x2e) .maxstack 2 .locals init (int V_0) IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""Property = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: call ""int C1.Property.get"" IL_0018: stloc.0 IL_0019: ldloca.s V_0 IL_001b: constrained. ""int"" IL_0021: callvirt ""string object.ToString()"" IL_0026: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_002b: pop IL_002c: ldc.i4.1 IL_002d: ret }"); } [Fact] public void ToString_TopLevelRecord_TwoFieldsAndTwoProperties() { var src = @" var c1 = new C1<int, string>(42, null) { field1 = 43, field2 = ""hi"" }; System.Console.Write(c1.ToString()); record C1<T1, T2>(T1 Property1, T2 Property2) { public T1 field1; public T2 field2; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { Property1 = 42, Property2 = , field1 = 43, field2 = hi }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties() { var src = @" var c1 = new C1(42, 43) { A2 = 100, B2 = 101 }; System.Console.Write(c1.ToString()); record Base(int A1) { public int A2; } record C1(int A1, int B1) : Base(A1) { public int B2; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { A1 = 42, A2 = 100, B1 = 43, B2 = 101 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 98 (0x62) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool Base.PrintMembers(System.Text.StringBuilder)"" IL_0007: brfalse.s IL_0015 IL_0009: ldarg.1 IL_000a: ldstr "", "" IL_000f: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0014: pop IL_0015: ldarg.1 IL_0016: ldstr ""B1 = "" IL_001b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0020: pop IL_0021: ldarg.1 IL_0022: ldarg.0 IL_0023: call ""int C1.B1.get"" IL_0028: stloc.0 IL_0029: ldloca.s V_0 IL_002b: constrained. ""int"" IL_0031: callvirt ""string object.ToString()"" IL_0036: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_003b: pop IL_003c: ldarg.1 IL_003d: ldstr "", B2 = "" IL_0042: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0047: pop IL_0048: ldarg.1 IL_0049: ldarg.0 IL_004a: ldflda ""int C1.B2"" IL_004f: constrained. ""int"" IL_0055: callvirt ""string object.ToString()"" IL_005a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_005f: pop IL_0060: ldc.i4.1 IL_0061: ret } "); } [Fact] public void ToString_DerivedRecord_AbstractSealed() { var src = @" record C1; abstract sealed record C2 : C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static // abstract sealed record C2 : C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24) ); var print = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.True(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); } [Theory] [InlineData(false)] [InlineData(true)] public void ToString_DerivedRecord_BaseHasSealedToString(bool usePreview) { var src = @" var c = new C2(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1; "; var comp = CreateCompilation(src, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9, options: TestOptions.DebugExe); if (usePreview) { comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); } else { comp.VerifyEmitDiagnostics( // (7,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater. // public sealed override string ToString() => "C1"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(7, 35) ); } } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1; record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseTriesToOverride() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public override string ToString() => ""C2""; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (11,28): error CS0239: 'C2.ToString()': cannot override inherited member 'C1.ToString()' because it is sealed // public override string ToString() => "C2"; Diagnostic(ErrorCode.ERR_CantOverrideSealed, "ToString").WithArguments("C2.ToString()", "C1.ToString()").WithLocation(11, 28) ); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseShadowsToStringPrivate() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { private new string ToString() => ""C2""; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseShadowsToStringNonSealed() { var src = @" C3 c3 = new C3(); System.Console.Write(c3.ToString()); C1 c1 = c3; System.Console.Write(c1.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public new virtual string ToString() => ""C2""; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseHasToStringWithDifferentSignature() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public string ToString(int n) => throw null; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseHasToStringWithDifferentReturnType() { var src = @" C1 c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public new int ToString() => throw null; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_ReverseOrder() { var src = @" var c1 = new C1(42, 43) { A1 = 100, B1 = 101 }; System.Console.Write(c1.ToString()); record Base(int A2) { public int A1; } record C1(int A2, int B2) : Base(A2) { public int B1; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { A2 = 42, A1 = 100, B2 = 43, B1 = 101 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_Partial() { var src1 = @" var c1 = new C1() { A1 = 100, B1 = 101 }; System.Console.Write(c1.ToString()); partial record C1 { public int A1; } "; var src2 = @" partial record C1 { public int B1; } "; var comp = CreateCompilation(new[] { src1, src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { A1 = 100, B1 = 101 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_Partial_ReverseOrder() { var src1 = @" var c1 = new C1() { A1 = 100, B1 = 101 }; System.Console.Write(c1.ToString()); partial record C1 { public int B1; } "; var src2 = @" partial record C1 { public int A1; } "; var comp = CreateCompilation(new[] { src1, src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { B1 = 101, A1 = 100 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_BadBase_MissingToString() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldstr ""RAN"" IL_0005: ret } } .class public auto ansi beforefieldinit B extends A { .method family hidebysig specialname virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Inequality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Equality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object obj ) cil managed { IL_0000: ldnull IL_0001: throw } .method public final hidebysig virtual instance bool Equals ( class A other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance bool Equals ( class B other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class B original ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void A::.ctor() IL_0006: ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } // no override for ToString } "; var source = @" var c = new C(); System.Console.Write(c); public record C : B { public override string ToString() => base.ToString(); } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); } [Fact] public void ToString_BadBase_PrintMembersSealed() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method final family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.PrintMembers(StringBuilder)': cannot override inherited member 'A.PrintMembers(StringBuilder)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)", "A.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersInaccessible() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method private hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // public record B : A { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersReturnsInt() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance int32 '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.PrintMembers(StringBuilder)': return type must be 'int' to match overridden member 'A.PrintMembers(StringBuilder)' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)", "A.PrintMembers(System.Text.StringBuilder)", "int").WithLocation(2, 15) ); } [Fact] public void EqualityContract_BadBase_ReturnsInt() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance int32 get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 EqualityContract() { .get instance int32 A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS1715: 'B.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "B").WithArguments("B.EqualityContract", "A.EqualityContract", "int").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersIsAmbiguous() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance int32 '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_BadBase_MissingPrintMembers() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // public record B : A { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_DuplicatePrintMembers() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder modopt(int64) builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_BadBase_PrintMembersNotOverriddenInBase() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi beforefieldinit B extends A { .method family hidebysig specialname virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Inequality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Equality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object obj ) cil managed { IL_0000: ldnull IL_0001: throw } .method public final hidebysig virtual instance bool Equals ( class A other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance bool Equals ( class B other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class B original ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } // no override for PrintMembers } "; var source = @" public record C : B { protected override bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,29): error CS8871: 'C.PrintMembers(StringBuilder)' does not override expected method from 'B'. // protected override bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(4, 29) ); var source2 = @" public record C : B; "; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8871: 'C.PrintMembers(StringBuilder)' does not override expected method from 'B'. // public record C : B; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersWithModOpt() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder modopt(int64) builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); var print = comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal("System.Boolean B.PrintMembers(System.Text.StringBuilder modopt(System.Int64) builder)", print.ToTestDisplayString()); Assert.Equal("System.Boolean A.PrintMembers(System.Text.StringBuilder modopt(System.Int64) builder)", print.OverriddenMethod.ToTestDisplayString()); } [Fact] public void ToString_BadBase_NewToString() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.ToString()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.ToString()").WithLocation(2, 15) ); } [Fact] public void ToString_NewToString_SealedBaseToString() { var source = @" B b = new B(); System.Console.Write(b.ToString()); A a = b; System.Console.Write(a.ToString()); public record A { public sealed override string ToString() => ""A""; } public record B : A { public new string ToString() => ""B""; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "BA"); } [Theory] [InlineData(false)] [InlineData(true)] public void ToString_BadBase_SealedToString(bool usePreview) { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public final hidebysig virtual instance string ToString () cil managed { IL_0000: ldstr ""A"" IL_0001: ret } } "; var source = @" var b = new B(); System.Console.Write(b.ToString()); public record B : A { }"; var comp = CreateCompilationWithIL( new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9); if (usePreview) { comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "A"); } else { comp.VerifyEmitDiagnostics( // (5,15): error CS8912: Inheriting from a record with a sealed 'Object.ToString' is not supported in C# 9.0. Please use language version '10.0' or greater. // public record B : A { Diagnostic(ErrorCode.ERR_InheritingFromRecordWithSealedToString, "B").WithArguments("9.0", "10.0").WithLocation(5, 15) ); } } [Fact] public void ToString_TopLevelRecord_UserDefinedToString() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1 { public override string ToString() => ""RAN""; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal("System.Boolean C1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", print.ToTestDisplayString()); } [Theory] [InlineData(false)] [InlineData(true)] public void ToString_TopLevelRecord_UserDefinedToString_Sealed(bool usePreview) { var src = @" record C1 { public sealed override string ToString() => throw null; } "; var comp = CreateCompilation(src, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9); if (usePreview) { comp.VerifyEmitDiagnostics(); } else { comp.VerifyEmitDiagnostics( // (4,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater. // public sealed override string ToString() => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(4, 35) ); } } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_Sealed_InSealedRecord() { var src = @" sealed record C1 { public sealed override string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_WithNullableStringBuilder() { var src = @" #nullable enable record C1 { protected virtual bool PrintMembers(System.Text.StringBuilder? builder) => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_ErrorReturnType() { var src = @" record C1 { protected virtual Error PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,23): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // protected virtual Error PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 23) ); } [Fact] public void ToString_UserDefinedPrintMembers_WrongReturnType() { var src = @" record C1 { protected virtual int PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,27): error CS8874: Record member 'C1.PrintMembers(StringBuilder)' must return 'bool'. // protected virtual int PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "bool").WithLocation(4, 27) ); } [Fact] public void ToString_UserDefinedPrintMembers_Sealed() { var src = @" record C1(int I1); record C2(int I1, int I2) : C1(I1) { protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,36): error CS8872: 'C2.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed. // protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 36) ); } [Fact] public void ToString_UserDefinedPrintMembers_NonVirtual() { var src = @" record C1 { protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,20): error CS8872: 'C1.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed. // protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20) ); } [Fact] public void ToString_UserDefinedPrintMembers_SealedInSealedRecord() { var src = @" record C1(int I1); sealed record C2(int I1, int I2) : C1(I1) { protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_Static() { var src = @" sealed record C { private static bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,25): error CS8877: Record member 'C.PrintMembers(StringBuilder)' may not be static. // private static bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "PrintMembers").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25) ); } [Fact] public void ToString_UserDefinedPrintMembers() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1 { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { builder.Append(""RAN""); return true; } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { RAN }"); } [Fact] public void ToString_UserDefinedPrintMembers_WrongAccessibility() { var src = @" record C1 { public virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,25): error CS8875: Record member 'C1.PrintMembers(StringBuilder)' must be protected. // public virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25) ); } [Fact] public void ToString_UserDefinedPrintMembers_WrongAccessibility_SealedRecord() { var src = @" sealed record C1 { protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,20): warning CS0628: 'C1.PrintMembers(StringBuilder)': new protected member declared in sealed type // protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20), // (4,20): error CS8879: Record member 'C1.PrintMembers(StringBuilder)' must be private. // protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20) ); } [Fact] public void ToString_UserDefinedPrintMembers_DerivedRecord_WrongAccessibility() { var src = @" record B; record C1 : B { public bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,17): error CS8875: Record member 'C1.PrintMembers(StringBuilder)' must be protected. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17), // (5,17): error CS8860: 'C1.PrintMembers(StringBuilder)' does not override expected method from 'B'. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(5, 17), // (5,17): error CS8872: 'C1.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17), // (5,17): warning CS0114: 'C1.PrintMembers(StringBuilder)' hides inherited member 'B.PrintMembers(StringBuilder)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17) ); } [Fact] public void ToString_UserDefinedPrintMembers_New() { var src = @" record B; record C1 : B { protected new virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,32): error CS8860: 'C1.PrintMembers(StringBuilder)' does not override expected method from 'B'. // protected new virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(5, 32) ); } [Fact] public void ToString_TopLevelRecord_EscapedNamed() { var src = @" var c1 = new @base(); System.Console.Write(c1.ToString()); record @base; "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "base { }"); } [Fact] public void ToString_DerivedDerivedRecord() { var src = @" var r1 = new R1(1); System.Console.Write(r1.ToString()); System.Console.Write("" ""); var r2 = new R2(10, 11); System.Console.Write(r2.ToString()); System.Console.Write("" ""); var r3 = new R3(20, 21, 22); System.Console.Write(r3.ToString()); record R1(int I1); record R2(int I1, int I2) : R1(I1); record R3(int I1, int I2, int I3) : R2(I1, I2); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "R1 { I1 = 1 } R2 { I1 = 10, I2 = 11 } R3 { I1 = 20, I2 = 21, I3 = 22 }", verify: Verification.Skipped /* init-only */); } [Fact] public void WithExpr24() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(ref C other) : this(-1) { } protected C(C other) { X = other.X; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); var clone = verifier.Compilation.GetMember("C." + WellKnownMemberNames.CloneMethodName); Assert.Equal("<Clone>$", clone.Name); } [Fact] public void WithExpr25() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(in C other) : this(-1) { } protected C(C other) { X = other.X; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr26() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(out C other) : this(-1) { other = null; } protected C(C other) { X = other.X; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr27() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(ref C other) : this(-1) { } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr28() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(in C other) : this(-1) { } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr29() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(out C other) : this(-1) { other = null; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void AccessibilityOfBaseCtor_01() { var src = @" using System; record Base { protected Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} public static void Main() { var c = new C(1, 2); } } record C(int X, int Y) : Base(X, Y); "; CompileAndVerify(src, expectedOutput: @" 1 2 ").VerifyDiagnostics(); } [Fact] public void AccessibilityOfBaseCtor_02() { var src = @" using System; record Base { protected Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} public static void Main() { var c = new C(1, 2); } } record C(int X, int Y) : Base(X, Y) {} "; CompileAndVerify(src, expectedOutput: @" 1 2 ").VerifyDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_03() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B(object P) : A; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_04() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B(object P) : A {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_05() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B : A; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_06() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B : A {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExprNestedErrors() { var src = @" class C { public int X { get; init; } public static void Main() { var c = new C(); c = c with { X = """"-3 }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone". // c = c with { X = ""-3 }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(8, 13), // (8,26): error CS0019: Operator '-' cannot be applied to operands of type 'string' and 'int' // c = c with { X = ""-3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, @"""""-3").WithArguments("-", "string", "int").WithLocation(8, 26) ); } [Fact] public void WithExprNoExpressionToPropertyTypeConversion() { var src = @" record C(int X) { public static void Main() { var c = new C(0); c = c with { X = """" }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int' // c = c with { X = "" }; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(8, 26) ); } [Fact] public void WithExprPropertyInaccessibleSet() { var src = @" record C { public int X { get; private set; } } class D { public static void Main() { var c = new C(); c = c with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,22): error CS0272: The property or indexer 'C.X' cannot be used in this context because the set accessor is inaccessible // c = c with { X = 0 }; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "X").WithArguments("C.X").WithLocation(11, 22) ); } [Fact] public void WithExprSideEffects1() { var src = @" using System; record C(int X, int Y, int Z) { public static void Main() { var c = new C(0, 1, 2); c = c with { Y = W(""Y""), X = W(""X"") }; } public static int W(string s) { Console.WriteLine(s); return 0; } } "; var verifier = CompileAndVerify(src, expectedOutput: @" Y X").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 47 (0x2f) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""C..ctor(int, int, int)"" IL_0008: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_000d: dup IL_000e: ldstr ""Y"" IL_0013: call ""int C.W(string)"" IL_0018: callvirt ""void C.Y.init"" IL_001d: dup IL_001e: ldstr ""X"" IL_0023: call ""int C.W(string)"" IL_0028: callvirt ""void C.X.init"" IL_002d: pop IL_002e: ret }"); var comp = (CSharpCompilation)verifier.Compilation; var tree = comp.SyntaxTrees.First(); var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); var withExpr1 = root.DescendantNodes().OfType<WithExpressionSyntax>().First(); comp.VerifyOperationTree(withExpr1, @" IWithOperation (OperationKind.With, Type: C) (Syntax: 'c with { Y ... = W(""X"") }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ Y = W(""Y"" ... = W(""X"") }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'Y = W(""Y"")') Left: IPropertyReferenceOperation: System.Int32 C.Y { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Y') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""Y"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""Y""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Y"") (Syntax: '""Y""') 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) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = W(""X"")') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""X"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""X""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""X"") (Syntax: '""X""') 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) "); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0, 1, 2)') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0, 1, 2)') Right: IObjectCreationOperation (Constructor: C..ctor(System.Int32 X, System.Int32 Y, System.Int32 Z)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0, 1, 2)') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Z) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') 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) Initializer: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] [1] Block[B2] - Block Predecessors: [B1] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Value: IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'Y = W(""Y"")') Left: IPropertyReferenceOperation: System.Int32 C.Y { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Y') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""Y"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""Y""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Y"") (Syntax: '""Y""') 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) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = W(""X"")') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""X"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""X""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""X"") (Syntax: '""X""') 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) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with ... = W(""X"") };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with ... = W(""X"") }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Next (Regular) Block[B3] Leaving: {R2} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void WithExprConversions1() { var src = @" using System; record C(long X) { public static void Main() { var c = new C(0); Console.WriteLine((c with { X = 11 }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: "11").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 32 (0x20) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: conv.i8 IL_0002: newobj ""C..ctor(long)"" IL_0007: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_000c: dup IL_000d: ldc.i4.s 11 IL_000f: conv.i8 IL_0010: callvirt ""void C.X.init"" IL_0015: callvirt ""long C.X.get"" IL_001a: call ""void System.Console.WriteLine(long)"" IL_001f: ret }"); } [Fact] public void WithExprConversions2() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static implicit operator long(S s) { Console.WriteLine(""conversion""); return s._i; } } record C(long X) { public static void Main() { var c = new C(0); var s = new S(11); Console.WriteLine((c with { X = s }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" conversion 11").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 44 (0x2c) .maxstack 3 .locals init (S V_0) //s IL_0000: ldc.i4.0 IL_0001: conv.i8 IL_0002: newobj ""C..ctor(long)"" IL_0007: ldloca.s V_0 IL_0009: ldc.i4.s 11 IL_000b: call ""S..ctor(int)"" IL_0010: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0015: dup IL_0016: ldloc.0 IL_0017: call ""long S.op_Implicit(S)"" IL_001c: callvirt ""void C.X.init"" IL_0021: callvirt ""long C.X.get"" IL_0026: call ""void System.Console.WriteLine(long)"" IL_002b: ret }"); } [Fact] public void WithExprConversions3() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static explicit operator int(S s) { Console.WriteLine(""conversion""); return s._i; } } record C(long X) { public static void Main() { var c = new C(0); var s = new S(11); Console.WriteLine((c with { X = (int)s }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" conversion 11").VerifyDiagnostics(); } [Fact] public void WithExprConversions4() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static explicit operator long(S s) => s._i; } record C(long X) { public static void Main() { var c = new C(0); var s = new S(11); Console.WriteLine((c with { X = s }).X); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (19,41): error CS0266: Cannot implicitly convert type 'S' to 'long'. An explicit conversion exists (are you missing a cast?) // Console.WriteLine((c with { X = s }).X); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "s").WithArguments("S", "long").WithLocation(19, 41) ); } [Fact] public void WithExprConversions5() { var src = @" using System; record C(object X) { public static void Main() { var c = new C(0); Console.WriteLine((c with { X = ""abc"" }).X); } }"; CompileAndVerify(src, expectedOutput: "abc").VerifyDiagnostics(); } [Fact] public void WithExprConversions6() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static implicit operator int(S s) { Console.WriteLine(""conversion""); return s._i; } } record C { private readonly long _x; public long X { get => _x; init { Console.WriteLine(""set""); _x = value; } } public static void Main() { var c = new C(); var s = new S(11); Console.WriteLine((c with { X = s }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" conversion set 11").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 43 (0x2b) .maxstack 3 .locals init (S V_0) //s IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_0 IL_0007: ldc.i4.s 11 IL_0009: call ""S..ctor(int)"" IL_000e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0013: dup IL_0014: ldloc.0 IL_0015: call ""int S.op_Implicit(S)"" IL_001a: conv.i8 IL_001b: callvirt ""void C.X.init"" IL_0020: callvirt ""long C.X.get"" IL_0025: call ""void System.Console.WriteLine(long)"" IL_002a: ret }"); } [Fact] public void WithExprStaticProperty() { var src = @" record C { public static int X { get; set; } public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,22): error CS0176: Member 'C.X' cannot be accessed with an instance reference; qualify it with a type name instead // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_ObjectProhibited, "X").WithArguments("C.X").WithLocation(9, 22) ); } [Fact] public void WithExprMethodAsArgument() { var src = @" record C { public int X() => 0; public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,22): error CS1913: Member 'X' cannot be initialized. It is not a field or property. // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "X").WithArguments("X").WithLocation(9, 22) ); } [Fact] public void WithExprStaticWithMethod() { var src = @" class C { public int X = 0; public static C Clone() => null; public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone". // c = c with { }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(9, 13), // (10,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone". // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(10, 13) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExprStaticWithMethod2() { var src = @" class B { public B Clone() => null; } class C : B { public int X = 0; public static new C Clone() => null; // static public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,13): error CS0266: Cannot implicitly convert type 'B' to 'C'. An explicit conversion exists (are you missing a cast?) // c = c with { }; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "c with { }").WithArguments("B", "C").WithLocation(13, 13), // (14,22): error CS0117: 'B' does not contain a definition for 'X' // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("B", "X").WithLocation(14, 22) ); } [Fact] public void WithExprBadMemberBadType() { var src = @" record C { public int X { get; init; } public static void Main() { var c = new C(); c = c with { X = ""a"" }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int' // c = c with { X = "a" }; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""a""").WithArguments("string", "int").WithLocation(8, 26) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExprCloneReturnDifferent() { var src = @" class B { public int X { get; init; } } class C : B { public B Clone() => new B(); public static void Main() { var c = new C(); var b = c with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithSemanticModel1() { var src = @" record C(int X, string Y) { public static void Main() { var c = new C(0, ""a""); c = c with { X = 2 }; } }"; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees[0]; var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); var withExpr = root.DescendantNodes().OfType<WithExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(withExpr); var c = comp.GlobalNamespace.GetTypeMember("C"); Assert.True(c.IsRecord); Assert.True(c.ISymbol.Equals(typeInfo.Type)); var x = c.GetMembers("X").Single(); var xId = withExpr.DescendantNodes().Single(id => id.ToString() == "X"); var symbolInfo = model.GetSymbolInfo(xId); Assert.True(x.ISymbol.Equals(symbolInfo.Symbol)); comp.VerifyOperationTree(withExpr, @" IWithOperation (OperationKind.With, Type: C) (Syntax: 'c with { X = 2 }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 2 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')"); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0, ""a"")') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0, ""a"")') Right: IObjectCreationOperation (Constructor: C..ctor(System.Int32 X, System.String Y)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0, ""a"")') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: '""a""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""a"") (Syntax: '""a""') 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) Initializer: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] [1] Block[B2] - Block Predecessors: [B1] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c with { X = 2 }') Value: IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with { X = 2 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with { X = 2 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }') Next (Regular) Block[B3] Leaving: {R2} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void NoCloneMethod_01() { var src = @" class C { int X { get; set; } public static void Main() { var c = new C(); c = c with { X = 2 }; } }"; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees[0]; var root = tree.GetRoot(); var withExpr = root.DescendantNodes().OfType<WithExpressionSyntax>().Single(); comp.VerifyOperationTree(withExpr, @" IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { X = 2 }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 2 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')"); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Right: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] [1] Block[B2] - Block Predecessors: [B1] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c') Value: IInvalidOperation (OperationKind.Invalid, Type: C, IsInvalid, IsImplicit) (Syntax: 'c') Children(1): ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'c = c with { X = 2 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsInvalid) (Syntax: 'c = c with { X = 2 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c') Next (Regular) Block[B3] Leaving: {R2} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void NoCloneMethod_02() { var source = @"#nullable enable class R { public object? P { get; set; } } class Program { static void Main() { R r = new R(); _ = r with { P = 2 }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS8858: The receiver type 'R' is not a valid record type. // _ = r with { P = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "r").WithArguments("R").WithLocation(11, 13)); } [Fact] public void WithBadExprArg() { var src = @" record C(int X, int Y) { public static void Main() { var c = new C(0, 0); c = c with { 5 }; c = c with { { X = 2 } }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,22): error CS0747: Invalid initializer member declarator // c = c with { 5 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "5").WithLocation(8, 22), // (9,22): error CS1513: } expected // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(9, 22), // (9,22): error CS1002: ; expected // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(9, 22), // (9,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.X' // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_ObjectRequired, "X").WithArguments("C.X").WithLocation(9, 24), // (9,30): error CS1002: ; expected // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(9, 30), // (9,33): error CS1597: Semicolon after method or accessor block is not valid // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(9, 33), // (11,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(11, 1) ); var tree = comp.SyntaxTrees[0]; var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); VerifyClone(model); var withExpr1 = root.DescendantNodes().OfType<WithExpressionSyntax>().First(); comp.VerifyOperationTree(withExpr1, @" IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { 5 }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ 5 }') Initializers(1): IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '5') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsInvalid) (Syntax: '5')"); var withExpr2 = root.DescendantNodes().OfType<WithExpressionSyntax>().Skip(1).Single(); comp.VerifyOperationTree(withExpr2, @" IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { ') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ ') Initializers(0)"); } [Fact] public void WithExpr_DefiniteAssignment_01() { var src = @" record B(int X) { static void M(B b) { int y; _ = b with { X = y = 42 }; y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_02() { var src = @" record B(int X, string Y) { static void M(B b) { int z; _ = b with { X = z = 42, Y = z.ToString() }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_03() { var src = @" record B(int X, string Y) { static void M(B b) { int z; _ = b with { Y = z.ToString(), X = z = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,26): error CS0165: Use of unassigned local variable 'z' // _ = b with { Y = z.ToString(), X = z = 42 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(7, 26)); } [Fact] public void WithExpr_DefiniteAssignment_04() { var src = @" record B(int X) { static void M() { B b; _ = (b = new B(42)) with { X = b.X }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_05() { var src = @" record B(int X) { static void M() { B b; _ = new B(b.X) with { X = (b = new B(42)).X }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,19): error CS0165: Use of unassigned local variable 'b' // _ = new B(b.X) with { X = new B(42).X }; Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(7, 19)); } [Fact] public void WithExpr_DefiniteAssignment_06() { var src = @" record B(int X) { static void M(B b) { int y; _ = b with { X = M(out y) }; y.ToString(); } static int M(out int y) { y = 42; return 43; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_07() { var src = @" record B(int X) { static void M(B b) { _ = b with { X = M(out int y) }; y.ToString(); } static int M(out int y) { y = 42; return 43; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_01() { var src = @" #nullable enable record B(int X) { static void M(B b) { string? s = null; _ = b with { X = M(out s) }; s.ToString(); } static int M(out string s) { s = ""a""; return 42; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_02() { var src = @" #nullable enable record B(string X) { static void M(B b, string? s) { b.X.ToString(); _ = b with { X = s }; // 1 b.X.ToString(); // 2 } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): warning CS8601: Possible null reference assignment. // _ = b with { X = s }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(8, 26)); } [Fact] public void WithExpr_NullableAnalysis_03() { var src = @" #nullable enable record B(string? X) { static void M1(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 1 _ = b with { X = s }; if (flag) { b.X.ToString(); } // 2 } static void M2(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 3 b = b with { X = s }; if (flag) { b.X.ToString(); } } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(7, 21), // (9,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(9, 21), // (14,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(14, 21)); } [Fact] public void WithExpr_NullableAnalysis_04() { var src = @" #nullable enable record B(int X) { static void M1(B? b) { var b1 = b with { X = 42 }; // 1 _ = b.ToString(); _ = b1.ToString(); } static void M2(B? b) { (b with { X = 42 }).ToString(); // 2 } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,18): warning CS8602: Dereference of a possibly null reference. // var b1 = b with { X = 42 }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(7, 18), // (14,10): warning CS8602: Dereference of a possibly null reference. // (b with { X = 42 }).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(14, 10)); } [Fact, WorkItem(44763, "https://github.com/dotnet/roslyn/issues/44763")] public void WithExpr_NullableAnalysis_05() { var src = @" #nullable enable record B(string? X, string? Y) { static void M1(bool flag) { B b = new B(""hello"", null); if (flag) { b.X.ToString(); // shouldn't warn b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); // shouldn't warn b.Y.ToString(); } }"; // records should propagate the nullability of the // constructor arguments to the corresponding properties. // https://github.com/dotnet/roslyn/issues/44763 var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(11, 13), // (15,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(15, 9)); } [Fact] public void WithExpr_NullableAnalysis_06() { var src = @" #nullable enable record B { public string? X { get; init; } public string? Y { get; init; } static void M1(bool flag) { B b = new B { X = ""hello"", Y = null }; if (flag) { b.X.ToString(); b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); b.Y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(14, 13) ); } [Fact, WorkItem(44691, "https://github.com/dotnet/roslyn/issues/44691")] public void WithExpr_NullableAnalysis_07() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B([AllowNull] string X) // 1 { static void M1(B b) { b.X.ToString(); b = b with { X = null }; // 2 b.X.ToString(); // 3 b = new B((string?)null); b.X.ToString(); } }"; var comp = CreateCompilation(new[] { src, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,10): warning CS8601: Possible null reference assignment. // record B([AllowNull] string X) // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "[AllowNull] string X").WithLocation(5, 10), // (10,26): warning CS8625: Cannot convert null literal to non-nullable reference type. // b = b with { X = null }; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 26), // (11,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(11, 9)); } [Fact, WorkItem(44691, "https://github.com/dotnet/roslyn/issues/44691")] public void WithExpr_NullableAnalysis_08() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B([property: AllowNull][AllowNull] string X) { static void M1(B b) { b.X.ToString(); b = b with { X = null }; b.X.ToString(); // 1 b = new B((string?)null); b.X.ToString(); } }"; var comp = CreateCompilation(new[] { src, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(11, 9)); } [Fact] public void WithExpr_NullableAnalysis_09() { var src = @" #nullable enable record B(string? X, string? Y) { static void M1(B b1) { B b2 = b1 with { X = ""hello"" }; B b3 = b1 with { Y = ""world"" }; B b4 = b2 with { Y = ""world"" }; b1.X.ToString(); // 1 b1.Y.ToString(); // 2 b2.X.ToString(); b2.Y.ToString(); // 3 b3.X.ToString(); // 4 b3.Y.ToString(); b4.X.ToString(); b4.Y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // b1.X.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1.X").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // b1.Y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1.Y").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // b2.Y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b2.Y").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // b3.X.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b3.X").WithLocation(15, 9)); } [Fact] public void WithExpr_NullableAnalysis_10() { var src = @" #nullable enable record B(string? X, string? Y) { static void M1(B b1) { string? local = ""hello""; _ = b1 with { X = local = null, Y = local.ToString() // 1 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,17): warning CS8602: Dereference of a possibly null reference. // Y = local.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "local").WithLocation(11, 17)); } [Fact] public void WithExpr_NullableAnalysis_11() { var src = @" #nullable enable record B(string X, string Y) { static string M0(out string? s) { s = null; return ""hello""; } static void M1(B b1) { string? local = ""world""; _ = b1 with { X = M0(out local), Y = local // 1 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,17): warning CS8601: Possible null reference assignment. // Y = local // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "local").WithLocation(13, 17)); } [Fact] public void WithExpr_NullableAnalysis_VariantClone() { var src = @" #nullable enable record A { public string? Y { get; init; } public string? Z { get; init; } } record B(string? X) : A { public new string Z { get; init; } = ""zed""; static void M1(B b1) { b1.Z.ToString(); (b1 with { Y = ""hello"" }).Y.ToString(); (b1 with { Y = ""hello"" }).Z.ToString(); } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_NullableClone() { var src = @" #nullable enable record B(string? X) { public B? Clone() => new B(X); static void M1(B b1) { _ = b1 with { X = null }; // 1 (b1 with { X = null }).ToString(); // 2 } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,21): warning CS8602: Dereference of a possibly null reference. // _ = b1 with { X = null }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(10, 21), // (11,18): warning CS8602: Dereference of a possibly null reference. // (b1 with { X = null }).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(11, 18)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_MaybeNullClone() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B(string? X) { [return: MaybeNull] public B Clone() => new B(X); static void M1(B b1) { _ = b1 with { }; _ = b1 with { X = null }; // 1 (b1 with { X = null }).ToString(); // 2 } } "; var comp = CreateCompilation(new[] { src, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (13,21): warning CS8602: Dereference of a possibly null reference. // _ = b1 with { X = null }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(13, 21), // (14,18): warning CS8602: Dereference of a possibly null reference. // (b1 with { X = null }).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(14, 18)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_NotNullClone() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B(string? X) { [return: NotNull] public B? Clone() => new B(X); static void M1(B b1) { _ = b1 with { }; _ = b1 with { X = null }; (b1 with { X = null }).ToString(); } } "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_NullableClone_NoInitializers() { var src = @" #nullable enable record B(string? X) { public B? Clone() => new B(X); static void M1(B b1) { _ = b1 with { }; (b1 with { }).ToString(); // 1 } } "; var comp = CreateCompilation(src); // Note: we expect to give a warning on `// 1`, but do not currently // due to limitations of object initializer analysis. // Tracking in https://github.com/dotnet/roslyn/issues/44759 comp.VerifyDiagnostics(); } [Fact] public void WithExprNominalRecord() { var src = @" using System; record C { public int X { get; set; } public string Y { get; init; } public long Z; public event Action E; public C() { } public C(C other) { X = other.X; Y = other.Y; Z = other.Z; E = other.E; } public static void Main() { var c = new C() { X = 1, Y = ""2"", Z = 3, E = () => { } }; var c2 = c with {}; Console.WriteLine(c.Equals(c2)); Console.WriteLine(ReferenceEquals(c, c2)); Console.WriteLine(c2.X); Console.WriteLine(c2.Y); Console.WriteLine(c2.Z); Console.WriteLine(ReferenceEquals(c.E, c2.E)); var c3 = c with { Y = ""3"", X = 2 }; Console.WriteLine(c.Y); Console.WriteLine(c3.Y); Console.WriteLine(c.X); Console.WriteLine(c3.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" True False 1 2 3 True 2 3 1 2").VerifyDiagnostics(); } [Fact] public void WithExprNominalRecord2() { var comp1 = CreateCompilation(@" public record C { public int X { get; set; } public string Y { get; init; } public long Z; public C() { } public C(C other) { X = other.X; Y = other.Y; Z = other.Z; } }"); var verifier = CompileAndVerify(@" class D { public C M(C c) => c with { X = 5, Y = ""a"", Z = 2, }; }", references: new[] { comp1.EmitToImageReference() }).VerifyDiagnostics(); verifier.VerifyIL("D.M", @" { // Code size 33 (0x21) .maxstack 3 IL_0000: ldarg.1 IL_0001: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0006: dup IL_0007: ldc.i4.5 IL_0008: callvirt ""void C.X.set"" IL_000d: dup IL_000e: ldstr ""a"" IL_0013: callvirt ""void C.Y.init"" IL_0018: dup IL_0019: ldc.i4.2 IL_001a: conv.i8 IL_001b: stfld ""long C.Z"" IL_0020: ret }"); } [Fact] public void WithExprAssignToRef1() { var src = @" using System; record C(int Y) { private readonly int[] _a = new[] { 0 }; public ref int X => ref _a[0]; public static void Main() { var c = new C(0) { X = 5 }; Console.WriteLine(c.X); c = c with { X = 1 }; Console.WriteLine(c.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 5 1").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 51 (0x33) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: newobj ""C..ctor(int)"" IL_0006: dup IL_0007: callvirt ""ref int C.X.get"" IL_000c: ldc.i4.5 IL_000d: stind.i4 IL_000e: dup IL_000f: callvirt ""ref int C.X.get"" IL_0014: ldind.i4 IL_0015: call ""void System.Console.WriteLine(int)"" IL_001a: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_001f: dup IL_0020: callvirt ""ref int C.X.get"" IL_0025: ldc.i4.1 IL_0026: stind.i4 IL_0027: callvirt ""ref int C.X.get"" IL_002c: ldind.i4 IL_002d: call ""void System.Console.WriteLine(int)"" IL_0032: ret }"); } [Fact] public void WithExprAssignToRef2() { var src = @" using System; record C(int Y) { private readonly int[] _a = new[] { 0 }; public ref int X { get => ref _a[0]; set { } } public static void Main() { var a = new[] { 0 }; var c = new C(0) { X = ref a[0] }; Console.WriteLine(c.X); c = c with { X = ref a[0] }; Console.WriteLine(c.X); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,9): error CS8147: Properties which return by reference cannot have set accessors // set { } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("C.X.set").WithLocation(9, 9), // (15,32): error CS1525: Invalid expression term 'ref' // var c = new C(0) { X = ref a[0] }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref a[0]").WithArguments("ref").WithLocation(15, 32), // (15,32): error CS1073: Unexpected token 'ref' // var c = new C(0) { X = ref a[0] }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(15, 32), // (17,26): error CS1073: Unexpected token 'ref' // c = c with { X = ref a[0] }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(17, 26) ); } [Fact] public void WithExpressionSameLHS() { var comp = CreateCompilation(@" record C(int X) { public static void Main() { var c = new C(0); c = c with { X = 1, X = 2}; } }"); comp.VerifyDiagnostics( // (7,29): error CS1912: Duplicate initialization of member 'X' // c = c with { X = 1, X = 2}; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(7, 29) ); } [Fact] public void WithExpr_ValEscape() { var text = @" using System; record R { public S1 Property { set { throw null; } } } class Program { static void Main() { var r = new R(); Span<int> local = stackalloc int[1]; _ = r with { Property = MayWrap(ref local) }; _ = new R() { Property = MayWrap(ref local) }; } static S1 MayWrap(ref Span<int> arg) { return default; } } ref struct S1 { public ref int this[int i] => throw null; } "; CreateCompilationWithMscorlibAndSpan(text).VerifyDiagnostics(); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Fact] public void Inheritance_01() { var source = @"record A { internal A() { } public object P1 { get; set; } internal object P2 { get; set; } protected internal object P3 { get; set; } protected object P4 { get; set; } private protected object P5 { get; set; } private object P6 { get; set; } } record B(object P1, object P2, object P3, object P4, object P5, object P6) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28), // (11,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(11, 39), // (11,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(11, 50), // (11,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(11, 61) ); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P6 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Fact] public void Inheritance_02() { var source = @"record A { internal A() { } private protected object P1 { get; set; } private object P2 { get; set; } private record B(object P1, object P2) : A { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,29): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // private record B(object P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(6, 29), // (6,40): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // private record B(object P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(6, 40) ); var actualMembers = GetProperties(comp, "A.B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type A.B.EqualityContract { get; }" }, actualMembers); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Theory] [InlineData(false)] [InlineData(true)] public void Inheritance_03(bool useCompilationReference) { var sourceA = @"public record A { public A() { } internal object P { get; set; } } public record B(object Q) : A { public B() : this(null) { } } record C1(object P, object Q) : B { }"; var comp = CreateCompilation(sourceA); AssertEx.Equal(new[] { "System.Type C1.EqualityContract { get; }" }, GetProperties(comp, "C1").ToTestDisplayStrings()); var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference(); var sourceB = @"record C2(object P, object Q) : B { }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,28): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record C2(object P, object Q) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 28) ); AssertEx.Equal(new[] { "System.Type C2.EqualityContract { get; }", "System.Object C2.P { get; init; }" }, GetProperties(comp, "C2").ToTestDisplayStrings()); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Fact] public void Inheritance_04() { var source = @"record A { internal A() { } public object P1 { get { return null; } set { } } public object P2 { get; init; } public object P3 { get; } public object P4 { set { } } public virtual object P5 { get; set; } public static object P6 { get; set; } public ref object P7 => throw null; } record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(12, 17), // (12,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(12, 28), // (12,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(12, 39), // (12,50): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'object' to match positional parameter 'P4'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "object", "P4").WithLocation(12, 50), // (12,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(12, 50), // (12,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(12, 61), // (12,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(12, 72), // (12,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(12, 72), // (12,83): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(12, 83)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_05() { var source = @"record A { internal A() { } public object P1 { get; set; } public int P2 { get; set; } } record B(int P1, object P2) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'int' to match positional parameter 'P1'. // record B(int P1, object P2) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "int", "P1").WithLocation(7, 14), // (7,14): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(int P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(7, 14), // (7,25): error CS8866: Record member 'A.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'. // record B(int P1, object P2) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("A.P2", "object", "P2").WithLocation(7, 25), // (7,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(int P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(7, 25)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_06() { var source = @"record A { internal int X { get; set; } internal int Y { set { } } internal int Z; } record B(int X, int Y, int Z) : A { } class Program { static void Main() { var b = new B(1, 2, 3); b.X = 4; b.Y = 5; b.Z = 6; ((A)b).X = 7; ((A)b).Y = 8; ((A)b).Z = 9; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14), // (7,21): error CS8866: Record member 'A.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'. // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("A.Y", "int", "Y").WithLocation(7, 21), // (7,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 21), // (7,24): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int Z").WithArguments("positional fields in records", "10.0").WithLocation(7, 24), // (7,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(7, 28)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_07() { var source = @"abstract record A { public abstract int X { get; } public virtual int Y { get; } } abstract record B1(int X, int Y) : A { } record B2(int X, int Y) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,24): error CS0546: 'B1.X.init': cannot override because 'A.X' does not have an overridable set accessor // abstract record B1(int X, int Y) : A Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("B1.X.init", "A.X").WithLocation(6, 24), // (6,31): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record B1(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(6, 31), // (9,15): error CS0546: 'B2.X.init': cannot override because 'A.X' does not have an overridable set accessor // record B2(int X, int Y) : A Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("B2.X.init", "A.X").WithLocation(9, 15), // (9,22): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B2(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(9, 22)); AssertEx.Equal(new[] { "System.Type B1.EqualityContract { get; }", "System.Int32 B1.X { get; init; }" }, GetProperties(comp, "B1").ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.Type B2.EqualityContract { get; }", "System.Int32 B2.X { get; init; }" }, GetProperties(comp, "B2").ToTestDisplayStrings()); var b1Ctor = comp.GetTypeByMetadataName("B1")!.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal("B1..ctor(System.Int32 X, System.Int32 Y)", b1Ctor.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, b1Ctor.DeclaredAccessibility); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_08() { var source = @"abstract record A { public abstract int X { get; } public virtual int Y { get; } public virtual int Z { get; } } abstract record B : A { public override abstract int Y { get; } } record C(int X, int Y, int Z) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,14): error CS0546: 'C.X.init': cannot override because 'A.X' does not have an overridable set accessor // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("C.X.init", "A.X").WithLocation(11, 14), // (11,21): error CS0546: 'C.Y.init': cannot override because 'B.Y' does not have an overridable set accessor // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.ERR_NoSetToOverride, "Y").WithArguments("C.Y.init", "B.Y").WithLocation(11, 21), // (11,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(11, 28)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; init; }", "System.Int32 C.Y { get; init; }" }, actualMembers); } [Fact, WorkItem(48947, "https://github.com/dotnet/roslyn/issues/48947")] public void Inheritance_09() { var source = @"abstract record C(int X, int Y) { public abstract int X { get; } public virtual int Y { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,23): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // abstract record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(1, 23), // (1,30): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(1, 30) ); NamedTypeSymbol c = comp.GetMember<NamedTypeSymbol>("C"); var actualMembers = c.GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; }", "System.Int32 C.X.get", "System.Int32 C.<Y>k__BackingField", "System.Int32 C.Y { get; }", "System.Int32 C.Y.get", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); var expectedMemberNames = new[] { ".ctor", "get_EqualityContract", "EqualityContract", "X", "get_X", "<Y>k__BackingField", "Y", "get_Y", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, c.GetPublicSymbol().MemberNames); var expectedCtors = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)", }; AssertEx.Equal(expectedCtors, c.GetPublicSymbol().Constructors.ToTestDisplayStrings()); } [Fact] public void Inheritance_10() { var source = @"using System; interface IA { int X { get; } } interface IB { int Y { get; } } record C(int X, int Y) : IA, IB { } class Program { static void Main() { var c = new C(1, 2); Console.WriteLine(""{0}, {1}"", c.X, c.Y); Console.WriteLine(""{0}, {1}"", ((IA)c).X, ((IB)c).Y); } }"; CompileAndVerify(source, expectedOutput: @"1, 2 1, 2").VerifyDiagnostics(); } [Fact] public void Inheritance_11() { var source = @"interface IA { int X { get; } } interface IB { object Y { get; set; } } record C(object X, object Y) : IA, IB { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,32): error CS0738: 'C' does not implement interface member 'IA.X'. 'C.X' cannot implement 'IA.X' because it does not have the matching return type of 'int'. // record C(object X, object Y) : IA, IB Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "IA").WithArguments("C", "IA.X", "C.X", "int").WithLocation(9, 32), // (9,36): error CS8854: 'C' does not implement interface member 'IB.Y.set'. 'C.Y.init' cannot implement 'IB.Y.set'. // record C(object X, object Y) : IA, IB Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "IB").WithArguments("C", "IB.Y.set", "C.Y.init").WithLocation(9, 36) ); } [Fact] public void Inheritance_12() { var source = @"record A { public object X { get; } public object Y { get; } } record B(object X, object Y) : A { public object X { get; } public object Y { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(6, 17), // (6,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(6, 27), // (8,19): warning CS0108: 'B.X' hides inherited member 'A.X'. Use the new keyword if hiding was intended. // public object X { get; } Diagnostic(ErrorCode.WRN_NewRequired, "X").WithArguments("B.X", "A.X").WithLocation(8, 19), // (9,19): warning CS0108: 'B.Y' hides inherited member 'A.Y'. Use the new keyword if hiding was intended. // public object Y { get; } Diagnostic(ErrorCode.WRN_NewRequired, "Y").WithArguments("B.Y", "A.Y").WithLocation(9, 19)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.X { get; }", "System.Object B.Y { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_13() { var source = @"record A(object X, object Y) { internal A() : this(null, null) { } } record B(object X, object Y) : A { public object X { get; } public object Y { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 17), // (5,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 27), // (7,19): warning CS0108: 'B.X' hides inherited member 'A.X'. Use the new keyword if hiding was intended. // public object X { get; } Diagnostic(ErrorCode.WRN_NewRequired, "X").WithArguments("B.X", "A.X").WithLocation(7, 19), // (8,19): warning CS0108: 'B.Y' hides inherited member 'A.Y'. Use the new keyword if hiding was intended. // public object Y { get; } Diagnostic(ErrorCode.WRN_NewRequired, "Y").WithArguments("B.Y", "A.Y").WithLocation(8, 19)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.X { get; }", "System.Object B.Y { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_14() { var source = @"record A { public object P1 { get; } public object P2 { get; } public object P3 { get; } public object P4 { get; } } record B : A { public new int P1 { get; } public new int P2 { get; } } record C(object P1, int P2, object P3, int P4) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,17): error CS8866: Record member 'B.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("B.P1", "object", "P1").WithLocation(13, 17), // (13,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(13, 17), // (13,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(13, 25), // (13,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(13, 36), // (13,44): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'int' to match positional parameter 'P4'. // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "int", "P4").WithLocation(13, 44), // (13,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(13, 44)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_15() { var source = @"record C(int P1, object P2) { public object P1 { get; set; } public int P2 { get; set; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,14): error CS8866: Record member 'C.P1' must be a readable instance property or field of type 'int' to match positional parameter 'P1'. // record C(int P1, object P2) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("C.P1", "int", "P1").WithLocation(1, 14), // (1,14): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(int P1, object P2) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 14), // (1,25): error CS8866: Record member 'C.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'. // record C(int P1, object P2) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("C.P2", "object", "P2").WithLocation(1, 25), // (1,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(int P1, object P2) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 25)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P1 { get; set; }", "System.Int32 C.P2 { get; set; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_16() { var source = @"record A { public int P1 { get; } public int P2 { get; } public int P3 { get; } public int P4 { get; } } record B(object P1, int P2, object P3, int P4) : A { public new object P1 { get; } public new object P2 { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(8, 17), // (8,25): error CS8866: Record member 'B.P2' must be a readable instance property or field of type 'int' to match positional parameter 'P2'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("B.P2", "int", "P2").WithLocation(8, 25), // (8,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(8, 25), // (8,36): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(8, 36), // (8,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(8, 36), // (8,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(8, 44)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P1 { get; }", "System.Object B.P2 { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_17() { var source = @"record A { public object P1 { get; } public object P2 { get; } public object P3 { get; } public object P4 { get; } } record B(object P1, int P2, object P3, int P4) : A { public new int P1 { get; } public new int P2 { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,17): error CS8866: Record member 'B.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("B.P1", "object", "P1").WithLocation(8, 17), // (8,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(8, 17), // (8,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(8, 25), // (8,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(8, 36), // (8,44): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'int' to match positional parameter 'P4'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "int", "P4").WithLocation(8, 44), // (8,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(8, 44)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Int32 B.P1 { get; }", "System.Int32 B.P2 { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_18() { var source = @"record C(object P1, object P2, object P3, object P4, object P5) { public object P1 { get { return null; } set { } } public object P2 { get; } public object P3 { set { } } public static object P4 { get; set; } public ref object P5 => throw null; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (1,39): error CS8866: Record member 'C.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("C.P3", "object", "P3").WithLocation(1, 39), // (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39), // (1,50): error CS8866: Record member 'C.P4' must be a readable instance property or field of type 'object' to match positional parameter 'P4'. // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("C.P4", "object", "P4").WithLocation(1, 50), // (1,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(1, 50), // (1,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(1, 61)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P1 { get; set; }", "System.Object C.P2 { get; }", "System.Object C.P3 { set; }", "System.Object C.P4 { get; set; }", "ref System.Object C.P5 { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_19() { var source = @"#pragma warning disable 8618 #nullable enable record A { internal A() { } public object P1 { get; } public dynamic[] P2 { get; } public object? P3 { get; } public object[] P4 { get; } public (int X, int Y) P5 { get; } public (int, int)[] P6 { get; } public nint P7 { get; } public System.UIntPtr[] P8 { get; } } record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,18): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(15, 18), // (15,31): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(15, 31), // (15,42): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(15, 42), // (15,56): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(15, 56), // (15,71): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(15, 71), // (15,92): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(15, 92), // (15,110): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(15, 110), // (15,122): warning CS8907: Parameter 'P8' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P8").WithArguments("P8").WithLocation(15, 122) ); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_20() { var source = @"#pragma warning disable 8618 #nullable enable record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) { public object P1 { get; } public dynamic[] P2 { get; } public object? P3 { get; } public object[] P4 { get; } public (int X, int Y) P5 { get; } public (int, int)[] P6 { get; } public nint P7 { get; } public System.UIntPtr[] P8 { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,18): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(3, 18), // (3,31): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(3, 31), // (3,42): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(3, 42), // (3,56): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(3, 56), // (3,71): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(3, 71), // (3,92): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(3, 92), // (3,110): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(3, 110), // (3,122): warning CS8907: Parameter 'P8' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P8").WithArguments("P8").WithLocation(3, 122) ); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P1 { get; }", "dynamic[] C.P2 { get; }", "System.Object? C.P3 { get; }", "System.Object[] C.P4 { get; }", "(System.Int32 X, System.Int32 Y) C.P5 { get; }", "(System.Int32, System.Int32)[] C.P6 { get; }", "nint C.P7 { get; }", "System.UIntPtr[] C.P8 { get; }" }; AssertEx.Equal(expectedMembers, actualMembers); } [Theory] [InlineData(false)] [InlineData(true)] public void Inheritance_21(bool useCompilationReference) { var sourceA = @"public record A { public object P1 { get; } internal object P2 { get; } } public record B : A { internal new object P1 { get; } public new object P2 { get; } }"; var comp = CreateCompilation(sourceA); var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference(); var sourceB = @"record C(object P1, object P2) : B { } class Program { static void Main() { var c = new C(1, 2); System.Console.WriteLine(""({0}, {1})"", c.P1, c.P2); } }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); var verifier = CompileAndVerify(comp, expectedOutput: "(, )").VerifyDiagnostics( // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28) ); verifier.VerifyIL("C..ctor(object, object)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""B..ctor()"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(C)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ret }"); verifier.VerifyIL("Program.Main", @"{ // Code size 41 (0x29) .maxstack 3 .locals init (C V_0) //c IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: ldc.i4.2 IL_0007: box ""int"" IL_000c: newobj ""C..ctor(object, object)"" IL_0011: stloc.0 IL_0012: ldstr ""({0}, {1})"" IL_0017: ldloc.0 IL_0018: callvirt ""object A.P1.get"" IL_001d: ldloc.0 IL_001e: callvirt ""object B.P2.get"" IL_0023: call ""void System.Console.WriteLine(string, object, object)"" IL_0028: ret }"); } [Fact] public void Inheritance_22() { var source = @"record A { public ref object P1 => throw null; public object P2 => throw null; } record B : A { public new object P1 => throw null; public new ref object P2 => throw null; } record C(object P1, object P2) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28) ); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_23() { var source = @"record A { public static object P1 { get; } public object P2 { get; } } record B : A { public new object P1 { get; } public new static object P2 { get; } } record C(object P1, object P2) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): error CS8866: Record member 'B.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'. // record C(object P1, object P2) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("B.P2", "object", "P2").WithLocation(11, 28), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_24() { var source = @"record A { public object get_P() => null; public object set_Q() => null; } record B(object P, object Q) : A { } record C(object P) { public object get_P() => null; public object set_Q() => null; }"; var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? source : new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics( // (9,17): error CS0082: Type 'C' already reserves a member called 'get_P' with the same parameter types // record C(object P) Diagnostic(ErrorCode.ERR_MemberReserved, "P").WithArguments("get_P", "C").WithLocation(9, 17)); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); var expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses ? "B B." + WellKnownMemberNames.CloneMethodName + "()" : "A B." + WellKnownMemberNames.CloneMethodName + "()"; var expectedMembers = new[] { "B..ctor(System.Object P, System.Object Q)", "System.Type B.EqualityContract.get", "System.Type B.EqualityContract { get; }", "System.Object B.<P>k__BackingField", "System.Object B.P.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.P.init", "System.Object B.P { get; init; }", "System.Object B.<Q>k__BackingField", "System.Object B.Q.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Q.init", "System.Object B.Q { get; init; }", "System.String B.ToString()", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", expectedClone, "B..ctor(B original)", "void B.Deconstruct(out System.Object P, out System.Object Q)" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings()); expectedMembers = new[] { "C..ctor(System.Object P)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.Object C.<P>k__BackingField", "System.Object C.P.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.P.init", "System.Object C.P { get; init; }", "System.Object C.get_P()", "System.Object C.set_Q()", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Object P)" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings()); } [Fact] public void Inheritance_25() { var sourceA = @"public record A { public class P1 { } internal object P2 = 2; public int P3(object o) => 3; internal int P4<T>(T t) => 4; }"; var sourceB = @"record B(object P1, object P2, object P3, object P4) : A { }"; var comp = CreateCompilation(new[] { sourceA, sourceB, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "object", "P1").WithLocation(1, 17), // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,21): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object P2").WithArguments("positional fields in records", "10.0").WithLocation(1, 21), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (1,39): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(1, 39), // (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P4 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); comp = CreateCompilation(sourceA); var refA = comp.EmitToImageReference(); comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "object", "P1").WithLocation(1, 17), // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,39): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(1, 39), // (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39)); actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P2 { get; init; }", "System.Object B.P4 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_26() { var sourceA = @"public record A { internal const int P = 4; }"; var sourceB = @"record B(object P) : A { }"; var comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (1,17): error CS8866: Record member 'A.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'. // record B(object P) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("A.P", "object", "P").WithLocation(1, 17), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B(object P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); comp = CreateCompilation(sourceA); var refA = comp.EmitToImageReference(); comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P { get; init; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [Fact] public void Inheritance_27() { var source = @"record A { public object P { get; } public object Q { get; set; } } record B(object get_P, object set_Q) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.get_P { get; init; }", "System.Object B.set_Q { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_28() { var source = @"interface I { object P { get; } } record A : I { object I.P => null; } record B(object P) : A { } record C(object P) : I { object I.P => null; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P { get; init; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P { get; init; }", "System.Object C.I.P { get; }" }, GetProperties(comp, "C").ToTestDisplayStrings()); } [Fact] public void Inheritance_29() { var sourceA = @"Public Class A Public Property P(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Property Q(x As Object, y As Object) As Object Get Return Nothing End Get Set End Set End Property End Class "; var compA = CreateVisualBasicCompilation(sourceA); compA.VerifyDiagnostics(); var refA = compA.EmitToImageReference(); var sourceB = @"record B(object P, object Q) : A { object P { get; } }"; var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'B.Equals(A?)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(1, 8), // (1,8): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,8): error CS8867: No accessible copy constructor found in base type 'A'. // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(1, 8), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B(object P, object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,32): error CS8864: Records may only inherit from object or another record // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(1, 32) ); var actualMembers = GetProperties(compB, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.Q { get; init; }", "System.Object B.P { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_30() { var sourceA = @"Public Class A Public ReadOnly Overloads Property P() As Object Get Return Nothing End Get End Property Public ReadOnly Overloads Property P(o As Object) As Object Get Return Nothing End Get End Property Public Overloads Property Q(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Overloads Property Q() As Object Get Return Nothing End Get Set End Set End Property End Class "; var compA = CreateVisualBasicCompilation(sourceA); compA.VerifyDiagnostics(); var refA = compA.EmitToImageReference(); var sourceB = @"record B(object P, object Q) : A { }"; var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'B.Equals(A?)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(1, 8), // (1,8): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,8): error CS8867: No accessible copy constructor found in base type 'A'. // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(1, 8), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B(object P, object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record B(object P, object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27), // (1,32): error CS8864: Records may only inherit from object or another record // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(1, 32) ); var actualMembers = GetProperties(compB, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_31() { var sourceA = @"Public Class A Public ReadOnly Property P() As Object Get Return Nothing End Get End Property Public Property Q(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Property R(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Sub New(a as A) End Sub End Class Public Class B Inherits A Public ReadOnly Overloads Property P(o As Object) As Object Get Return Nothing End Get End Property Public Overloads Property Q() As Object Get Return Nothing End Get Set End Set End Property Public Overloads Property R(x As Object, y As Object) As Object Get Return Nothing End Get Set End Set End Property Public Sub New(b as B) MyBase.New(b) End Sub End Class "; var compA = CreateVisualBasicCompilation(sourceA); compA.VerifyDiagnostics(); var refA = compA.EmitToImageReference(); var sourceB = @"record C(object P, object Q, object R) : B { }"; var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (1,8): error CS0115: 'C.EqualityContract': no suitable method found to override // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'C.Equals(B?)': no suitable method found to override // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.Equals(B?)").WithLocation(1, 8), // (1,8): error CS0115: 'C.PrintMembers(StringBuilder)': no suitable method found to override // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'b' of 'B.B(B)' // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("b", "B.B(B)").WithLocation(1, 8), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27), // (1,42): error CS8864: Records may only inherit from object or another record // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_BadRecordBase, "B").WithLocation(1, 42) ); var actualMembers = GetProperties(compB, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.R { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_32() { var source = @"record A { public virtual object P1 { get; } public virtual object P2 { get; set; } public virtual object P3 { get; protected init; } public virtual object P4 { protected get; init; } public virtual object P5 { init { } } public virtual object P6 { set { } } public static object P7 { get; set; } } record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28), // (11,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(11, 39), // (11,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(11, 50), // (11,61): error CS8866: Record member 'A.P5' must be a readable instance property or field of type 'object' to match positional parameter 'P5'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P5").WithArguments("A.P5", "object", "P5").WithLocation(11, 61), // (11,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(11, 61), // (11,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(11, 72), // (11,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(11, 72), // (11,83): error CS8866: Record member 'A.P7' must be a readable instance property or field of type 'object' to match positional parameter 'P7'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P7").WithArguments("A.P7", "object", "P7").WithLocation(11, 83), // (11,83): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(11, 83)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_33() { var source = @"abstract record A { public abstract object P1 { get; } public abstract object P2 { get; set; } public abstract object P3 { get; protected init; } public abstract object P4 { protected get; init; } public abstract object P5 { init; } public abstract object P6 { set; } } record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,8): error CS0534: 'B' does not implement inherited abstract member 'A.P6.set' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P6.set").WithLocation(10, 8), // (10,8): error CS0534: 'B' does not implement inherited abstract member 'A.P5.init' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P5.init").WithLocation(10, 8), // (10,17): error CS0546: 'B.P1.init': cannot override because 'A.P1' does not have an overridable set accessor // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_NoSetToOverride, "P1").WithArguments("B.P1.init", "A.P1").WithLocation(10, 17), // (10,28): error CS8853: 'B.P2' must match by init-only of overridden member 'A.P2' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "P2").WithArguments("B.P2", "A.P2").WithLocation(10, 28), // (10,39): error CS0507: 'B.P3.init': cannot change access modifiers when overriding 'protected' inherited member 'A.P3.init' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "P3").WithArguments("B.P3.init", "protected", "A.P3.init").WithLocation(10, 39), // (10,50): error CS0507: 'B.P4.get': cannot change access modifiers when overriding 'protected' inherited member 'A.P4.get' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "P4").WithArguments("B.P4.get", "protected", "A.P4.get").WithLocation(10, 50), // (10,61): error CS8866: Record member 'A.P5' must be a readable instance property or field of type 'object' to match positional parameter 'P5'. // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P5").WithArguments("A.P5", "object", "P5").WithLocation(10, 61), // (10,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(10, 61), // (10,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'. // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(10, 72), // (10,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(10, 72)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P1 { get; init; }", "System.Object B.P2 { get; init; }", "System.Object B.P3 { get; init; }", "System.Object B.P4 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_34() { var source = @"abstract record A { public abstract object P1 { get; init; } public virtual object P2 { get; init; } } record B(string P1, string P2) : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,8): error CS0534: 'B' does not implement inherited abstract member 'A.P1.init' // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P1.init").WithLocation(6, 8), // (6,8): error CS0534: 'B' does not implement inherited abstract member 'A.P1.get' // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P1.get").WithLocation(6, 8), // (6,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'string' to match positional parameter 'P1'. // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "string", "P1").WithLocation(6, 17), // (6,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(string P1, string P2) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(6, 17), // (6,28): error CS8866: Record member 'A.P2' must be a readable instance property or field of type 'string' to match positional parameter 'P2'. // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("A.P2", "string", "P2").WithLocation(6, 28), // (6,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(string P1, string P2) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(6, 28)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_35() { var source = @"using static System.Console; abstract record A(object X, object Y) { public abstract object X { get; } public abstract object Y { get; init; } } record B(object X, object Y) : A(X, Y) { public override object X { get; } = X; } class Program { static void Main() { B b = new B(1, 2); A a = b; WriteLine((b.X, b.Y)); WriteLine((a.X, a.Y)); var (x, y) = b; WriteLine((x, y)); (x, y) = a; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.Y { get; init; }", "System.Object B.X { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"(1, 2) (1, 2) (1, 2) (1, 2)").VerifyDiagnostics( // (2,26): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 26), // (2,36): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(2, 36) ); verifier.VerifyIL("A..ctor(object, object)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A..ctor(A)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("A.GetHashCode()", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type A.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ret }"); verifier.VerifyIL("B..ctor(object, object)", @"{ // Code size 23 (0x17) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.2 IL_0002: stfld ""object B.<Y>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: stfld ""object B.<X>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldarg.1 IL_0010: ldarg.2 IL_0011: call ""A..ctor(object, object)"" IL_0016: ret }"); verifier.VerifyIL("B..ctor(B)", @"{ // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""A..ctor(A)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object B.<Y>k__BackingField"" IL_000e: stfld ""object B.<Y>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object B.<X>k__BackingField"" IL_001a: stfld ""object B.<X>k__BackingField"" IL_001f: ret }"); verifier.VerifyIL("B.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 64 (0x40) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_003e IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: brfalse.s IL_003c IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""object B.<Y>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""object B.<Y>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0023: brfalse.s IL_003c IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_002a: ldarg.0 IL_002b: ldfld ""object B.<X>k__BackingField"" IL_0030: ldarg.1 IL_0031: ldfld ""object B.<X>k__BackingField"" IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_003b: ret IL_003c: ldc.i4.0 IL_003d: ret IL_003e: ldc.i4.1 IL_003f: ret }"); verifier.VerifyIL("B.GetHashCode()", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""object B.<Y>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_001c: add IL_001d: ldc.i4 0xa5555529 IL_0022: mul IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0028: ldarg.0 IL_0029: ldfld ""object B.<X>k__BackingField"" IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0033: add IL_0034: ret }"); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_36() { var source = @"using static System.Console; abstract record A { public abstract object X { get; init; } } abstract record B : A { public abstract object Y { get; init; } } record C(object X, object Y) : B; class Program { static void Main() { C c = new C(1, 2); B b = c; A a = c; WriteLine((c.X, c.Y)); WriteLine((b.X, b.Y)); WriteLine(a.X); var (x, y) = c; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.X { get; init; }", "System.Object C.Y { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"(1, 2) (1, 2) 1 (1, 2)").VerifyDiagnostics(); verifier.VerifyIL("A..ctor()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A..ctor(A)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("A.GetHashCode()", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type A.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ret }"); verifier.VerifyIL("B..ctor()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""A..ctor()"" IL_0006: ret }"); verifier.VerifyIL("B..ctor(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""A..ctor(A)"" IL_0007: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); verifier.VerifyIL("B.GetHashCode()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(object, object)", @"{ // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""object C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""object C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: call ""B..ctor()"" IL_0014: ret }"); verifier.VerifyIL("C..ctor(C)", @"{ // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<X>k__BackingField"" IL_000e: stfld ""object C.<X>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<Y>k__BackingField"" IL_001a: stfld ""object C.<Y>k__BackingField"" IL_001f: ret }"); verifier.VerifyIL("C.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object B.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 64 (0x40) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_003e IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_003c IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""object C.<X>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""object C.<X>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0023: brfalse.s IL_003c IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_002a: ldarg.0 IL_002b: ldfld ""object C.<Y>k__BackingField"" IL_0030: ldarg.1 IL_0031: ldfld ""object C.<Y>k__BackingField"" IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_003b: ret IL_003c: ldc.i4.0 IL_003d: ret IL_003e: ldc.i4.1 IL_003f: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int B.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""object C.<X>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_001c: add IL_001d: ldc.i4 0xa5555529 IL_0022: mul IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0028: ldarg.0 IL_0029: ldfld ""object C.<Y>k__BackingField"" IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0033: add IL_0034: ret }"); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_37() { var source = @"using static System.Console; abstract record A(object X, object Y) { public abstract object X { get; init; } public virtual object Y { get; init; } } abstract record B(object X, object Y) : A(X, Y) { public override abstract object X { get; init; } public override abstract object Y { get; init; } } record C(object X, object Y) : B(X, Y); class Program { static void Main() { C c = new C(1, 2); B b = c; A a = c; WriteLine((c.X, c.Y)); WriteLine((b.X, b.Y)); WriteLine((a.X, a.Y)); var (x, y) = c; WriteLine((x, y)); (x, y) = b; WriteLine((x, y)); (x, y) = a; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.X { get; init; }", "System.Object C.Y { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"(1, 2) (1, 2) (1, 2) (1, 2) (1, 2) (1, 2)").VerifyDiagnostics( // (2,26): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 26), // (2,36): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(2, 36) ); verifier.VerifyIL("A..ctor(object, object)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A..ctor(A)", @"{ // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""object A.<Y>k__BackingField"" IL_000d: stfld ""object A.<Y>k__BackingField"" IL_0012: ret }"); verifier.VerifyIL("A.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""object A.<Y>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""object A.<Y>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("A.GetHashCode()", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type A.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ldc.i4 0xa5555529 IL_0015: mul IL_0016: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""object A.<Y>k__BackingField"" IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0026: add IL_0027: ret }"); verifier.VerifyIL("B..ctor(object, object)", @"{ // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""A..ctor(object, object)"" IL_0008: ret }"); verifier.VerifyIL("B..ctor(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""A..ctor(A)"" IL_0007: ret }"); verifier.VerifyIL("B.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); verifier.VerifyIL("B.GetHashCode()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(object, object)", @"{ // Code size 23 (0x17) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""object C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""object C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldarg.1 IL_0010: ldarg.2 IL_0011: call ""B..ctor(object, object)"" IL_0016: ret }"); verifier.VerifyIL("C..ctor(C)", @"{ // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<X>k__BackingField"" IL_000e: stfld ""object C.<X>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<Y>k__BackingField"" IL_001a: stfld ""object C.<Y>k__BackingField"" IL_001f: ret }"); verifier.VerifyIL("C.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 64 (0x40) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_003e IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_003c IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""object C.<X>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""object C.<X>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0023: brfalse.s IL_003c IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_002a: ldarg.0 IL_002b: ldfld ""object C.<Y>k__BackingField"" IL_0030: ldarg.1 IL_0031: ldfld ""object C.<Y>k__BackingField"" IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_003b: ret IL_003c: ldc.i4.0 IL_003d: ret IL_003e: ldc.i4.1 IL_003f: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int B.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""object C.<X>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_001c: add IL_001d: ldc.i4 0xa5555529 IL_0022: mul IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0028: ldarg.0 IL_0029: ldfld ""object C.<Y>k__BackingField"" IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0033: add IL_0034: ret }"); } // Member in intermediate base that hides abstract property. Not supported. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_38() { var source = @"using static System.Console; abstract record A { public abstract object X { get; init; } public abstract object Y { get; init; } } abstract record B : A { public new void X() { } public new struct Y { } } record C(object X, object Y) : B; class Program { static void Main() { C c = new C(1, 2); A a = c; WriteLine((a.X, a.Y)); var (x, y) = c; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (9,21): error CS0533: 'B.X()' hides inherited abstract member 'A.X' // public new void X() { } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "X").WithArguments("B.X()", "A.X").WithLocation(9, 21), // (10,23): error CS0533: 'B.Y' hides inherited abstract member 'A.Y' // public new struct Y { } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Y").WithArguments("B.Y", "A.Y").WithLocation(10, 23), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.Y.get' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.Y.get").WithLocation(12, 8), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.X.get' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.X.get").WithLocation(12, 8), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.X.init' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.X.init").WithLocation(12, 8), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.Y.init' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.Y.init").WithLocation(12, 8), // (12,17): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'object' to match positional parameter 'X'. // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "object", "X").WithLocation(12, 17), // (12,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(object X, object Y) : B; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(12, 17), // (12,27): error CS8866: Record member 'B.Y' must be a readable instance property or field of type 'object' to match positional parameter 'Y'. // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("B.Y", "object", "Y").WithLocation(12, 27), // (12,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(object X, object Y) : B; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(12, 27)); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", }, GetProperties(comp, "C").ToTestDisplayStrings()); } // Member in intermediate base that hides abstract property. Not supported. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_39() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .property instance object P() { .get instance object A::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object) } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .method public abstract virtual instance object get_P() { } .method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } .class public abstract B extends A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void A::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class B A_1) { ldnull throw } .method public hidebysig specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .method public hidebysig instance object P() { ldnull ret } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"record CA(object P) : A; record CB(object P) : B; "; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,8): error CS0534: 'CB' does not implement inherited abstract member 'A.P.get' // record CB(object P) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "CB").WithArguments("CB", "A.P.get").WithLocation(2, 8), // (2,8): error CS0534: 'CB' does not implement inherited abstract member 'A.P.init' // record CB(object P) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "CB").WithArguments("CB", "A.P.init").WithLocation(2, 8), // (2,18): error CS8866: Record member 'B.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'. // record CB(object P) : B; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("B.P", "object", "P").WithLocation(2, 18), // (2,18): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record CB(object P) : B; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 18)); AssertEx.Equal(new[] { "System.Type CA.EqualityContract { get; }", "System.Object CA.P { get; init; }" }, GetProperties(comp, "CA").ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.Type CB.EqualityContract { get; }" }, GetProperties(comp, "CB").ToTestDisplayStrings()); } // Accessor names that do not match the property name. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_40() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::GetProperty1() } .property instance object P() { .get instance object A::GetProperty2() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::SetProperty2(object) } .method family virtual instance class [mscorlib]System.Type GetProperty1() { ldnull ret } .method public abstract virtual instance object GetProperty2() { } .method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) SetProperty2(object 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using static System.Console; record B(object P) : A { static void Main() { B b = new B(3); WriteLine(b.P); WriteLine(((A)b).P); b = new B(1) { P = 2 }; WriteLine(b.P); WriteLine(b.EqualityContract.Name); } }"; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"3 3 2 B").VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B"); Assert.Equal(2, actualMembers.Length); VerifyProperty(actualMembers[0], "System.Type B.EqualityContract { get; }", "GetProperty1", null); VerifyProperty(actualMembers[1], "System.Object B.P { get; init; }", "GetProperty2", "SetProperty2"); } // Accessor names that do not match the property name and are not valid C# names. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_41() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::'EqualityContract<>get'() } .property instance object P() { .get instance object A::'P<>get'() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::'P<>set'(object) } .method family virtual instance class [mscorlib]System.Type 'EqualityContract<>get'() { ldnull ret } .method public abstract virtual instance object 'P<>get'() { } .method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) 'P<>set'(object 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using static System.Console; record B(object P) : A { static void Main() { B b = new B(3); WriteLine(b.P); WriteLine(((A)b).P); b = new B(1) { P = 2 }; WriteLine(b.P); WriteLine(b.EqualityContract.Name); } }"; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"3 3 2 B").VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B"); Assert.Equal(2, actualMembers.Length); VerifyProperty(actualMembers[0], "System.Type B.EqualityContract { get; }", "EqualityContract<>get", null); VerifyProperty(actualMembers[1], "System.Object B.P { get; init; }", "P<>get", "P<>set"); } private static void VerifyProperty(Symbol symbol, string propertyDescription, string? getterName, string? setterName) { var property = (PropertySymbol)symbol; Assert.Equal(propertyDescription, symbol.ToTestDisplayString()); VerifyAccessor(property.GetMethod, getterName); VerifyAccessor(property.SetMethod, setterName); } private static void VerifyAccessor(MethodSymbol? accessor, string? name) { Assert.Equal(name, accessor?.Name); if (accessor is object) { Assert.True(accessor.HasSpecialName); foreach (var parameter in accessor.Parameters) { Assert.Same(accessor, parameter.ContainingSymbol); } } } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_42() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type modopt(int32) EqualityContract() { .get instance class [mscorlib]System.Type modopt(int32) A::get_EqualityContract() } .property instance object modopt(uint16) P() { .get instance object modopt(uint16) A::get_P() .set instance void modopt(uint8) modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object modopt(uint16)) } .method family virtual instance class [mscorlib]System.Type modopt(int32) get_EqualityContract() { ldnull ret } .method public abstract virtual instance object modopt(uint16) get_P() { } .method public abstract virtual instance void modopt(uint8) modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object modopt(uint16) 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using static System.Console; record B(object P) : A { static void Main() { B b = new B(3); WriteLine(b.P); WriteLine(((A)b).P); b = new B(1) { P = 2 }; WriteLine(b.P); WriteLine(b.EqualityContract.Name); } }"; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"3 3 2 B").VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B"); Assert.Equal(2, actualMembers.Length); var property = (PropertySymbol)actualMembers[0]; Assert.Equal("System.Type modopt(System.Int32) B.EqualityContract { get; }", property.ToTestDisplayString()); verifyReturnType(property.GetMethod, CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_Int32))); property = (PropertySymbol)actualMembers[1]; Assert.Equal("System.Object modopt(System.UInt16) B.P { get; init; }", property.ToTestDisplayString()); verifyReturnType(property.GetMethod, CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_UInt16))); verifyReturnType(property.SetMethod, CSharpCustomModifier.CreateRequired(comp.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsExternalInit)), CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_Byte))); verifyParameterType(property.SetMethod, CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_UInt16))); static void verifyReturnType(MethodSymbol method, params CustomModifier[] expectedModifiers) { var returnType = method.ReturnTypeWithAnnotations; Assert.True(method.OverriddenMethod.ReturnTypeWithAnnotations.Equals(returnType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); AssertEx.Equal(expectedModifiers, returnType.CustomModifiers); } static void verifyParameterType(MethodSymbol method, params CustomModifier[] expectedModifiers) { var parameterType = method.Parameters[0].TypeWithAnnotations; Assert.True(method.OverriddenMethod.Parameters[0].TypeWithAnnotations.Equals(parameterType, TypeCompareKind.ConsiderEverything)); AssertEx.Equal(expectedModifiers, parameterType.CustomModifiers); } } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_43() { var source = @"#nullable enable record A { protected virtual System.Type? EqualityContract => null; } record B : A { static void Main() { var b = new B(); _ = b.EqualityContract.ToString(); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); Assert.Equal("System.Type! B.EqualityContract { get; }", GetProperties(comp, "B").Single().ToTestDisplayString(includeNonNullable: true)); } // No EqualityContract property on base. [Fact] public void Inheritance_44() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { ldnull throw } .property instance object P() { .get instance object A::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object) } .method public instance object get_P() { ldnull ret } .method public instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object 'value') { ret } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"record B : A; "; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B : A; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [Theory, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [InlineData(false)] [InlineData(true)] public void CopyCtor(bool useCompilationReference) { var sourceA = @"public record B(object N1, object N2) { }"; var compA = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? sourceA : new[] { sourceA, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); var verifierA = CompileAndVerify(compA, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifierA.VerifyIL("B..ctor(B)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""object B.<N1>k__BackingField"" IL_000d: stfld ""object B.<N1>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""object B.<N2>k__BackingField"" IL_0019: stfld ""object B.<N2>k__BackingField"" IL_001e: ret }"); var refA = useCompilationReference ? compA.ToMetadataReference() : compA.EmitToImageReference(); var sourceB = @"record C(object P1, object P2) : B(3, 4) { static void Main() { var c1 = new C(1, 2); System.Console.Write((c1.P1, c1.P2, c1.N1, c1.N2)); System.Console.Write("" ""); var c2 = new C(c1); System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2)); System.Console.Write("" ""); var c3 = c1 with { P1 = 10, N1 = 30 }; System.Console.Write((c3.P1, c3.P2, c3.N1, c3.N2)); } }"; var compB = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? sourceB : new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, targetFramework: TargetFramework.StandardLatest); var verifierB = CompileAndVerify(compB, expectedOutput: "(1, 2, 3, 4) (1, 2, 3, 4) (10, 2, 30, 4)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); // call base copy constructor B..ctor(B) verifierB.VerifyIL("C..ctor(C)", @" { // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ret }"); verifierA.VerifyIL($"B.{WellKnownMemberNames.CloneMethodName}()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""B..ctor(B)"" IL_0006: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithOtherOverload() { var source = @"public record B(object N1, object N2) { public B(C c) : this(30, 40) => throw null; } public record C(object P1, object P2) : B(3, 4) { static void Main() { var c1 = new C(1, 2); System.Console.Write((c1.P1, c1.P2, c1.N1, c1.N2)); System.Console.Write("" ""); var c2 = c1 with { P1 = 10, P2 = 20, N1 = 30, N2 = 40 }; System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 3, 4) (10, 20, 30, 40)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); // call base copy constructor B..ctor(B) verifier.VerifyIL("C..ctor(C)", @" { // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithObsoleteCopyConstructor() { var source = @"public record B(object N1, object N2) { [System.Obsolete(""Obsolete"", true)] public B(B b) { } } public record C(object P1, object P2) : B(3, 4) { } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithParamsCopyConstructor() { var source = @"public record B(object N1, object N2) { public B(B b, params int[] i) : this(30, 40) { } } public record C(object P1, object P2) : B(3, 4) { } "; var comp = CreateCompilation(source); var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().Where(m => m.Name == ".ctor").ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Object N1, System.Object N2)", "B..ctor(B b, params System.Int32[] i)", "B..ctor(B original)" }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithInitializers() { var source = @"public record C(object N1, object N2) { private int field = 42; public int Property = 43; }"; var comp = CreateCompilation(source); var verifier = CompileAndVerify(comp, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics( // (3,17): warning CS0414: The field 'C.field' is assigned but its value is never used // private int field = 42; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C.field").WithLocation(3, 17) ); verifier.VerifyIL("C..ctor(C)", @" { // Code size 55 (0x37) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""object C.<N1>k__BackingField"" IL_000d: stfld ""object C.<N1>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""object C.<N2>k__BackingField"" IL_0019: stfld ""object C.<N2>k__BackingField"" IL_001e: ldarg.0 IL_001f: ldarg.1 IL_0020: ldfld ""int C.field"" IL_0025: stfld ""int C.field"" IL_002a: ldarg.0 IL_002b: ldarg.1 IL_002c: ldfld ""int C.Property"" IL_0031: stfld ""int C.Property"" IL_0036: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_NotInRecordType() { var source = @"public class C { public object Property { get; set; } public int field = 42; public C(C c) { } } public class D : C { public int field2 = 43; public D(D d) : base(d) { } } "; var comp = CreateCompilation(source); var verifier = CompileAndVerify(comp).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: stfld ""int C.field"" IL_0008: ldarg.0 IL_0009: call ""object..ctor()"" IL_000e: ret }"); verifier.VerifyIL("D..ctor(D)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 43 IL_0003: stfld ""int D.field2"" IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: call ""C..ctor(C)"" IL_000f: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor() { var source = @"public record B(object N1, object N2) { } public record C(object P1, object P2) : B(0, 1) { public C(C c) // 1, 2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,12): error CS1729: 'B' does not contain a constructor that takes 0 arguments // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(6, 12), // (6,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(6, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject() { var source = @"public record C(int I) { public int I { get; set; } = 42; public C(C c) { } public static void Main() { var c = new C(1); c.I = 2; var c2 = new C(c); System.Console.Write((c.I, c2.I)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(2, 0)").VerifyDiagnostics( // (1,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // public record C(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(1, 21) ); verifier.VerifyIL("C..ctor(C)", @" { // Code size 9 (0x9) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: nop IL_0008: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject_WithFieldInitializer() { var source = @"public record C(int I) { public int I { get; set; } = 42; public int field = 43; public C(C c) { System.Console.Write("" RAN ""); } public static void Main() { var c = new C(1); c.I = 2; c.field = 100; System.Console.Write((c.I, c.field)); var c2 = new C(c); System.Console.Write((c2.I, c2.field)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(2, 100) RAN (0, 0)").VerifyDiagnostics( // (1,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // public record C(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(1, 21) ); verifier.VerifyIL("C..ctor(C)", @" { // Code size 20 (0x14) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: nop IL_0008: ldstr "" RAN "" IL_000d: call ""void System.Console.Write(string)"" IL_0012: nop IL_0013: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_DerivesFromObject_GivesParameterToBase() { var source = @" public record C(object I) { public C(C c) : base(1) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS1729: 'object' does not contain a constructor that takes 1 arguments // public C(C c) : base(1) { } Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("object", "1").WithLocation(4, 21), // (4,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : base(1) { } Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(4, 21) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_DerivesFromObject_WithSomeOtherConstructor() { var source = @" public record C(object I) { public C(int i) : this((object)null) { } public static void Main() { var c = new C((object)null); var c2 = new C(1); var c3 = new C(c); System.Console.Write(""RAN""); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "RAN", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int)", @" { // Code size 10 (0xa) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldnull IL_0002: call ""C..ctor(object)"" IL_0007: nop IL_0008: nop IL_0009: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject_UsesThis() { var source = @"public record C(int I) { public C(C c) : this(c.I) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : this(c.I) Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(3, 21) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefined_DerivesFromObject_UsesBase() { var source = @"public record C(int I) { public C(C c) : base() { System.Console.Write(""RAN ""); } public static void Main() { var c = new C(1); System.Console.Write(c.I); System.Console.Write("" ""); var c2 = c with { I = 2 }; System.Console.Write(c2.I); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "1 RAN 2", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 20 (0x14) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: nop IL_0008: ldstr ""RAN "" IL_000d: call ""void System.Console.Write(string)"" IL_0012: nop IL_0013: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_NoPositionalMembers() { var source = @"public record B(object N1, object N2) { } public record C(object P1) : B(0, 1) { public C(C c) // 1, 2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,12): error CS1729: 'B' does not contain a constructor that takes 0 arguments // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(6, 12), // (6,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(6, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_UsesThis() { var source = @"public record B(object N1, object N2) { } public record C(object P1, object P2) : B(0, 1) { public C(C c) : this(1, 2) // 1 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : this(1, 2) // 1 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(6, 21) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_UsesBase() { var source = @"public record B(int i) { } public record C(int j) : B(0) { public C(C c) : base(1) // 1 { } } #nullable enable public record D(int j) : B(0) { public D(D? d) : base(1) // 2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : base(1) // 1 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(6, 21), // (13,22): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public D(D? d) : base(1) // 2 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(13, 22) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefined_WithFieldInitializers() { var source = @"public record C(int I) { } public record D(int J) : C(1) { public int field = 42; public D(D d) : base(d) { System.Console.Write(""RAN ""); } public static void Main() { var d = new D(2); System.Console.Write((d.I, d.J, d.field)); System.Console.Write("" ""); var d2 = d with { I = 10, J = 20 }; System.Console.Write((d2.I, d2.J, d.field)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 42) RAN (10, 20, 42)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("D..ctor(D)", @" { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C..ctor(C)"" IL_0007: nop IL_0008: nop IL_0009: ldstr ""RAN "" IL_000e: call ""void System.Console.Write(string)"" IL_0013: nop IL_0014: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_Synthesized_WithFieldInitializers() { var source = @"public record C(int I) { } public record D(int J) : C(1) { public int field = 42; public static void Main() { var d = new D(2); System.Console.Write((d.I, d.J, d.field)); System.Console.Write("" ""); var d2 = d with { I = 10, J = 20 }; System.Console.Write((d2.I, d2.J, d.field)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 42) (10, 20, 42)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("D..ctor(D)", @" { // Code size 33 (0x21) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C..ctor(C)"" IL_0007: nop IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: ldfld ""int D.<J>k__BackingField"" IL_000f: stfld ""int D.<J>k__BackingField"" IL_0014: ldarg.0 IL_0015: ldarg.1 IL_0016: ldfld ""int D.field"" IL_001b: stfld ""int D.field"" IL_0020: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButPrivate() { var source = @"public record B(object N1, object N2) { private B(B b) { } } public record C(object P1, object P2) : B(0, 1) { private C(C c) : base(2, 3) { } // 1 } public record D(object P1, object P2) : B(0, 1) { private D(D d) : base(d) { } // 2 } public record E(object P1, object P2) : B(0, 1); // 3 "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,13): error CS8878: A copy constructor 'B.B(B)' must be public or protected because the record is not sealed. // private B(B b) { } Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "B").WithArguments("B.B(B)").WithLocation(3, 13), // (7,13): error CS8878: A copy constructor 'C.C(C)' must be public or protected because the record is not sealed. // private C(C c) : base(2, 3) { } // 1 Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "C").WithArguments("C.C(C)").WithLocation(7, 13), // (7,22): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // private C(C c) : base(2, 3) { } // 1 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(7, 22), // (11,13): error CS8878: A copy constructor 'D.D(D)' must be public or protected because the record is not sealed. // private D(D d) : base(d) { } // 2 Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "D").WithArguments("D.D(D)").WithLocation(11, 13), // (11,22): error CS0122: 'B.B(B)' is inaccessible due to its protection level // private D(D d) : base(d) { } // 2 Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("B.B(B)").WithLocation(11, 22), // (13,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record E(object P1, object P2) : B(0, 1); // 3 Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "E").WithArguments("B").WithLocation(13, 15) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_InaccessibleToCaller() { var sourceA = @"public record B(object N1, object N2) { internal B(B b) { } }"; var compA = CreateCompilation(sourceA); compA.VerifyDiagnostics( // (3,14): error CS8878: A copy constructor 'B.B(B)' must be public or protected because the record is not sealed. // internal B(B b) { } Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "B").WithArguments("B.B(B)").WithLocation(3, 14) ); var refA = compA.ToMetadataReference(); var sourceB = @" record C(object P1, object P2) : B(3, 4); // 1 "; var compB = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (2,8): error CS8867: No accessible copy constructor found in base type 'B'. // record C(object P1, object P2) : B(3, 4); // 1 Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 8) ); var sourceC = @" record C(object P1, object P2) : B(3, 4) { protected C(C c) : base(c) { } // 1, 2 } "; var compC = CreateCompilation(sourceC, references: new[] { refA }, parseOptions: TestOptions.Regular9); compC.VerifyDiagnostics( // (4,24): error CS0122: 'B.B(B)' is inaccessible due to its protection level // protected C(C c) : base(c) { } // 1, 2 Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("B.B(B)").WithLocation(4, 24) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_InaccessibleToCallerFromPE_WithIVT() { var sourceA = @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""AssemblyB"")] internal record B(object N1, object N2) { public B(B b) { } }"; var compA = CreateCompilation(new[] { sourceA, IsExternalInitTypeDefinition }, assemblyName: "AssemblyA", parseOptions: TestOptions.Regular9); var refA = compA.EmitToImageReference(); var sourceB = @" record C(int j) : B(3, 4); "; var compB = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB"); compB.VerifyDiagnostics(); var sourceC = @" record C(int j) : B(3, 4) { protected C(C c) : base(c) { } } "; var compC = CreateCompilation(sourceC, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB"); compC.VerifyDiagnostics(); var compB2 = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB2"); compB2.VerifyEmitDiagnostics( // (2,8): error CS0115: 'C.ToString()': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'C.GetHashCode()': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'C.EqualityContract': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'C.Equals(object?)': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'C.PrintMembers(StringBuilder)': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,19): error CS0122: 'B' is inaccessible due to its protection level // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_BadAccess, "B").WithArguments("B").WithLocation(2, 19), // (2,20): error CS0122: 'B.B(object, object)' is inaccessible due to its protection level // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_BadAccess, "(3, 4)").WithArguments("B.B(object, object)").WithLocation(2, 20) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [WorkItem(45012, "https://github.com/dotnet/roslyn/issues/45012")] public void CopyCtor_UserDefinedButPrivate_InSealedType() { var source = @"public record B(int i) { } public sealed record C(int j) : B(0) { private C(C c) : base(c) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var copyCtor = comp.GetMembers("C..ctor")[1]; Assert.Equal("C..ctor(C c)", copyCtor.ToTestDisplayString()); Assert.True(copyCtor.DeclaredAccessibility == Accessibility.Private); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [WorkItem(45012, "https://github.com/dotnet/roslyn/issues/45012")] public void CopyCtor_UserDefinedButInternal() { var source = @"public record B(object N1, object N2) { } public sealed record Sealed(object P1, object P2) : B(0, 1) { internal Sealed(Sealed s) : base(s) { } } public record Unsealed(object P1, object P2) : B(0, 1) { internal Unsealed(Unsealed s) : base(s) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,14): error CS8878: A copy constructor 'Unsealed.Unsealed(Unsealed)' must be public or protected because the record is not sealed. // internal Unsealed(Unsealed s) : base(s) Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "Unsealed").WithArguments("Unsealed.Unsealed(Unsealed)").WithLocation(12, 14) ); var sealedCopyCtor = comp.GetMembers("Sealed..ctor")[1]; Assert.Equal("Sealed..ctor(Sealed s)", sealedCopyCtor.ToTestDisplayString()); Assert.True(sealedCopyCtor.DeclaredAccessibility == Accessibility.Internal); var unsealedCopyCtor = comp.GetMembers("Unsealed..ctor")[1]; Assert.Equal("Unsealed..ctor(Unsealed s)", unsealedCopyCtor.ToTestDisplayString()); Assert.True(unsealedCopyCtor.DeclaredAccessibility == Accessibility.Internal); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_BaseHasRefKind() { var source = @"public record B(int i) { public B(ref B b) => throw null; // 1, not recognized as copy constructor } public record C(int j) : B(1) { protected C(C c) : base(c) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public B(ref B b) => throw null; // 1, not recognized as copy constructor Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "B").WithLocation(3, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_BaseHasRefKind_WithThisInitializer() { var source = @"public record B(int i) { public B(ref B b) : this(0) => throw null; // 1, not recognized as copy constructor } public record C(int j) : B(1) { protected C(C c) : base(c) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().Where(m => m.Name == ".ctor").ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Int32 i)", "B..ctor(ref B b)", "B..ctor(B original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithPrivateField() { var source = @"public record B(object N1, object N2) { private int field1 = 100; public int GetField1() => field1; } public record C(object P1, object P2) : B(3, 4) { private int field2 = 200; public int GetField2() => field2; static void Main() { var c1 = new C(1, 2); var c2 = new C(c1); System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2, c2.GetField1(), c2.GetField2())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 3, 4, 100, 200)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 44 (0x2c) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ldarg.0 IL_0020: ldarg.1 IL_0021: ldfld ""int C.field2"" IL_0026: stfld ""int C.field2"" IL_002b: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_MissingInMetadata() { // IL for `public record B { }` var ilSource = @" .class public auto ansi beforefieldinit B extends [mscorlib]System.Object { .method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { IL_0000: ldnull IL_0001: throw } // Removed copy constructor //.method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15) ); var source2 = @" public record C : B { public C(C c) { } }"; var comp2 = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics( // (4,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) { } Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(4, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_InaccessibleInMetadata() { // IL for `public record B { }` var ilSource = @" .class public auto ansi beforefieldinit B extends [mscorlib]System.Object { .method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { IL_0000: ldnull IL_0001: throw } // Inaccessible copy constructor .method private hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15) ); } [Fact, WorkItem(45077, "https://github.com/dotnet/roslyn/issues/45077")] public void CopyCtor_AmbiguitiesInMetadata() { // IL for a minimal `public record B { }` with injected copy constructors var ilSource_template = @" .class public auto ansi beforefieldinit B extends [mscorlib]System.Object { INJECT .method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldarg.0 IL_0001: newobj instance void B::.ctor(class B) IL_0006: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C : B { public static void Main() { var c = new C(); _ = c with { }; } }"; // We're going to inject various copy constructors into record B (at INJECT marker), and check which one is used // by derived record C // The RAN and THROW markers are shorthands for method bodies that print "RAN" and throw, respectively. // .ctor(B) vs. .ctor(modopt B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW "); // .ctor(modopt B) alone verify(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed RAN "); // .ctor(B) vs. .ctor(modreq B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int64) '' ) cil managed THROW "); // .ctor(modopt B) vs. .ctor(modreq B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int64) '' ) cil managed THROW "); // .ctor(B) vs. .ctor(modopt1 B) and .ctor(modopt2 B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed THROW "); // .ctor(B) vs. .ctor(modopt1 B) and .ctor(modreq B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW .method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int32) '' ) cil managed THROW "); // .ctor(modeopt1 B) vs. .ctor(modopt2 B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed THROW ", isError: true); // private .ctor(B) vs. .ctor(modopt1 B) and .ctor(modopt B) verifyBoth(@" .method private hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed THROW ", isError: true); void verifyBoth(string inject1, string inject2, bool isError = false) { verify(inject1 + inject2, isError); verify(inject2 + inject1, isError); } void verify(string inject, bool isError = false) { var ranBody = @" { IL_0000: ldstr ""RAN"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } "; var throwBody = @" { IL_0000: ldnull IL_0001: throw } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource_template.Replace("INJECT", inject).Replace("RAN", ranBody).Replace("THROW", throwBody), parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var expectedDiagnostics = isError ? new[] { // (2,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record C : B Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15) } : new DiagnosticDescription[] { }; comp.VerifyDiagnostics(expectedDiagnostics); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics(); } } } [Fact, WorkItem(45077, "https://github.com/dotnet/roslyn/issues/45077")] public void CopyCtor_AmbiguitiesInMetadata_GenericType() { // IL for a minimal `public record B<T> { }` with modopt in nested position of parameter type var ilSource = @" .class public auto ansi beforefieldinit B`1<T> extends [mscorlib]System.Object implements class [mscorlib]System.IEquatable`1<class B`1<!T>> { .method family hidebysig specialname rtspecialname instance void .ctor ( class B`1<!T modopt(int64)> '' ) cil managed { IL_0000: ldstr ""RAN"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig specialname newslot virtual instance class B`1<!T> '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldarg.0 IL_0001: newobj instance void class B`1<!T>::.ctor(class B`1<!0>) IL_0006: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method public newslot virtual instance bool Equals ( class B`1<!T> '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B`1::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C<T> : B<T> { } public class Program { public static void Main() { var c = new C<string>(); _ = c with { }; } }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void CopyCtor_Accessibility_01(string accessibility) { var source = $@" record A(int X) {{ { accessibility } A(A a) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,6): error CS8878: A copy constructor 'A.A(A)' must be public or protected because the record is not sealed. // A(A a) Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "A").WithArguments("A.A(A)").WithLocation(4, 6 + accessibility.Length) ); } [Theory] [InlineData("public")] [InlineData("protected")] public void CopyCtor_Accessibility_02(string accessibility) { var source = $@" record A(int X) {{ { accessibility } A(A a) => System.Console.Write(""RAN""); public static void Main() {{ var a = new A(123); _ = a with {{}}; }} }} "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] [InlineData("public")] public void CopyCtor_Accessibility_03(string accessibility) { var source = $@" sealed record A(int X) {{ { accessibility } A(A a) => System.Console.Write(""RAN""); public static void Main() {{ var a = new A(123); _ = a with {{}}; }} }} "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics(); var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Theory] [InlineData("private protected")] [InlineData("internal protected")] [InlineData("protected")] public void CopyCtor_Accessibility_04(string accessibility) { var source = $@" sealed record A(int X) {{ { accessibility } A(A a) => System.Console.Write(""RAN""); public static void Main() {{ var a = new A(123); _ = a with {{}}; }} }} "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics( // (4,15): warning CS0628: 'A.A(A)': new protected member declared in sealed type // protected A(A a) Diagnostic(ErrorCode.WRN_ProtectedInSealed, "A").WithArguments("A.A(A)").WithLocation(4, 6 + accessibility.Length) ); var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Fact] public void CopyCtor_Signature_01() { var source = @" record A(int X) { public A(in A a) : this(-15) => System.Console.Write(""RAN""); public static void Main() { var a = new A(123); System.Console.Write((a with { }).X); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "123").VerifyDiagnostics(); } [Fact] public void Deconstruct_Simple() { var source = @"using System; record B(int X, int Y) { public static void Main() { M(new B(1, 2)); } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); var deconstruct = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("B.Deconstruct"); Assert.Equal(2, deconstruct.ParameterCount); Assert.Equal(RefKind.Out, deconstruct.Parameters[0].RefKind); Assert.Equal("X", deconstruct.Parameters[0].Name); Assert.Equal(RefKind.Out, deconstruct.Parameters[1].RefKind); Assert.Equal("Y", deconstruct.Parameters[1].Name); Assert.True(deconstruct.ReturnsVoid); Assert.False(deconstruct.IsVirtual); Assert.False(deconstruct.IsStatic); Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility); } [Fact] public void Deconstruct_PositionalAndNominalProperty() { var source = @"using System; record B(int X) { public int Y { get; init; } public static void Main() { M(new B(1)); } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal( "void B.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Nested() { var source = @"using System; record B(int X, int Y); record C(B B, int Z) { public static void Main() { M(new C(new B(1, 2), 3)); } static void M(C c) { switch (c) { case C(B(int x, int y), int z): Console.Write(x); Console.Write(y); Console.Write(z); break; } } } "; var verifier = CompileAndVerify(source, expectedOutput: "123"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""B C.B.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""int C.Z.get"" IL_000f: stind.i4 IL_0010: ret }"); } [Fact] public void Deconstruct_PropertyCollision() { var source = @"using System; record B(int X, int Y) { public int X => 3; static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "32"); verifier.VerifyDiagnostics( // (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14) ); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_01() { var source = @" record B(int X, int Y) { public int X() => 3; static void M(B b) { switch (b) { case B(int x, int y): break; } } static void Main() { M(new B(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS0102: The type 'B' already contains a definition for 'X' // public int X() => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("B", "X").WithLocation(4, 16) ); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_02() { var source = @" record B { public int X(int y) => y; } record C(int X, int Y) : B { static void M(C c) { switch (c) { case C(int x, int y): break; } } static void Main() { M(new C(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record C(int X, int Y) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "int", "X").WithLocation(7, 14), // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_03() { var source = @" using System; record B { public int X() => 3; } record C(int X, int Y) : B { public new int X { get; } static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "02"); verifier.VerifyDiagnostics( // (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_04() { var source = @" record C(int X, int Y) { public int X(int arg) => 3; static void M(C c) { switch (c) { case C(int x, int y): break; } } static void Main() { M(new C(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS0102: The type 'C' already contains a definition for 'X' // public int X(int arg) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(4, 16) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_FieldCollision() { var source = @" using System; record C(int X) { int X; static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(0)); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,10): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record C(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(4, 10), // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (6,9): warning CS0169: The field 'C.X' is never used // int X; Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("C.X").WithLocation(6, 9) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (6,9): warning CS0169: The field 'C.X' is never used // int X; Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("C.X").WithLocation(6, 9) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_EventCollision() { var source = @" using System; record C(Action X) { event Action X; static void M(C c) { switch (c) { case C(Action x): Console.Write(x); break; } } static void Main() { M(new C(() => { })); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS0102: The type 'C' already contains a definition for 'X' // event Action X; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(6, 18), // (6,18): warning CS0067: The event 'C.X' is never used // event Action X; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "X").WithArguments("C.X").WithLocation(6, 18) ); Assert.Equal( "void C.Deconstruct(out System.Action X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_WriteOnlyPropertyInBase() { var source = @" using System; record B { public int X { set { } } } record C(int X) : B { static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,14): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record C(int X) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "int", "X").WithLocation(9, 14), // (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14)); Assert.Equal( "void C.Deconstruct(out System.Int32 X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_PrivateWriteOnlyPropertyInBase() { var source = @" using System; record B { private int X { set { } } } record C(int X) : B { static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal( "void C.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty() { var source = @" record C { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); Assert.Null(comp.GetMember("C.Deconstruct")); } [Fact] public void Deconstruct_Inheritance_01() { var source = @" using System; record B(int X, int Y) { internal B() : this(0, 1) { } } record C : B { static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } switch (c) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "0101"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; Assert.Null(comp.GetMember("C.Deconstruct")); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Inheritance_02() { var source = @" using System; record B(int X, int Y) { // https://github.com/dotnet/roslyn/issues/44902 internal B() : this(0, 1) { } } record C(int X, int Y, int Z) : B(X, Y) { static void M(C c) { switch (c) { case C(int x, int y, int z): Console.Write(x); Console.Write(y); Console.Write(z); break; } switch (c) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(0, 1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "01201"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y, out System.Int32 Z)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Inheritance_03() { var source = @" using System; record B(int X, int Y) { internal B() : this(0, 1) { } } record C(int X, int Y) : B { static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } switch (c) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(0, 1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "0101"); verifier.VerifyDiagnostics( // (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14), // (9,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(9, 21) ); var comp = verifier.Compilation; Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Inheritance_04() { var source = @" using System; record A<T>(T P) { internal A() : this(default(T)) { } } record B1(int P, object Q) : A<int>(P) { internal B1() : this(0, null) { } } record B2(object P, object Q) : A<object>(P) { internal B2() : this(null, null) { } } record B3<T>(T P, object Q) : A<T>(P) { internal B3() : this(default, 0) { } } class C { static void M0(A<int> arg) { switch (arg) { case A<int>(int x): Console.Write(x); break; } } static void M1(B1 arg) { switch (arg) { case B1(int p, object q): Console.Write(p); Console.Write(q); break; } } static void M2(B2 arg) { switch (arg) { case B2(object p, object q): Console.Write(p); Console.Write(q); break; } } static void M3(B3<int> arg) { switch (arg) { case B3<int>(int p, object q): Console.Write(p); Console.Write(q); break; } } static void Main() { M0(new A<int>(0)); M1(new B1(1, 2)); M2(new B2(3, 4)); M3(new B3<int>(5, 6)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "0123456"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; Assert.Equal( "void A<T>.Deconstruct(out T P)", comp.GetMember("A.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B1.Deconstruct(out System.Int32 P, out System.Object Q)", comp.GetMember("B1.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B2.Deconstruct(out System.Object P, out System.Object Q)", comp.GetMember("B2.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B3<T>.Deconstruct(out T P, out System.Object Q)", comp.GetMember("B3.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Conversion_01() { var source = @" using System; record C(int X, int Y) { public long X { get; init; } public long Y { get; init; } static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(0, 1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,14): error CS8866: Record member 'C.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record C(int X, int Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("C.X", "int", "X").WithLocation(4, 14), // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (4,21): error CS8866: Record member 'C.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'. // record C(int X, int Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("C.Y", "int", "Y").WithLocation(4, 21), // (4,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(4, 21)); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Conversion_02() { var source = @" #nullable enable using System; record C(string? X, string Y) { public string X { get; init; } = null!; public string? Y { get; init; } static void M(C c) { switch (c) { case C(var x, string y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(""a"", ""b"")); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,18): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 18), // (5,28): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 28) ); Assert.Equal( "void C.Deconstruct(out System.String? X, out System.String Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Conversion_03() { var source = @" using System; class Base { } class Derived : Base { } record C(Derived X, Base Y) { public Base X { get; init; } public Derived Y { get; init; } static void M(C c) { switch (c) { case C(Derived x, Base y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(new Derived(), new Base())); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8866: Record member 'C.X' must be a readable instance property or field of type 'Derived' to match positional parameter 'X'. // record C(Derived X, Base Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("C.X", "Derived", "X").WithLocation(7, 18), // (7,18): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(Derived X, Base Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 18), // (7,26): error CS8866: Record member 'C.Y' must be a readable instance property or field of type 'Base' to match positional parameter 'Y'. // record C(Derived X, Base Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("C.Y", "Base", "Y").WithLocation(7, 26), // (7,26): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(Derived X, Base Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 26)); Assert.Equal( "void C.Deconstruct(out Derived X, out Base Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty_WithParameterList() { var source = @" record C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); Assert.Null(comp.GetMember("C.Deconstruct")); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_01() { var source = @"using System; record C() { public void Deconstruct() { } static void M(C c) { switch (c) { case C(): Console.Write(12); break; } } public static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_02() { var source = @"using System; record C() { public void Deconstruct(out int X, out int Y) { X = 1; Y = 2; } static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_03() { var source = @"using System; record C() { private void Deconstruct() { } static void M(C c) { switch (c) { case C(): Console.Write(12); break; } } public static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_04() { var source = @" record C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } public static void Deconstruct() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS0176: Member 'C.Deconstruct()' cannot be accessed with an instance reference; qualify it with a type name instead // case C(): Diagnostic(ErrorCode.ERR_ObjectProhibited, "()", isSuppressed: false).WithArguments("C.Deconstruct()").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_05() { var source = @" record C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } public int Deconstruct() { return 1; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); } [Fact] public void Deconstruct_UserDefined() { var source = @"using System; record B(int X, int Y) { public void Deconstruct(out int X, out int Y) { X = this.X + 1; Y = this.Y + 2; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(0, 0)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_01() { var source = @"using System; record B(int X, int Y) { public void Deconstruct(out int Z) { Z = X + Y; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } switch (b) { case B(int z): Console.Write(z); break; } } public static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "123"); verifier.VerifyDiagnostics(); var expectedSymbols = new[] { "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", "void B.Deconstruct(out System.Int32 Z)", }; Assert.Equal(expectedSymbols, verifier.Compilation.GetMembers("B.Deconstruct").Select(s => s.ToTestDisplayString(includeNonNullable: false))); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_02() { var source = @"using System; record B(int X) { public int Deconstruct(out int a) => throw null; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,16): error CS8874: Record member 'B.Deconstruct(out int)' must return 'void'. // public int Deconstruct(out int a) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Deconstruct").WithArguments("B.Deconstruct(out int)", "void").WithLocation(5, 16), // (11,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'B', with 1 out parameters and a void return type. // case B(int x): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int x)").WithArguments("B", "1").WithLocation(11, 19)); Assert.Equal("System.Int32 B.Deconstruct(out System.Int32 a)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_03() { var source = @"using System; record B(int X) { public void Deconstruct(int X) { } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); var expectedSymbols = new[] { "void B.Deconstruct(out System.Int32 X)", "void B.Deconstruct(System.Int32 X)", }; Assert.Equal(expectedSymbols, verifier.Compilation.GetMembers("B.Deconstruct").Select(s => s.ToTestDisplayString(includeNonNullable: false))); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_04() { var source = @"using System; record B(int X) { public void Deconstruct(ref int X) { } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS0663: 'B' cannot define an overloaded method that differs only on parameter modifiers 'ref' and 'out' // public void Deconstruct(ref int X) Diagnostic(ErrorCode.ERR_OverloadRefKind, "Deconstruct").WithArguments("B", "method", "ref", "out").WithLocation(5, 17) ); Assert.Equal(2, comp.GetMembers("B.Deconstruct").Length); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_05() { var source = @"using System; record A(int X) { public A() : this(0) { } public int Deconstruct(out int a, out int b) => throw null; } record B(int X, int Y) : A(X) { static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); Assert.Equal("void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_06() { var source = @"using System; record A(int X) { public A() : this(0) { } public virtual int Deconstruct(out int a, out int b) => throw null; } record B(int X, int Y) : A(X) { static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); Assert.Equal("void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void Deconstruct_UserDefined_Accessibility_07(string accessibility) { var source = $@" record A(int X) {{ { accessibility } void Deconstruct(out int a) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,11): error CS8873: Record member 'A.Deconstruct(out int)' must be public. // void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 11 + accessibility.Length) ); } [Fact] public void Deconstruct_UserDefined_Static_08() { var source = @" record A(int X) { public static void Deconstruct(out int a) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS8877: Record member 'A.Deconstruct(out int)' may not be static. // public static void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 24) ); } [Fact] public void Deconstruct_Shadowing_01() { var source = @" abstract record A(int X) { public abstract int Deconstruct(out int a, out int b); } abstract record B(int X, int Y) : A(X) { public static void Main() { } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,17): error CS0533: 'B.Deconstruct(out int, out int)' hides inherited abstract member 'A.Deconstruct(out int, out int)' // abstract record B(int X, int Y) : A(X) Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "B").WithArguments("B.Deconstruct(out int, out int)", "A.Deconstruct(out int, out int)").WithLocation(6, 17) ); } [Fact] public void Deconstruct_TypeMismatch_01() { var source = @" record A(int X) { public System.Type X => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record A(int X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 14), // (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14) ); } [Fact] public void Deconstruct_TypeMismatch_02() { var source = @" record A { public System.Type X => throw null; } record B(int X) : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (7,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record B(int X) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(7, 14), // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/45010")] [WorkItem(45010, "https://github.com/dotnet/roslyn/issues/45010")] public void Deconstruct_ObsoleteProperty() { var source = @"using System; record B(int X) { [Obsolete] int X { get; } = X; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal("void B.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/45009")] [WorkItem(45009, "https://github.com/dotnet/roslyn/issues/45009")] public void Deconstruct_RefProperty() { var source = @"using System; record B(int X) { static int _x = 2; ref int X => ref _x; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "2"); verifier.VerifyDiagnostics(); var deconstruct = verifier.Compilation.GetMember("B.Deconstruct"); Assert.Equal("void B.Deconstruct(out System.Int32 X)", deconstruct.ToTestDisplayString(includeNonNullable: false)); Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility); Assert.False(deconstruct.IsAbstract); Assert.False(deconstruct.IsVirtual); Assert.False(deconstruct.IsOverride); Assert.False(deconstruct.IsSealed); Assert.True(deconstruct.IsImplicitlyDeclared); } [Fact] public void Deconstruct_Static() { var source = @" using System; record B(int X, int Y) { static int Y { get; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS8866: Record member 'B.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'. // record B(int X, int Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("B.Y", "int", "Y").WithLocation(4, 21), // (4,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(4, 21)); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Theory] [InlineData(false)] [InlineData(true)] public void Overrides_01(bool usePreview) { var source = @"record A { public sealed override bool Equals(object other) => false; public sealed override int GetHashCode() => 0; public sealed override string ToString() => null; } record B(int X, int Y) : A { }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9); if (usePreview) { comp.VerifyDiagnostics( // (3,33): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public sealed override bool Equals(object other) => false; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 33), // (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed. // public sealed override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32), // (7,8): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // record B(int X, int Y) : A Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(7, 8) ); } else { comp.VerifyDiagnostics( // (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed. // public sealed override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32), // (5,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater. // public sealed override string ToString() => null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(5, 35), // (3,33): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public sealed override bool Equals(object other) => false; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 33), // (7,8): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // record B(int X, int Y) : A Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(7, 8) ); } var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Int32 X, System.Int32 Y)", "System.Type B.EqualityContract.get", "System.Type B.EqualityContract { get; }", "System.Int32 B.<X>k__BackingField", "System.Int32 B.X.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.X.init", "System.Int32 B.X { get; init; }", "System.Int32 B.<Y>k__BackingField", "System.Int32 B.Y.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Y.init", "System.Int32 B.Y { get; init; }", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", "A B." + WellKnownMemberNames.CloneMethodName + "()", "B..ctor(B original)", "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Overrides_02() { var source = @"abstract record A { public abstract override bool Equals(object other); public abstract override int GetHashCode(); public abstract override string ToString(); } record B(int X, int Y) : A { }"; var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? source : new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics( // (3,35): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public abstract override bool Equals(object other); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 35), // (7,8): error CS0534: 'B' does not implement inherited abstract member 'A.Equals(object)' // record B(int X, int Y) : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.Equals(object)").WithLocation(7, 8) ); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); string expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses ? "B B." + WellKnownMemberNames.CloneMethodName + "()" : "A B." + WellKnownMemberNames.CloneMethodName + "()"; var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Int32 X, System.Int32 Y)", "System.Type B.EqualityContract.get", "System.Type B.EqualityContract { get; }", "System.Int32 B.<X>k__BackingField", "System.Int32 B.X.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.X.init", "System.Int32 B.X { get; init; }", "System.Int32 B.<Y>k__BackingField", "System.Int32 B.Y.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Y.init", "System.Int32 B.Y { get; init; }", "System.String B.ToString()", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", expectedClone, "B..ctor(B original)", "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ObjectEquals_01() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public final hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0239: 'B.Equals(object?)': cannot override inherited member 'A.Equals(object)' because it is sealed // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.Equals(object?)", "A.Equals(object)").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_02() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public newslot hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.Equals(object?)' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.Equals(object?)").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_03() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public newslot hidebysig instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.Equals(object?)': cannot override inherited member 'A.Equals(object)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(object?)", "A.Equals(object)").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_04() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public newslot hidebysig virtual instance int32 Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.Equals(object?)': return type must be 'int' to match overridden member 'A.Equals(object)' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.Equals(object?)", "A.Equals(object)", "int").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_05() { var source0 = @"namespace System { public class Object { public virtual int Equals(object other) => default; public virtual int GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'A.Equals(object?)': return type must be 'int' to match overridden member 'object.Equals(object)' // public record A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "A").WithArguments("A.Equals(object?)", "object.Equals(object)", "int").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void ObjectEquals_06() { var source = @"record A { public static new bool Equals(object obj) => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,28): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public static new bool Equals(object obj) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 28) ); } [Fact] public void ObjectGetHashCode_01() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source1 = @" public record B : A { }"; var source2 = @" public record B : A { public override int GetHashCode() => 0; }"; var source3 = @" public record C : B { } "; var source4 = @" public record C : B { public override int GetHashCode() => 0; } "; var comp = CreateCompilationWithIL(new[] { source1, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15) ); comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25) ); comp = CreateCompilationWithIL(new[] { source1 + source3, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15) ); comp = CreateCompilationWithIL(new[] { source1 + source4, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15) ); comp = CreateCompilationWithIL(new[] { source2 + source3, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25) ); comp = CreateCompilationWithIL(new[] { source2 + source4, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_02() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source1 = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source1, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(2, 15) ); var source2 = @" public record B : A { public override int GetHashCode() => throw null; }"; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override // public override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_03() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance bool GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.GetHashCode()': return type must be 'bool' to match overridden member 'A.GetHashCode()' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()", "bool").WithLocation(2, 15) ); var source2 = @" public record B : A { public override int GetHashCode() => throw null; }"; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS0508: 'B.GetHashCode()': return type must be 'bool' to match overridden member 'A.GetHashCode()' // public override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()", "bool").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_04() { var source = @"record A { public override bool GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,26): error CS0508: 'A.GetHashCode()': return type must be 'int' to match overridden member 'object.GetHashCode()' // public override bool GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GetHashCode").WithArguments("A.GetHashCode()", "object.GetHashCode()", "int").WithLocation(3, 26) ); } [Fact] public void ObjectGetHashCode_05() { var source = @"record A { public new int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,20): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public new int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 20) ); } [Fact] public void ObjectGetHashCode_06() { var source = @"record A { public static new int GetHashCode() => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,27): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public static new int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 27), // (6,8): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(6, 8) ); } [Fact] public void ObjectGetHashCode_07() { var source = @"record A { public new int GetHashCode => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,20): error CS0102: The type 'A' already contains a definition for 'GetHashCode' // public new int GetHashCode => throw null; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "GetHashCode").WithArguments("A", "GetHashCode").WithLocation(3, 20) ); } [Fact] public void ObjectGetHashCode_08() { var source = @"record A { public new void GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,21): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public new void GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 21) ); } [Fact] public void ObjectGetHashCode_09() { var source = @"record A { public void GetHashCode(int x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); Assert.Equal("System.Int32 A.GetHashCode()", comp.GetMembers("A.GetHashCode").First().ToTestDisplayString()); } [Fact] public void ObjectGetHashCode_10() { var source = @" record A { public sealed override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed. // public sealed override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32) ); } [Fact] public void ObjectGetHashCode_11() { var source = @" sealed record A { public sealed override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] public void ObjectGetHashCode_12() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public final hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(2, 15) ); var source2 = @" public record B : A { public override int GetHashCode() => throw null; }"; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // public override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantOverrideSealed, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_13() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance class A GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source2 = @" public record B : A { public override A GetHashCode() => default; }"; var comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,23): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override A GetHashCode() => default; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 23) ); } [Fact] public void ObjectGetHashCode_14() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance class A GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source2 = @" public record B : A { public override B GetHashCode() => default; }"; var comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,23): error CS8830: 'B.GetHashCode()': Target runtime doesn't support covariant return types in overrides. Return type must be 'A' to match overridden member 'A.GetHashCode()' // public override B GetHashCode() => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()", "A").WithLocation(3, 23) ); } [Fact] public void ObjectGetHashCode_15() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual Something GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } public class Something { } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { public override Something GetHashCode() => default; } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,31): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public override Something GetHashCode() => default; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 31), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void ObjectGetHashCode_16() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual bool GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { public override bool GetHashCode() => default; } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,26): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public override bool GetHashCode() => default; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 26), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void ObjectGetHashCode_17() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual bool GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'A.GetHashCode()': return type must be 'bool' to match overridden member 'object.GetHashCode()' // public record A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "A").WithArguments("A.GetHashCode()", "object.GetHashCode()", "bool").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void BaseEquals_01() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(2, 15) ); } [Fact] public void BaseEquals_02() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(2, 15) ); } [Fact] public void BaseEquals_03() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance int32 Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.Equals(A?)': return type must be 'int' to match overridden member 'A.Equals(A)' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.Equals(A?)", "A.Equals(A)", "int").WithLocation(2, 15) ); } [Fact] public void BaseEquals_04() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A .class public auto ansi beforefieldinit B extends A { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class B "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8871: 'C.Equals(B?)' does not override expected method from 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "C").WithArguments("C.Equals(B?)", "B").WithLocation(2, 15) ); } [Fact] public void BaseEquals_05() { var source = @" record A { } record B : A { public override bool Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (8,26): error CS0111: Type 'B' already defines a member called 'Equals' with the same parameter types // public override bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "B").WithLocation(8, 26) ); } [Fact] public void RecordEquals_01() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(A x); } record B : A { public virtual bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False ").VerifyDiagnostics( // (5,26): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public abstract bool Equals(A x); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 26), // (9,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25) ); } [Fact] public void RecordEquals_02() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } record B : A { public override bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False ").VerifyDiagnostics( // (9,26): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 26) ); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_03() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } record B : A { public sealed override bool Equals(B other) => Report(""B.Equals(B)""); } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (9,33): error CS8872: 'B.Equals(B)' must allow overriding because the containing record is not sealed. // public sealed override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("B.Equals(B)").WithLocation(9, 33), // (9,33): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public sealed override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 33) ); } [Fact] public void RecordEquals_04() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } sealed record B : A { public sealed override bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False ").VerifyDiagnostics( // (9,33): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public sealed override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 33) ); var copyCtor = comp.GetMember<NamedTypeSymbol>("A").InstanceConstructors.Where(c => c.ParameterCount == 1).Single(); Assert.Equal(Accessibility.Protected, copyCtor.DeclaredAccessibility); Assert.False(copyCtor.IsOverride); Assert.False(copyCtor.IsVirtual); Assert.False(copyCtor.IsAbstract); Assert.False(copyCtor.IsSealed); Assert.True(copyCtor.IsImplicitlyDeclared); copyCtor = comp.GetMember<NamedTypeSymbol>("B").InstanceConstructors.Where(c => c.ParameterCount == 1).Single(); Assert.Equal(Accessibility.Private, copyCtor.DeclaredAccessibility); Assert.False(copyCtor.IsOverride); Assert.False(copyCtor.IsVirtual); Assert.False(copyCtor.IsAbstract); Assert.False(copyCtor.IsSealed); Assert.True(copyCtor.IsImplicitlyDeclared); } [Fact] public void RecordEquals_05() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } abstract record B : A { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (7,17): error CS0533: 'B.Equals(B?)' hides inherited abstract member 'A.Equals(B)' // abstract record B : A Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "B").WithArguments("B.Equals(B?)", "A.Equals(B)").WithLocation(7, 17) ); var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_06(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } " + modifiers + @" record B : A { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (8,8): error CS0534: 'B' does not implement inherited abstract member 'A.Equals(B)' // record B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.Equals(B)").WithLocation(8, 8) ); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_07(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public virtual bool Equals(B x) => Report(""A.Equals(B)""); } " + modifiers + @" record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" A.Equals(B) False True True ").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_08(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(C x); } abstract record B : A { public override bool Equals(C x) => Report(""B.Equals(C)""); } " + modifiers + @" record C : B { } class Program { static void Main() { A a1 = new C(); C c2 = new C(); System.Console.WriteLine(a1.Equals(c2)); System.Console.WriteLine(c2.Equals(a1)); System.Console.WriteLine(c2.Equals((C)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(C) False True True ").VerifyDiagnostics(); var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); clone = comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); clone = comp.GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_09(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public bool Equals(B x) => Report(""A.Equals(B)""); } " + modifiers + @" record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" A.Equals(B) False True True ").VerifyDiagnostics(); } [Theory] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void RecordEquals_10(string accessibility) { var source = $@" record A {{ { accessibility } virtual bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS8873: Record member 'A.Equals(A)' must be public. // { accessibility } virtual bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length), // (4,...): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // { accessibility } virtual bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 19 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("private")] public void RecordEquals_11(string accessibility) { var source = $@" record A {{ { accessibility } virtual bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS0621: 'A.Equals(A)': virtual or abstract members cannot be private // virtual bool Equals(A x) Diagnostic(ErrorCode.ERR_VirtualPrivate, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length), // (4,...): error CS8873: Record member 'A.Equals(A)' must be public. // { accessibility } virtual bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length), // (4,...): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // virtual bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 19 + accessibility.Length) ); } [Fact] public void RecordEquals_12() { var source = @" record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public virtual bool Equals(B other) => Report(""A.Equals(B)""); } class B { } class Program { static void Main() { A a1 = new A(); A a2 = new A(); System.Console.WriteLine(a1.Equals(a2)); System.Console.WriteLine(a1.Equals((object)a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_13() { var source = @" record A { public virtual int Equals(A other) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,24): error CS8874: Record member 'A.Equals(A)' must return 'bool'. // public virtual int Equals(A other) Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual int Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void RecordEquals_14() { var source = @" record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (4,20): error CS0518: Predefined type 'System.Boolean' is not defined or imported // public virtual bool Equals(A other) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(4, 20), // (4,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 25) ); } [Fact] public void RecordEquals_15() { var source = @" record A { public virtual Boolean Equals(A other) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,20): error CS0246: The type or namespace name 'Boolean' could not be found (are you missing a using directive or an assembly reference?) // public virtual Boolean Equals(A other) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Boolean").WithArguments("Boolean").WithLocation(4, 20), // (4,28): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual Boolean Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 28) ); } [Fact] public void RecordEquals_16() { var source = @" abstract record A { } record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_17() { var source = @" abstract record A { } sealed record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.False(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_18() { var source = @" sealed record A { } class Program { static void Main() { A a1 = new A(); A a2 = new A(); System.Console.WriteLine(a1.Equals(a2)); System.Console.WriteLine(a2.Equals(a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.False(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_19() { var source = @" record A { public static bool Equals(A x) => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,8): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 8), // (4,24): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed. // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24), // (7,8): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(7, 8) ); } [Fact] public void RecordEquals_20() { var source = @" sealed record A { public static bool Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static. // sealed record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 15), // (4,24): error CS8877: Record member 'A.Equals(A)' may not be static. // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void EqualityContract_01() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected abstract System.Type EqualityContract { get; } } record B : A { protected override System.Type EqualityContract { get { Report(""B.EqualityContract""); return typeof(B); } } } class Program { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.EqualityContract B.EqualityContract True ").VerifyDiagnostics(); } [Fact] public void EqualityContract_02() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected abstract System.Type EqualityContract { get; } } record B : A { protected sealed override System.Type EqualityContract { get { Report(""B.EqualityContract""); return typeof(B); } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (9,43): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed. // protected sealed override System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(9, 43) ); } [Fact] public void EqualityContract_03() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected abstract System.Type EqualityContract { get; } } sealed record B : A { protected sealed override System.Type EqualityContract { get { Report(""B.EqualityContract""); return typeof(B); } } } class Program { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.EqualityContract B.EqualityContract True ").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("sealed ")] public void EqualityContract_04(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected virtual System.Type EqualityContract { get { Report(""A.EqualityContract""); return typeof(B); } } } " + modifiers + @" record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True True ").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.True(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); var equalityContractGet = equalityContract.GetMethod; Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContractGet!.DeclaredAccessibility); Assert.False(equalityContractGet.IsAbstract); Assert.False(equalityContractGet.IsVirtual); Assert.True(equalityContractGet.IsOverride); Assert.False(equalityContractGet.IsSealed); Assert.True(equalityContractGet.IsImplicitlyDeclared); Assert.Empty(equalityContractGet.DeclaringSyntaxReferences); } [Theory] [InlineData("public")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void EqualityContract_05(string accessibility) { var source = $@" record A {{ { accessibility } virtual System.Type EqualityContract => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS8875: Record member 'A.EqualityContract' must be protected. // { accessibility } virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("private")] public void EqualityContract_06(string accessibility) { var source = $@" record A {{ { accessibility } virtual System.Type EqualityContract => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS0621: 'A.EqualityContract': virtual or abstract members cannot be private // { accessibility } virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_VirtualPrivate, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length), // (4,...): error CS8875: Record member 'A.EqualityContract' must be protected. // { accessibility } virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("abstract ")] [InlineData("sealed ")] public void EqualityContract_07(string modifiers) { var source = @" record A { } " + modifiers + @" record B : A { public void PrintEqualityContract() => System.Console.WriteLine(EqualityContract); } "; if (modifiers != "abstract ") { source += @" class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); b2.PrintEqualityContract(); } }"; } var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: modifiers == "abstract " ? TestOptions.ReleaseDll : TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: modifiers == "abstract " ? null : @" True True True B ").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.True(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); var equalityContractGet = equalityContract.GetMethod; Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContractGet!.DeclaredAccessibility); Assert.False(equalityContractGet.IsAbstract); Assert.False(equalityContractGet.IsVirtual); Assert.True(equalityContractGet.IsOverride); Assert.False(equalityContractGet.IsSealed); Assert.True(equalityContractGet.IsImplicitlyDeclared); Assert.Empty(equalityContractGet.DeclaringSyntaxReferences); verifier.VerifyIL("B.EqualityContract.get", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""B"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret } "); } [Theory] [InlineData("")] [InlineData("abstract ")] [InlineData("sealed ")] public void EqualityContract_08(string modifiers) { var source = modifiers + @" record B { public void PrintEqualityContract() => System.Console.WriteLine(EqualityContract); } "; if (modifiers != "abstract ") { source += @" class Program { static void Main() { B a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); b2.PrintEqualityContract(); } }"; } var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: modifiers == "abstract " ? TestOptions.ReleaseDll : TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: modifiers == "abstract " ? null : @" True True True B ").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(modifiers == "sealed " ? Accessibility.Private : Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.Equal(modifiers != "sealed ", equalityContract.IsVirtual); Assert.False(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); var equalityContractGet = equalityContract.GetMethod; Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(modifiers == "sealed " ? Accessibility.Private : Accessibility.Protected, equalityContractGet!.DeclaredAccessibility); Assert.False(equalityContractGet.IsAbstract); Assert.Equal(modifiers != "sealed ", equalityContractGet.IsVirtual); Assert.False(equalityContractGet.IsOverride); Assert.False(equalityContractGet.IsSealed); Assert.True(equalityContractGet.IsImplicitlyDeclared); Assert.Empty(equalityContractGet.DeclaringSyntaxReferences); verifier.VerifyIL("B.EqualityContract.get", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""B"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret } "); } [Fact] public void EqualityContract_09() { var source = @" record A { protected virtual int EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,27): error CS8874: Record member 'A.EqualityContract' must return 'Type'. // protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("A.EqualityContract", "System.Type").WithLocation(4, 27) ); } [Fact] public void EqualityContract_10() { var source = @" record A { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeTypeMissing(WellKnownType.System_Type); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // record A Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record A { }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // record A Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record A { }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 8) ); } [Fact] public void EqualityContract_11() { var source = @" record A { protected virtual Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,23): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(4, 23) ); } [Fact] public void EqualityContract_12() { var source = @" record A { protected System.Type EqualityContract => throw null; } sealed record B { protected System.Type EqualityContract => throw null; } sealed record C { protected virtual System.Type EqualityContract => throw null; } record D { protected virtual System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,27): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 27), // (10,27): warning CS0628: 'B.EqualityContract': new protected member declared in sealed type // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(10, 27), // (10,27): error CS8879: Record member 'B.EqualityContract' must be private. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(10, 27), // (11,12): warning CS0628: 'B.EqualityContract.get': new protected member declared in sealed type // => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("B.EqualityContract.get").WithLocation(11, 12), // (16,35): warning CS0628: 'C.EqualityContract': new protected member declared in sealed type // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(16, 35), // (16,35): error CS8879: Record member 'C.EqualityContract' must be private. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(16, 35), // (17,12): error CS0549: 'C.EqualityContract.get' is a new virtual member in sealed type 'C' // => throw null; Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "throw null").WithArguments("C.EqualityContract.get", "C").WithLocation(17, 12) ); } [Fact] public void EqualityContract_13() { var source = @" record A {} record B : A { protected System.Type EqualityContract => throw null; } sealed record C : A { protected System.Type EqualityContract => throw null; } sealed record D : A { protected virtual System.Type EqualityContract => throw null; } record E : A { protected virtual System.Type EqualityContract => throw null; } record F : A { protected override System.Type EqualityContract => throw null; } record G : A { protected sealed override System.Type EqualityContract => throw null; } sealed record H : A { protected sealed override System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (7,27): error CS8876: 'B.EqualityContract' does not override expected property from 'A'. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("B.EqualityContract", "A").WithLocation(7, 27), // (7,27): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(7, 27), // (7,27): warning CS0114: 'B.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(7, 27), // (13,27): warning CS0628: 'C.EqualityContract': new protected member declared in sealed type // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(13, 27), // (13,27): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(13, 27), // (13,27): warning CS0114: 'C.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("C.EqualityContract", "A.EqualityContract").WithLocation(13, 27), // (14,12): warning CS0628: 'C.EqualityContract.get': new protected member declared in sealed type // => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("C.EqualityContract.get").WithLocation(14, 12), // (19,35): warning CS0628: 'D.EqualityContract': new protected member declared in sealed type // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("D.EqualityContract").WithLocation(19, 35), // (19,35): error CS8876: 'D.EqualityContract' does not override expected property from 'A'. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("D.EqualityContract", "A").WithLocation(19, 35), // (19,35): warning CS0114: 'D.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("D.EqualityContract", "A.EqualityContract").WithLocation(19, 35), // (20,12): error CS0549: 'D.EqualityContract.get' is a new virtual member in sealed type 'D' // => throw null; Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "throw null").WithArguments("D.EqualityContract.get", "D").WithLocation(20, 12), // (25,35): error CS8876: 'E.EqualityContract' does not override expected property from 'A'. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("E.EqualityContract", "A").WithLocation(25, 35), // (25,35): warning CS0114: 'E.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("E.EqualityContract", "A.EqualityContract").WithLocation(25, 35), // (37,43): error CS8872: 'G.EqualityContract' must allow overriding because the containing record is not sealed. // protected sealed override System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("G.EqualityContract").WithLocation(37, 43) ); } [Fact] public void EqualityContract_14() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { } public record C : A { new protected virtual System.Type EqualityContract => throw null; } public record D : A { new protected virtual int EqualityContract => throw null; } public record E : A { new protected virtual Type EqualityContract => throw null; } public record F : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(2, 15), // (6,39): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // new protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 39), // (11,31): error CS8874: Record member 'D.EqualityContract' must return 'Type'. // new protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 31), // (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // new protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27), // (21,36): error CS0506: 'F.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "EqualityContract").WithArguments("F.EqualityContract", "A.EqualityContract").WithLocation(21, 36) ); } [Fact] public void EqualityContract_15() { var source = @" record A { protected virtual int EqualityContract => throw null; } record B : A { } record C : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,27): error CS8874: Record member 'A.EqualityContract' must return 'Type'. // protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("A.EqualityContract", "System.Type").WithLocation(4, 27), // (8,8): error CS1715: 'B.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract' // record B : A Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "B").WithArguments("B.EqualityContract", "A.EqualityContract", "int").WithLocation(8, 8), // (14,36): error CS1715: 'C.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract' // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "EqualityContract").WithArguments("C.EqualityContract", "A.EqualityContract", "int").WithLocation(14, 36) ); } [Fact] public void EqualityContract_16() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot final virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { } public record C : A { new protected virtual System.Type EqualityContract => throw null; } public record D : A { new protected virtual int EqualityContract => throw null; } public record E : A { new protected virtual Type EqualityContract => throw null; } public record F : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(2, 15), // (6,39): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // new protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 39), // (11,31): error CS8874: Record member 'D.EqualityContract' must return 'Type'. // new protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 31), // (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // new protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27), // (21,36): error CS0506: 'F.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "EqualityContract").WithArguments("F.EqualityContract", "A.EqualityContract").WithLocation(21, 36) ); } [Fact] public void EqualityContract_17() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { } public record C : A { protected virtual System.Type EqualityContract => throw null; } public record D : A { protected virtual int EqualityContract => throw null; } public record E : A { protected virtual Type EqualityContract => throw null; } public record F : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0115: 'B.EqualityContract': no suitable method found to override // public record B : A { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(2, 15), // (6,35): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 35), // (11,27): error CS8874: Record member 'D.EqualityContract' must return 'Type'. // protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 27), // (16,23): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 23), // (21,36): error CS0115: 'F.EqualityContract': no suitable method found to override // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_OverrideNotExpected, "EqualityContract").WithArguments("F.EqualityContract").WithLocation(21, 36) ); } [Fact] public void EqualityContract_18() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A .class public auto ansi beforefieldinit B extends A { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class B "; var source = @" public record C : B { } public record D : B { new protected virtual System.Type EqualityContract => throw null; } public record E : B { new protected virtual int EqualityContract => throw null; } public record F : B { new protected virtual Type EqualityContract => throw null; } public record G : B { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8876: 'C.EqualityContract' does not override expected property from 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "C").WithArguments("C.EqualityContract", "B").WithLocation(2, 15), // (6,39): error CS8876: 'D.EqualityContract' does not override expected property from 'B'. // new protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("D.EqualityContract", "B").WithLocation(6, 39), // (11,31): error CS8874: Record member 'E.EqualityContract' must return 'Type'. // new protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("E.EqualityContract", "System.Type").WithLocation(11, 31), // (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // new protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27), // (21,36): error CS8876: 'G.EqualityContract' does not override expected property from 'B'. // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("G.EqualityContract", "B").WithLocation(21, 36) ); } [Fact] public void EqualityContract_19() { var source = @"sealed record A { protected static System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,34): warning CS0628: 'A.EqualityContract': new protected member declared in sealed type // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34), // (3,34): error CS8879: Record member 'A.EqualityContract' must be private. // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34), // (3,34): error CS8877: Record member 'A.EqualityContract' may not be static. // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34), // (3,54): warning CS0628: 'A.EqualityContract.get': new protected member declared in sealed type // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("A.EqualityContract.get").WithLocation(3, 54) ); } [Fact] public void EqualityContract_20() { var source = @"sealed record A { private static System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,32): error CS8877: Record member 'A.EqualityContract' may not be static. // private static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 32) ); } [Fact] public void EqualityContract_21() { var source = @" sealed record A { static void Main() { A a1 = new A(); A a2 = new A(); System.Console.WriteLine(a1.Equals(a2)); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "True").VerifyDiagnostics(); var equalityContract = comp.GetMembers("A.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type A.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Private, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.False(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); } [Fact] public void EqualityContract_22() { var source = @" record A; sealed record B : A { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "True").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.True(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); } [Fact] public void EqualityContract_23() { var source = @" record A { protected static System.Type EqualityContract => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,34): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed. // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 34), // (7,8): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(7, 8) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_24_SetterOnlyProperty() { var src = @" record R { protected virtual System.Type EqualityContract { set { } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,35): error CS8906: Record equality contract property 'R.EqualityContract' must have a get accessor. // protected virtual System.Type EqualityContract { set { } } Diagnostic(ErrorCode.ERR_EqualityContractRequiresGetter, "EqualityContract").WithArguments("R.EqualityContract").WithLocation(4, 35) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_24_GetterAndSetterProperty() { var src = @" _ = new R() == new R2(); record R { protected virtual System.Type EqualityContract { get { System.Console.Write(""RAN ""); return GetType(); } set { } } } record R2 : R; "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_25_SetterOnlyProperty_DerivedRecord() { var src = @" record Base; record R : Base { protected override System.Type EqualityContract { set { } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,36): error CS8906: Record equality contract property 'R.EqualityContract' must have a get accessor. // protected override System.Type EqualityContract { set { } } Diagnostic(ErrorCode.ERR_EqualityContractRequiresGetter, "EqualityContract").WithArguments("R.EqualityContract").WithLocation(5, 36), // (5,55): error CS0546: 'R.EqualityContract.set': cannot override because 'Base.EqualityContract' does not have an overridable set accessor // protected override System.Type EqualityContract { set { } } Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("R.EqualityContract.set", "Base.EqualityContract").WithLocation(5, 55) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_26_SetterOnlyProperty_InMetadata() { // `record Base;` with modified EqualityContract property, method bodies simplified and nullability removed var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object implements class [mscorlib]System.IEquatable`1<class Base> { .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance bool PrintMembers( class [mscorlib] System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Inequality( class Base r1, class Base r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Equality( class Base r1, class Base r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals( object obj ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance bool Equals( class Base other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance class Base '<Clone>$'() cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class Base original ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname newslot virtual instance void set_EqualityContract ( class [mscorlib]System.Type 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } // Property has a setter but no getter .property instance class [mscorlib]System.Type EqualityContract() { .set instance void Base::set_EqualityContract(class [mscorlib]System.Type) } } "; var src = @" record R : Base; "; var comp = CreateCompilationWithIL(src, il); comp.VerifyEmitDiagnostics( // (2,8): error CS0545: 'R.EqualityContract.get': cannot override because 'Base.EqualityContract' does not have an overridable get accessor // record R : Base; Diagnostic(ErrorCode.ERR_NoGetToOverride, "R").WithArguments("R.EqualityContract.get", "Base.EqualityContract").WithLocation(2, 8) ); var src2 = @" record R : Base { protected override System.Type EqualityContract => typeof(R); } "; var comp2 = CreateCompilationWithIL(src2, il); comp2.VerifyEmitDiagnostics( // (4,56): error CS0545: 'R.EqualityContract.get': cannot override because 'Base.EqualityContract' does not have an overridable get accessor // protected override System.Type EqualityContract => typeof(R); Diagnostic(ErrorCode.ERR_NoGetToOverride, "typeof(R)").WithArguments("R.EqualityContract.get", "Base.EqualityContract").WithLocation(4, 56) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_27_GetterAndSetterProperty_ExplicitlyOverridden() { var src = @" _ = new R() == new R2(); record R { protected virtual System.Type EqualityContract { get { System.Console.Write(""RAN ""); return GetType(); } set { } } } record R2 : R { protected override System.Type EqualityContract { get { System.Console.Write(""RAN2 ""); return GetType(); } } } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN RAN2"); } [Fact] public void EqualityOperators_01() { var source = @" record A(int X) { public virtual bool Equals(ref A other) => throw null; static void Main() { Test(null, null); Test(null, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); Test(new A(4), new B(4, 5)); Test(new B(6, 7), new B(6, 7)); Test(new B(8, 9), new B(8, 10)); var a = new A(11); Test(a, a); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } record B(int X, int Y) : A(X); "; var verifier = CompileAndVerify(source, expectedOutput: @" True True False False False False True True True True False False False False True True False False True True True True False False False False True True True True False False ").VerifyDiagnostics(); var comp = (CSharpCompilation)verifier.Compilation; MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(); Assert.Equal("System.Boolean A.op_Equality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single(); Assert.Equal("System.Boolean A.op_Inequality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); verifier.VerifyIL("bool A.op_Equality(A, A)", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0011 IL_0004: ldarg.0 IL_0005: brfalse.s IL_000f IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: callvirt ""bool A.Equals(A)"" IL_000e: ret IL_000f: ldc.i4.0 IL_0010: ret IL_0011: ldc.i4.1 IL_0012: ret } "); verifier.VerifyIL("bool A.op_Inequality(A, A)", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool A.op_Equality(A, A)"" IL_0007: ldc.i4.0 IL_0008: ceq IL_000a: ret } "); } [Fact] public void EqualityOperators_02() { var source = @" record B; record A(int X) : B { public virtual bool Equals(A other) { System.Console.WriteLine(""Equals(A other)""); return base.Equals(other) && X == other.X; } static void Main() { Test(null, null); Test(null, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); var a = new A(11); Test(a, a); Test(new A(3), new B()); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } static void Test(A a1, B b2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == b2, b2 == a1, a1 != b2, b2 != a1); } } "; var verifier = CompileAndVerify(source, expectedOutput: @" True True False False Equals(A other) Equals(A other) False False True True Equals(A other) Equals(A other) Equals(A other) Equals(A other) True True False False Equals(A other) Equals(A other) Equals(A other) Equals(A other) False False True True True True False False Equals(A other) Equals(A other) False False True True ").VerifyDiagnostics( // (6,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(6, 25) ); var comp = (CSharpCompilation)verifier.Compilation; MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(); Assert.Equal("System.Boolean A.op_Equality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single(); Assert.Equal("System.Boolean A.op_Inequality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); verifier.VerifyIL("bool A.op_Equality(A, A)", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0011 IL_0004: ldarg.0 IL_0005: brfalse.s IL_000f IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: callvirt ""bool A.Equals(A)"" IL_000e: ret IL_000f: ldc.i4.0 IL_0010: ret IL_0011: ldc.i4.1 IL_0012: ret } "); verifier.VerifyIL("bool A.op_Inequality(A, A)", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool A.op_Equality(A, A)"" IL_0007: ldc.i4.0 IL_0008: ceq IL_000a: ret } "); } [Fact] public void EqualityOperators_03() { var source = @" record A { public static bool operator==(A r1, A r2) => throw null; public static bool operator==(A r1, string r2) => throw null; public static bool operator!=(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool operator==(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "==").WithArguments("op_Equality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_04() { var source = @" record A { public static bool operator!=(A r1, A r2) => throw null; public static bool operator!=(string r1, A r2) => throw null; public static bool operator==(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool operator!=(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "!=").WithArguments("op_Inequality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_05() { var source = @" record A { public static bool op_Equality(A r1, A r2) => throw null; public static bool op_Equality(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool op_Equality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Equality").WithArguments("op_Equality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_06() { var source = @" record A { public static bool op_Inequality(A r1, A r2) => throw null; public static bool op_Inequality(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool op_Inequality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Inequality").WithArguments("op_Inequality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_07() { var source = @" record A { public static bool Equals(A other) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,8): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 8), // (4,24): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed. // public static bool Equals(A other) Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_08() { var source = @" record A { public virtual string Equals(A other) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,8): error CS0738: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement 'IEquatable<A>.Equals(A)' because it does not have the matching return type of 'bool'. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)", "bool").WithLocation(2, 8), // (4,27): error CS8874: Record member 'A.Equals(A)' must return 'bool'. // public virtual string Equals(A other) Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 27), // (4,27): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual string Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 27) ); } [Theory] [CombinatorialData] public void EqualityOperators_09(bool useImageReference) { var source1 = @" public record A(int X) { } "; var comp1 = CreateCompilation(source1); var source2 = @" class Program { static void Main() { Test(null, null); Test(null, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } "; CompileAndVerify(source2, references: new[] { useImageReference ? comp1.EmitToImageReference() : comp1.ToMetadataReference() }, expectedOutput: @" True True False False False False True True True True False False False False True True ").VerifyDiagnostics(); } [WorkItem(44692, "https://github.com/dotnet/roslyn/issues/44692")] [Fact] public void DuplicateProperty_01() { var src = @"record C(object Q) { public object P { get; } public object P { get; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0102: The type 'C' already contains a definition for 'P' // public object P { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 19)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.Q { get; init; }", "System.Object C.P { get; }", "System.Object C.P { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [WorkItem(44692, "https://github.com/dotnet/roslyn/issues/44692")] [Fact] public void DuplicateProperty_02() { var src = @"record C(object P, object Q) { public object P { get; } public int P { get; } public int Q { get; } public object Q { get; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,27): error CS8866: Record member 'C.Q' must be a readable instance property or field of type 'object' to match positional parameter 'Q'. // record C(object P, object Q) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Q").WithArguments("C.Q", "object", "Q").WithLocation(1, 27), // (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27), // (4,16): error CS0102: The type 'C' already contains a definition for 'P' // public int P { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 16), // (6,19): error CS0102: The type 'C' already contains a definition for 'Q' // public object Q { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("C", "Q").WithLocation(6, 19)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P { get; }", "System.Int32 C.P { get; }", "System.Int32 C.Q { get; }", "System.Object C.Q { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void DuplicateProperty_03() { var src = @"record A { public object P { get; } public object P { get; } public object Q { get; } public int Q { get; } } record B(object Q) : A { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0102: The type 'A' already contains a definition for 'P' // public object P { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("A", "P").WithLocation(4, 19), // (6,16): error CS0102: The type 'A' already contains a definition for 'Q' // public int Q { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("A", "Q").WithLocation(6, 16), // (8,17): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record B(object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(8, 17)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void NominalRecordWith() { var src = @" using System; record C { public int X { get; init; } public string Y; public int Z { get; set; } public static void Main() { var c = new C() { X = 1, Y = ""2"", Z = 3 }; var c2 = new C() { X = 1, Y = ""2"", Z = 3 }; Console.WriteLine(c.Equals(c2)); var c3 = c2 with { X = 3, Y = ""2"", Z = 1 }; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c3.Equals(c2)); Console.WriteLine(c2.X + "" "" + c2.Y + "" "" + c2.Z); } }"; CompileAndVerify(src, expectedOutput: @" True True False 1 2 3").VerifyDiagnostics(); } [Theory] [InlineData(true)] [InlineData(false)] public void WithExprReference(bool emitRef) { var src = @" public record C { public int X { get; init; } } public record D(int Y) : C;"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var src2 = @" using System; class E { public static void Main() { var c = new C() { X = 1 }; var c2 = c with { X = 2 }; Console.WriteLine(c.X); Console.WriteLine(c2.X); var d = new D(2) { X = 1 }; var d2 = d with { X = 2, Y = 3 }; Console.WriteLine(d.X + "" "" + d.Y); Console.WriteLine(d2.X + "" "" + d2.Y); C c3 = d; C c4 = d2; c3 = c3 with { X = 3 }; c4 = c4 with { X = 4 }; d = (D)c3; d2 = (D)c4; Console.WriteLine(d.X + "" "" + d.Y); Console.WriteLine(d2.X + "" "" + d2.Y); } }"; var verifier = CompileAndVerify(src2, references: new[] { emitRef ? comp.EmitToImageReference() : comp.ToMetadataReference() }, expectedOutput: @" 1 2 1 2 2 3 3 2 4 3").VerifyDiagnostics(); verifier.VerifyIL("E.Main", @" { // Code size 318 (0x13e) .maxstack 3 .locals init (C V_0, //c D V_1, //d D V_2, //d2 C V_3, //c3 C V_4, //c4 int V_5) IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: callvirt ""void C.X.init"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0013: dup IL_0014: ldc.i4.2 IL_0015: callvirt ""void C.X.init"" IL_001a: ldloc.0 IL_001b: callvirt ""int C.X.get"" IL_0020: call ""void System.Console.WriteLine(int)"" IL_0025: callvirt ""int C.X.get"" IL_002a: call ""void System.Console.WriteLine(int)"" IL_002f: ldc.i4.2 IL_0030: newobj ""D..ctor(int)"" IL_0035: dup IL_0036: ldc.i4.1 IL_0037: callvirt ""void C.X.init"" IL_003c: stloc.1 IL_003d: ldloc.1 IL_003e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0043: castclass ""D"" IL_0048: dup IL_0049: ldc.i4.2 IL_004a: callvirt ""void C.X.init"" IL_004f: dup IL_0050: ldc.i4.3 IL_0051: callvirt ""void D.Y.init"" IL_0056: stloc.2 IL_0057: ldloc.1 IL_0058: callvirt ""int C.X.get"" IL_005d: stloc.s V_5 IL_005f: ldloca.s V_5 IL_0061: call ""string int.ToString()"" IL_0066: ldstr "" "" IL_006b: ldloc.1 IL_006c: callvirt ""int D.Y.get"" IL_0071: stloc.s V_5 IL_0073: ldloca.s V_5 IL_0075: call ""string int.ToString()"" IL_007a: call ""string string.Concat(string, string, string)"" IL_007f: call ""void System.Console.WriteLine(string)"" IL_0084: ldloc.2 IL_0085: callvirt ""int C.X.get"" IL_008a: stloc.s V_5 IL_008c: ldloca.s V_5 IL_008e: call ""string int.ToString()"" IL_0093: ldstr "" "" IL_0098: ldloc.2 IL_0099: callvirt ""int D.Y.get"" IL_009e: stloc.s V_5 IL_00a0: ldloca.s V_5 IL_00a2: call ""string int.ToString()"" IL_00a7: call ""string string.Concat(string, string, string)"" IL_00ac: call ""void System.Console.WriteLine(string)"" IL_00b1: ldloc.1 IL_00b2: stloc.3 IL_00b3: ldloc.2 IL_00b4: stloc.s V_4 IL_00b6: ldloc.3 IL_00b7: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_00bc: dup IL_00bd: ldc.i4.3 IL_00be: callvirt ""void C.X.init"" IL_00c3: stloc.3 IL_00c4: ldloc.s V_4 IL_00c6: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_00cb: dup IL_00cc: ldc.i4.4 IL_00cd: callvirt ""void C.X.init"" IL_00d2: stloc.s V_4 IL_00d4: ldloc.3 IL_00d5: castclass ""D"" IL_00da: stloc.1 IL_00db: ldloc.s V_4 IL_00dd: castclass ""D"" IL_00e2: stloc.2 IL_00e3: ldloc.1 IL_00e4: callvirt ""int C.X.get"" IL_00e9: stloc.s V_5 IL_00eb: ldloca.s V_5 IL_00ed: call ""string int.ToString()"" IL_00f2: ldstr "" "" IL_00f7: ldloc.1 IL_00f8: callvirt ""int D.Y.get"" IL_00fd: stloc.s V_5 IL_00ff: ldloca.s V_5 IL_0101: call ""string int.ToString()"" IL_0106: call ""string string.Concat(string, string, string)"" IL_010b: call ""void System.Console.WriteLine(string)"" IL_0110: ldloc.2 IL_0111: callvirt ""int C.X.get"" IL_0116: stloc.s V_5 IL_0118: ldloca.s V_5 IL_011a: call ""string int.ToString()"" IL_011f: ldstr "" "" IL_0124: ldloc.2 IL_0125: callvirt ""int D.Y.get"" IL_012a: stloc.s V_5 IL_012c: ldloca.s V_5 IL_012e: call ""string int.ToString()"" IL_0133: call ""string string.Concat(string, string, string)"" IL_0138: call ""void System.Console.WriteLine(string)"" IL_013d: ret }"); } [Theory] [InlineData(true)] [InlineData(false)] public void WithExprReference_WithCovariantReturns(bool emitRef) { var src = @" public record C { public int X { get; init; } } public record D(int Y) : C;"; var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? src : new[] { src, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics(); var src2 = @" using System; class E { public static void Main() { var c = new C() { X = 1 }; var c2 = CHelper(c); Console.WriteLine(c.X); Console.WriteLine(c2.X); var d = new D(2) { X = 1 }; var d2 = DHelper(d); Console.WriteLine(d.X + "" "" + d.Y); Console.WriteLine(d2.X + "" "" + d2.Y); } private static C CHelper(C c) { return c with { X = 2 }; } private static D DHelper(D d) { return d with { X = 2, Y = 3 }; } }"; var verifier = CompileAndVerify(RuntimeUtilities.IsCoreClrRuntime ? src2 : new[] { src2, IsExternalInitTypeDefinition }, references: new[] { emitRef ? comp.EmitToImageReference() : comp.ToMetadataReference() }, expectedOutput: @" 1 2 1 2 2 3", targetFramework: TargetFramework.StandardLatest).VerifyDiagnostics().VerifyIL("E.CHelper", @" { // Code size 14 (0xe) .maxstack 3 IL_0000: ldarg.0 IL_0001: callvirt ""C C.<Clone>$()"" IL_0006: dup IL_0007: ldc.i4.2 IL_0008: callvirt ""void C.X.init"" IL_000d: ret } "); if (RuntimeUtilities.IsCoreClrRuntime) { verifier.VerifyIL("E.DHelper", @" { // Code size 21 (0x15) .maxstack 3 IL_0000: ldarg.0 IL_0001: callvirt ""D D.<Clone>$()"" IL_0006: dup IL_0007: ldc.i4.2 IL_0008: callvirt ""void C.X.init"" IL_000d: dup IL_000e: ldc.i4.3 IL_000f: callvirt ""void D.Y.init"" IL_0014: ret } "); } else { verifier.VerifyIL("E.DHelper", @" { // Code size 26 (0x1a) .maxstack 3 IL_0000: ldarg.0 IL_0001: callvirt ""C C.<Clone>$()"" IL_0006: castclass ""D"" IL_000b: dup IL_000c: ldc.i4.2 IL_000d: callvirt ""void C.X.init"" IL_0012: dup IL_0013: ldc.i4.3 IL_0014: callvirt ""void D.Y.init"" IL_0019: ret } "); } } private static ImmutableArray<Symbol> GetProperties(CSharpCompilation comp, string typeName) { return comp.GetMember<NamedTypeSymbol>(typeName).GetMembers().WhereAsArray(m => m.Kind == SymbolKind.Property); } [Fact] public void BaseArguments_01() { var src = @" using System; record Base { public Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} } record C(int X, int Y = 123) : Base(X, Y) { int Z = 123; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.Z); } C(int X, int Y, int Z = 124) : this(X, Y) {} }"; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2 123").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 31 (0x1f) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.s 123 IL_0011: stfld ""int C.Z"" IL_0016: ldarg.0 IL_0017: ldarg.1 IL_0018: ldarg.2 IL_0019: call ""Base..ctor(int, int)"" IL_001e: ret } "); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal(Accessibility.Public, symbol.ContainingSymbol.DeclaredAccessibility); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single(); Assert.Equal("Base(X, Y)", baseWithargs.ToString()); Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs)); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString()); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString()); model = comp.GetSemanticModel(tree); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString()); model = comp.GetSemanticModel(tree); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString()); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); #nullable disable var operation = model.GetOperation(baseWithargs); VerifyOperationTree(comp, operation, @" IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') 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) "); Assert.Null(model.GetOperation(baseWithargs.Type)); Assert.Null(model.GetOperation(baseWithargs.Parent)); Assert.Same(operation.Parent.Parent, model.GetOperation(baseWithargs.Parent.Parent)); Assert.Equal(SyntaxKind.RecordDeclaration, baseWithargs.Parent.Parent.Kind()); VerifyOperationTree(comp, operation.Parent.Parent, @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'record C(in ... }') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') 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) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'record C(in ... }') ExpressionBody: null "); Assert.Null(operation.Parent.Parent.Parent); VerifyFlowGraph(comp, operation.Parent.Parent.Syntax, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') 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) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); var equalsValue = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First(); Assert.Equal("= 123", equalsValue.ToString()); model.VerifyOperationTree(equalsValue, @" IParameterInitializerOperation (Parameter: [System.Int32 Y = 123]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= 123') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 123) (Syntax: '123') "); #nullable enable } { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": this(X, Y)", baseWithargs.ToString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString()); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString())); model.VerifyOperationTree(baseWithargs, @" IInvocationOperation ( C..ctor(System.Int32 X, [System.Int32 Y = 123])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': this(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ': this(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') 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) "); var equalsValue = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Last(); Assert.Equal("= 124", equalsValue.ToString()); model.VerifyOperationTree(equalsValue, @" IParameterInitializerOperation (Parameter: [System.Int32 Z = 124]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= 124') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 124) (Syntax: '124') "); model.VerifyOperationTree(baseWithargs.Parent, @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'C(int X, in ... is(X, Y) {}') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': this(X, Y)') Expression: IInvocationOperation ( C..ctor(System.Int32 X, [System.Int32 Y = 123])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': this(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ': this(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') 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) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{}') ExpressionBody: null "); } } [Fact] public void BaseArguments_02() { var src = @" using System; record Base { public Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} } record C(int X) : Base(Test(X, out var y), y) { public static void Main() { var c = new C(1); } private static int Test(int x, out int y) { y = 2; return x; } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var yDecl = OutVarTests.GetOutVarDeclaration(tree, "y"); var yRef = OutVarTests.GetReferences(tree, "y").ToArray(); Assert.Equal(2, yRef.Length); OutVarTests.VerifyModelForOutVar(model, yDecl, yRef[0]); OutVarTests.VerifyNotAnOutLocal(model, yRef[1]); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1); Assert.Equal("Test(X, out var y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); var y = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "y").First(); Assert.Equal("y", y.Parent!.ToString()); Assert.Equal("(Test(X, out var y), y)", y.Parent!.Parent!.ToString()); Assert.Equal("Base(Test(X, out var y), y)", y.Parent!.Parent!.Parent!.ToString()); symbol = model.GetSymbolInfo(y).Symbol; Assert.Equal(SymbolKind.Local, symbol!.Kind); Assert.Equal("System.Int32 y", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "y")); Assert.Contains("y", model.LookupNames(x.SpanStart)); var test = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").First(); Assert.Equal("(Test(X, out var y), y)", test.Parent!.Parent!.Parent!.ToString()); symbol = model.GetSymbolInfo(test).Symbol; Assert.Equal(SymbolKind.Method, symbol!.Kind); Assert.Equal("System.Int32 C.Test(System.Int32 x, out System.Int32 y)", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "Test")); Assert.Contains("Test", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_03() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (13,16): error CS8861: Unexpected argument list. // record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 16) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_04() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C(int X, int Y) { } partial record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (17,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[0])); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[1])); } [Fact] public void BaseArguments_05() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C : Base(X, Y) { } partial record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (13,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 24), // (17,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray(); Assert.Equal(2, xs.Length); foreach (var x in xs) { Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[0])); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[1])); } [Fact] public void BaseArguments_06() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C(int X, int Y) : Base(X, Y) { } partial record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (17,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray(); Assert.Equal(2, xs.Length); var x = xs[0]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); x = xs[1]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); model.VerifyOperationTree(recordDeclarations[0], @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'partial rec ... }') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') 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) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'partial rec ... }') ExpressionBody: null "); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[1])); } [Fact] public void BaseArguments_07() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C : Base(X, Y) { } partial record C(int X, int Y) : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (13,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray(); Assert.Equal(2, xs.Length); var x = xs[1]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); x = xs[0]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[0])); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); model.VerifyOperationTree(recordDeclarations[1], @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'partial rec ... }') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') 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) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'partial rec ... }') ExpressionBody: null "); } [Fact] public void BaseArguments_08() { var src = @" record Base { public Base(int Y) { } public Base() {} } record C(int X) : Base(Y) { public int Y = 0; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.Y' // record C(int X) : Base(Y) Diagnostic(ErrorCode.ERR_ObjectRequired, "Y").WithArguments("C.Y").WithLocation(11, 24) ); } [Fact] public void BaseArguments_09() { var src = @" record Base { public Base(int X) { } public Base() {} } record C(int X) : Base(this.X) { public int Y = 0; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,24): error CS0027: Keyword 'this' is not available in the current context // record C(int X) : Base(this.X) Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(11, 24) ); } [Fact] public void BaseArguments_10() { var src = @" record Base { public Base(int X) { } public Base() {} } record C(dynamic X) : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,27): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments. // record C(dynamic X) : Base(X) Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, "(X)").WithLocation(11, 27) ); } [Fact] public void BaseArguments_11() { var src = @" record Base { public Base(int X, int Y) { } public Base() {} } record C(int X) : Base(Test(X, out var y), y) { int Z = y; private static int Test(int x, out int y) { y = 2; return x; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,13): error CS0103: The name 'y' does not exist in the current context // int Z = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(13, 13) ); } [Fact] public void BaseArguments_12() { var src = @" using System; class Base { public Base(int X) { } } class C : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (11,7): error CS7036: There is no argument given that corresponds to the required formal parameter 'X' of 'Base.Base(int)' // class C : Base(X) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("X", "Base.Base(int)").WithLocation(11, 7), // (11,15): error CS8861: Unexpected argument list. // class C : Base(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(11, 15) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_13() { var src = @" using System; interface Base { } struct C : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (8,16): error CS8861: Unexpected argument list. // struct C : Base(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(8, 16) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_14() { var src = @" using System; interface Base { } interface C : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (8,19): error CS8861: Unexpected argument list. // interface C : Base(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(8, 19) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_15() { var src = @" using System; record Base { public Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} } partial record C { } partial record C(int X, int Y) : Base(X, Y) { int Z = 123; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.Z); } } partial record C { } "; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2 123").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 31 (0x1f) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.s 123 IL_0011: stfld ""int C.Z"" IL_0016: ldarg.0 IL_0017: ldarg.1 IL_0018: ldarg.2 IL_0019: call ""Base..ctor(int, int)"" IL_001e: ret } "); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_16() { var src = @" using System; record Base { public Base(Func<int> X) { Console.WriteLine(X()); } public Base() {} } record C(int X) : Base(() => X) { public static void Main() { var c = new C(1); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"1").VerifyDiagnostics(); } [Fact] public void BaseArguments_17() { var src = @" record Base { public Base(int X, int Y) { } public Base() {} } record C(int X, int y) : Base(Test(X, out var y), Test(X, out var z)) { int Z = z; private static int Test(int x, out int y) { y = 2; return x; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,28): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // : Base(Test(X, out var y), Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(12, 28), // (15,13): error CS0103: The name 'z' does not exist in the current context // int Z = z; Diagnostic(ErrorCode.ERR_NameNotInContext, "z").WithArguments("z").WithLocation(15, 13) ); } [Fact] public void BaseArguments_18() { var src = @" record Base { public Base(int X, int Y) { } public Base() {} } record C(int X, int y) : Base(Test(X + 1, out var z), Test(X + 2, out var z)) { private static int Test(int x, out int y) { y = 2; return x; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,32): error CS0128: A local variable or function named 'z' is already defined in this scope // Test(X + 2, out var z)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "z").WithArguments("z").WithLocation(13, 32) ); } [Fact] public void BaseArguments_19() { var src = @" record Base { public Base(int X) { } public Base() {} } record C(int X, int Y) : Base(GetInt(X, out var xx) + xx, Y), I { C(int X, int Y, int Z) : this(X, Y, Z, 1) { return; } static int GetInt(int x1, out int x2) { throw null; } } interface I {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,30): error CS1729: 'Base' does not contain a constructor that takes 2 arguments // record C(int X, int Y) : Base(GetInt(X, out var xx) + xx, Y) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(GetInt(X, out var xx) + xx, Y)").WithArguments("Base", "2").WithLocation(11, 30), // (13,30): error CS1729: 'C' does not contain a constructor that takes 4 arguments // C(int X, int Y, int Z) : this(X, Y, Z, 1) {} Diagnostic(ErrorCode.ERR_BadCtorArgCount, "this").WithArguments("C", "4").WithLocation(13, 30) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); SymbolInfo symbolInfo; PrimaryConstructorBaseTypeSyntax speculativePrimaryInitializer; ConstructorInitializerSyntax speculativeBaseInitializer; { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single(); Assert.Equal("Base(GetInt(X, out var xx) + xx, Y)", baseWithargs.ToString()); Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs)); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); string[] candidates = new[] { "Base..ctor(Base original)", "Base..ctor(System.Int32 X)", "Base..ctor()" }; Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); model = comp.GetSemanticModel(tree); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); model = comp.GetSemanticModel(tree); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); SemanticModel speculativeModel; speculativePrimaryInitializer = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1))); speculativeBaseInitializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, speculativePrimaryInitializer.ArgumentList); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.False(model.TryGetSpeculativeSemanticModel(tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().SpanStart, speculativeBaseInitializer, out _)); var otherBasePosition = ((BaseListSyntax)baseWithargs.Parent!).Types[1].SpanStart; Assert.False(model.TryGetSpeculativeSemanticModel(otherBasePosition, speculativePrimaryInitializer, out _)); Assert.True(model.TryGetSpeculativeSemanticModel(baseWithargs.SpanStart, speculativePrimaryInitializer, out speculativeModel!)); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel!.GetSymbolInfo((SyntaxNode)speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel.GetSymbolInfo(speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", CSharpExtensions.GetSymbolInfo(speculativeModel, speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.True(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out speculativeModel!)); var xxDecl = OutVarTests.GetOutVarDeclaration(speculativePrimaryInitializer.SyntaxTree, "xx"); var xxRef = OutVarTests.GetReferences(speculativePrimaryInitializer.SyntaxTree, "xx").ToArray(); Assert.Equal(1, xxRef.Length); OutVarTests.VerifyModelForOutVar(speculativeModel, xxDecl, xxRef); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel!.GetSymbolInfo((SyntaxNode)speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel.GetSymbolInfo(speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", CSharpExtensions.GetSymbolInfo(speculativeModel, speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Throws<ArgumentNullException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (PrimaryConstructorBaseTypeSyntax)null!, out _)); Assert.Throws<ArgumentException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, baseWithargs, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(otherBasePosition, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, otherBasePosition, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.SpanStart, speculativePrimaryInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single().ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": this(X, Y, Z, 1)", baseWithargs.ToString()); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); string[] candidates = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)", "C..ctor(System.Int32 X, System.Int32 Y, System.Int32 Z)" }; Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString())); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } } [Fact] public void BaseArguments_20() { var src = @" class Base { public Base(int X) { } public Base() {} } class C : Base(GetInt(X, out var xx) + xx, Y), I { C(int X, int Y, int Z) : base(X, Y, Z, 1) { return; } static int GetInt(int x1, out int x2) { throw null; } } interface I {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,15): error CS8861: Unexpected argument list. // class C : Base(GetInt(X, out var xx) + xx, Y), I Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(GetInt(X, out var xx) + xx, Y)").WithLocation(11, 15), // (13,30): error CS1729: 'Base' does not contain a constructor that takes 4 arguments // C(int X, int Y, int Z) : base(X, Y, Z, 1) { return; } Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("Base", "4").WithLocation(13, 30) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); SymbolInfo symbolInfo; PrimaryConstructorBaseTypeSyntax speculativePrimaryInitializer; ConstructorInitializerSyntax speculativeBaseInitializer; { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single(); Assert.Equal("Base(GetInt(X, out var xx) + xx, Y)", baseWithargs.ToString()); Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs)); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); Assert.Empty(model.GetMemberGroup(baseWithargs)); speculativePrimaryInitializer = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1))); speculativeBaseInitializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, speculativePrimaryInitializer.ArgumentList); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.False(model.TryGetSpeculativeSemanticModel(tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().SpanStart, speculativeBaseInitializer, out _)); var otherBasePosition = ((BaseListSyntax)baseWithargs.Parent!).Types[1].SpanStart; Assert.False(model.TryGetSpeculativeSemanticModel(otherBasePosition, speculativePrimaryInitializer, out _)); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.SpanStart, speculativePrimaryInitializer, out _)); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _)); Assert.Throws<ArgumentNullException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (PrimaryConstructorBaseTypeSyntax)null!, out _)); Assert.Throws<ArgumentException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, baseWithargs, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(otherBasePosition, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, otherBasePosition, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single().ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": base(X, Y, Z, 1)", baseWithargs.ToString()); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); string[] candidates = new[] { "Base..ctor(System.Int32 X)", "Base..ctor()" }; Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString())); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } } [Fact] public void Equality_02() { var source = @"using static System.Console; record C; class Program { static void Main() { var x = new C(); var y = new C(); WriteLine(x.Equals(y) && x.GetHashCode() == y.GetHashCode()); WriteLine(((object)x).Equals(y)); WriteLine(((System.IEquatable<C>)x).Equals(y)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var ordinaryMethods = comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray(); Assert.Equal(6, ordinaryMethods.Length); foreach (var m in ordinaryMethods) { Assert.True(m.IsImplicitlyDeclared); } var verifier = CompileAndVerify(comp, expectedOutput: @"True True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("C.Equals(object)", @"{ // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: callvirt ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type C.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ret }"); } [Fact] public void Equality_03() { var source = @"using static System.Console; record C { private static int _nextId = 0; private int _id; public C() { _id = _nextId++; } } class Program { static void Main() { var x = new C(); var y = new C(); WriteLine(x.Equals(x)); WriteLine(x.Equals(y)); WriteLine(y.Equals(y)); } }"; var verifier = CompileAndVerify(source, expectedOutput: @"True False True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C._id"" IL_0025: ldarg.1 IL_0026: ldfld ""int C._id"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type C.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ldc.i4 0xa5555529 IL_0015: mul IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C._id"" IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_0026: add IL_0027: ret }"); var clone = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.True(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Fact] public void Equality_04() { var source = @"using static System.Console; record A; record B1(int P) : A { internal B1() : this(0) { } // Use record base call syntax instead internal int P { get; set; } // Use record base call syntax instead } record B2(int P) : A { internal B2() : this(0) { } // Use record base call syntax instead internal int P { get; set; } // Use record base call syntax instead } class Program { static B1 NewB1(int p) => new B1 { P = p }; // Use record base call syntax instead static B2 NewB2(int p) => new B2 { P = p }; // Use record base call syntax instead static void Main() { WriteLine(new A().Equals(NewB1(1))); WriteLine(NewB1(1).Equals(new A())); WriteLine(NewB1(1).Equals(NewB2(1))); WriteLine(new A().Equals((A)NewB2(1))); WriteLine(((A)NewB2(1)).Equals(new A())); WriteLine(((A)NewB2(1)).Equals(NewB2(1)) && ((A)NewB2(1)).GetHashCode() == NewB2(1).GetHashCode()); WriteLine(NewB2(1).Equals((A)NewB2(1))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"False False False False False True True").VerifyDiagnostics( // (3,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B1(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(3, 15), // (8,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B2(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(8, 15) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("B1.Equals(B1)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int B1.<P>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int B1.<P>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); verifier.VerifyIL("B1.GetHashCode()", @"{ // Code size 30 (0x1e) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""int B1.<P>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_001c: add IL_001d: ret }"); } [Fact] public void Equality_05() { var source = @"using static System.Console; record A(int P) { internal A() : this(0) { } // Use record base call syntax instead internal int P { get; set; } // Use record base call syntax instead } record B1(int P) : A { internal B1() : this(0) { } // Use record base call syntax instead } record B2(int P) : A { internal B2() : this(0) { } // Use record base call syntax instead } class Program { static A NewA(int p) => new A { P = p }; // Use record base call syntax instead static B1 NewB1(int p) => new B1 { P = p }; // Use record base call syntax instead static B2 NewB2(int p) => new B2 { P = p }; // Use record base call syntax instead static void Main() { WriteLine(NewA(1).Equals(NewA(2))); WriteLine(NewA(1).Equals(NewA(1)) && NewA(1).GetHashCode() == NewA(1).GetHashCode()); WriteLine(NewA(1).Equals(NewB1(1))); WriteLine(NewB1(1).Equals(NewA(1))); WriteLine(NewB1(1).Equals(NewB2(1))); WriteLine(NewA(1).Equals((A)NewB2(1))); WriteLine(((A)NewB2(1)).Equals(NewA(1))); WriteLine(((A)NewB2(1)).Equals(NewB2(1))); WriteLine(NewB2(1).Equals((A)NewB2(1))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"False True False False False False False True True").VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record A(int P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14), // (7,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B1(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(7, 15), // (11,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B2(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(11, 15) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int A.<P>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int A.<P>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("B1.Equals(B1)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); verifier.VerifyIL("B1.GetHashCode()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ret }"); } [Fact] public void Equality_06() { var source = @" using System; using static System.Console; record A; record B : A { protected override Type EqualityContract => typeof(A); public virtual bool Equals(B b) => base.Equals((A)b); } record C : B; class Program { static void Main() { WriteLine(new A().Equals(new A())); WriteLine(new A().Equals(new B())); WriteLine(new A().Equals(new C())); WriteLine(new B().Equals(new A())); WriteLine(new B().Equals(new B())); WriteLine(new B().Equals(new C())); WriteLine(new C().Equals(new A())); WriteLine(new C().Equals(new B())); WriteLine(new C().Equals(new C())); WriteLine(((A)new C()).Equals(new A())); WriteLine(((A)new C()).Equals(new B())); WriteLine(((A)new C()).Equals(new C())); WriteLine(new C().Equals((A)new C())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().First(); Assert.Null(model.GetOperation(recordDeclaration)); var verifier = CompileAndVerify(comp, expectedOutput: @"True True False False True False False False True False False True True").VerifyDiagnostics( // (8,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(8, 25) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); } [Fact] public void Equality_07() { var source = @"using System; using static System.Console; record A; record B : A; record C : B; class Program { static void Main() { WriteLine(new A().Equals(new A())); WriteLine(new A().Equals(new B())); WriteLine(new A().Equals(new C())); WriteLine(new B().Equals(new A())); WriteLine(new B().Equals(new B())); WriteLine(new B().Equals(new C())); WriteLine(new C().Equals(new A())); WriteLine(new C().Equals(new B())); WriteLine(new C().Equals(new C())); WriteLine(((A)new B()).Equals(new A())); WriteLine(((A)new B()).Equals(new B())); WriteLine(((A)new B()).Equals(new C())); WriteLine(((A)new C()).Equals(new A())); WriteLine(((A)new C()).Equals(new B())); WriteLine(((A)new C()).Equals(new C())); WriteLine(((B)new C()).Equals(new A())); WriteLine(((B)new C()).Equals(new B())); WriteLine(((B)new C()).Equals(new C())); WriteLine(new C().Equals((A)new C())); WriteLine(((IEquatable<A>)new B()).Equals(new A())); WriteLine(((IEquatable<A>)new B()).Equals(new B())); WriteLine(((IEquatable<A>)new B()).Equals(new C())); WriteLine(((IEquatable<A>)new C()).Equals(new A())); WriteLine(((IEquatable<A>)new C()).Equals(new B())); WriteLine(((IEquatable<A>)new C()).Equals(new C())); WriteLine(((IEquatable<B>)new C()).Equals(new A())); WriteLine(((IEquatable<B>)new C()).Equals(new B())); WriteLine(((IEquatable<B>)new C()).Equals(new C())); WriteLine(((IEquatable<C>)new C()).Equals(new C())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"True False False False True False False False True False True False False False True False False True True False True False False False True False False True True").VerifyDiagnostics(); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("B.Equals(A)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("C.Equals(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.get_EqualityContract"), isOverride: false); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.get_EqualityContract"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C.get_EqualityContract"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName), isOverride: false); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.CloneMethodName), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.GetHashCode"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.GetHashCode"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C.GetHashCode"), isOverride: true); VerifyVirtualMethods(comp.GetMembers("A.Equals"), ("System.Boolean A.Equals(A? other)", false), ("System.Boolean A.Equals(System.Object? obj)", true)); VerifyVirtualMethods(comp.GetMembers("B.Equals"), ("System.Boolean B.Equals(B? other)", false), ("System.Boolean B.Equals(A? other)", true), ("System.Boolean B.Equals(System.Object? obj)", true)); ImmutableArray<Symbol> cEquals = comp.GetMembers("C.Equals"); VerifyVirtualMethods(cEquals, ("System.Boolean C.Equals(C? other)", false), ("System.Boolean C.Equals(B? other)", true), ("System.Boolean C.Equals(System.Object? obj)", true)); var baseEquals = cEquals[1]; Assert.Equal("System.Boolean C.Equals(B? other)", baseEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, baseEquals.DeclaredAccessibility); Assert.True(baseEquals.IsOverride); Assert.True(baseEquals.IsSealed); Assert.True(baseEquals.IsImplicitlyDeclared); } private static void VerifyVirtualMethod(MethodSymbol method, bool isOverride) { Assert.Equal(!isOverride, method.IsVirtual); Assert.Equal(isOverride, method.IsOverride); Assert.True(method.IsMetadataVirtual()); Assert.Equal(!isOverride, method.IsMetadataNewSlot()); } private static void VerifyVirtualMethods(ImmutableArray<Symbol> members, params (string displayString, bool isOverride)[] values) { Assert.Equal(members.Length, values.Length); for (int i = 0; i < members.Length; i++) { var method = (MethodSymbol)members[i]; (string displayString, bool isOverride) = values[i]; Assert.Equal(displayString, method.ToTestDisplayString(includeNonNullable: true)); VerifyVirtualMethod(method, isOverride); } } [WorkItem(44895, "https://github.com/dotnet/roslyn/issues/44895")] [Fact] public void Equality_08() { var source = @" using System; using static System.Console; record A(int X) { internal A() : this(0) { } // Use record base call syntax instead internal int X { get; set; } // Use record base call syntax instead } record B : A { internal B() { } // Use record base call syntax instead internal B(int X, int Y) : base(X) { this.Y = Y; } internal int Y { get; set; } protected override Type EqualityContract => typeof(A); public virtual bool Equals(B b) => base.Equals((A)b); } record C(int X, int Y, int Z) : B { internal C() : this(0, 0, 0) { } // Use record base call syntax instead internal int Z { get; set; } // Use record base call syntax instead } class Program { static A NewA(int x) => new A { X = x }; // Use record base call syntax instead static B NewB(int x, int y) => new B { X = x, Y = y }; static C NewC(int x, int y, int z) => new C { X = x, Y = y, Z = z }; static void Main() { WriteLine(NewA(1).Equals(NewA(1))); WriteLine(NewA(1).Equals(NewB(1, 2))); WriteLine(NewA(1).Equals(NewC(1, 2, 3))); WriteLine(NewB(1, 2).Equals(NewA(1))); WriteLine(NewB(1, 2).Equals(NewB(1, 2))); WriteLine(NewB(1, 2).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewA(1))); WriteLine(NewC(1, 2, 3).Equals(NewB(1, 2))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(4, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 4))); WriteLine(((A)NewB(1, 2)).Equals(NewA(1))); WriteLine(((A)NewB(1, 2)).Equals(NewB(1, 2))); WriteLine(((A)NewB(1, 2)).Equals(NewC(1, 2, 3))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewC(1, 2, 3))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewC(1, 2, 3)) && NewC(1, 2, 3).GetHashCode() == NewC(1, 2, 3).GetHashCode()); WriteLine(NewC(1, 2, 3).Equals((A)NewC(1, 2, 3))); } }"; // https://github.com/dotnet/roslyn/issues/44895: C.Equals() should compare B.Y. var verifier = CompileAndVerify(source, expectedOutput: @"True True False False True False False False True False True False False True False False False True False False True True").VerifyDiagnostics( // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (15,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(15, 25), // (17,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(17, 14), // (17,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(17, 21), // (17,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(17, 28) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int A.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int A.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); // https://github.com/dotnet/roslyn/issues/44895: C.Equals() should compare B.Y. verifier.VerifyIL("C.Equals(C)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int C.<Z>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int C.<Z>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 30 (0x1e) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int B.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""int C.<Z>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_001c: add IL_001d: ret }"); } [Fact] public void Equality_09() { var source = @"using static System.Console; record A(int X) { internal A() : this(0) { } // Use record base call syntax instead internal int X { get; set; } // Use record base call syntax instead } record B(int X, int Y) : A { internal B() : this(0, 0) { } // Use record base call syntax instead internal int Y { get; set; } } record C(int X, int Y, int Z) : B { internal C() : this(0, 0, 0) { } // Use record base call syntax instead internal int Z { get; set; } // Use record base call syntax instead } class Program { static A NewA(int x) => new A { X = x }; // Use record base call syntax instead static B NewB(int x, int y) => new B { X = x, Y = y }; static C NewC(int x, int y, int z) => new C { X = x, Y = y, Z = z }; static void Main() { WriteLine(NewA(1).Equals(NewA(1))); WriteLine(NewA(1).Equals(NewB(1, 2))); WriteLine(NewA(1).Equals(NewC(1, 2, 3))); WriteLine(NewB(1, 2).Equals(NewA(1))); WriteLine(NewB(1, 2).Equals(NewB(1, 2))); WriteLine(NewB(1, 2).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewA(1))); WriteLine(NewC(1, 2, 3).Equals(NewB(1, 2))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(4, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 4))); WriteLine(((A)NewB(1, 2)).Equals(NewA(1))); WriteLine(((A)NewB(1, 2)).Equals(NewB(1, 2))); WriteLine(((A)NewB(1, 2)).Equals(NewC(1, 2, 3))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewC(1, 2, 3))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals((A)NewC(1, 2, 3))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().ElementAt(1); Assert.Equal("B", recordDeclaration.Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclaration)); var verifier = CompileAndVerify(comp, expectedOutput: @"True False False False True False False False True False False False False True False False False True False False True True").VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14), // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14), // (7,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 21), // (12,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(12, 14), // (12,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(12, 21), // (12,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(12, 28) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int A.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int A.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("B.Equals(A)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int B.<Y>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int B.<Y>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); verifier.VerifyIL("C.Equals(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int C.<Z>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int C.<Z>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); } [Fact] public void Equality_11() { var source = @"using System; record A { protected virtual Type EqualityContract => typeof(object); } record B1(object P) : A; record B2(object P) : A; class Program { static void Main() { Console.WriteLine(new A().Equals(new A())); Console.WriteLine(new A().Equals(new B1((object)null))); Console.WriteLine(new B1((object)null).Equals(new A())); Console.WriteLine(new B1((object)null).Equals(new B1((object)null))); Console.WriteLine(new B1((object)null).Equals(new B2((object)null))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); // init-only is unverifiable CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"True False False True False").VerifyDiagnostics(); } [Fact] public void Equality_12() { var source = @"using System; abstract record A { public A() { } protected abstract Type EqualityContract { get; } } record B1(object P) : A; record B2(object P) : A; class Program { static void Main() { var b1 = new B1((object)null); var b2 = new B2((object)null); Console.WriteLine(b1.Equals(b1)); Console.WriteLine(b1.Equals(b2)); Console.WriteLine(((A)b1).Equals(b1)); Console.WriteLine(((A)b1).Equals(b2)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); // init-only is unverifiable CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"True False True False").VerifyDiagnostics(); } [Fact] public void Equality_13() { var source = @"record A { protected System.Type EqualityContract => typeof(A); } record B : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,27): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed. // protected System.Type EqualityContract => typeof(A); Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 27), // (5,8): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(5, 8)); } [Fact] public void Equality_14() { var source = @"record A; record B : A { protected sealed override System.Type EqualityContract => typeof(B); } record C : B; "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics( // (4,43): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed. // protected sealed override System.Type EqualityContract => typeof(B); Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(4, 43), // (6,8): error CS0239: 'C.EqualityContract': cannot override inherited member 'B.EqualityContract' because it is sealed // record C : B; Diagnostic(ErrorCode.ERR_CantOverrideSealed, "C").WithArguments("C.EqualityContract", "B.EqualityContract").WithLocation(6, 8)); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); string expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses ? "B B." + WellKnownMemberNames.CloneMethodName + "()" : "A B." + WellKnownMemberNames.CloneMethodName + "()"; var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Type B.EqualityContract.get", "System.String B.ToString()", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", expectedClone, "B..ctor(B original)", "B..ctor()", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Equality_15() { var source = @"using System; record A; record B1 : A { public B1(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(A); public virtual bool Equals(B1 o) => base.Equals((A)o); } record B2 : A { public B2(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(B2); public virtual bool Equals(B2 o) => base.Equals((A)o); } class Program { static void Main() { Console.WriteLine(new B1(1).Equals(new B1(2))); Console.WriteLine(new B1(1).Equals(new B2(1))); Console.WriteLine(new B2(1).Equals(new B2(2))); } }"; CompileAndVerify(source, expectedOutput: @"True False True").VerifyDiagnostics( // (8,25): warning CS8851: 'B1' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B1 o) => base.Equals((A)o); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B1").WithLocation(8, 25), // (15,25): warning CS8851: 'B2' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B2 o) => base.Equals((A)o); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B2").WithLocation(15, 25) ); } [Fact] public void Equality_16() { var source = @"using System; record A; record B1 : A { public B1(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(string); public virtual bool Equals(B1 b) => base.Equals((A)b); } record B2 : A { public B2(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(string); public virtual bool Equals(B2 b) => base.Equals((A)b); } class Program { static void Main() { Console.WriteLine(new B1(1).Equals(new B1(2))); Console.WriteLine(new B1(1).Equals(new B2(2))); Console.WriteLine(new B2(1).Equals(new B2(2))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"True False True").VerifyDiagnostics( // (8,25): warning CS8851: 'B1' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B1 b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B1").WithLocation(8, 25), // (15,25): warning CS8851: 'B2' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B2 b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B2").WithLocation(15, 25) ); } [Fact] public void Equality_17() { var source = @"using static System.Console; record A; record B1(int P) : A { } record B2(int P) : A { } class Program { static void Main() { WriteLine(new B1(1).Equals(new B1(1))); WriteLine(new B1(1).Equals(new B1(2))); WriteLine(new B2(3).Equals(new B2(3))); WriteLine(new B2(3).Equals(new B2(4))); WriteLine(((A)new B1(1)).Equals(new B1(1))); WriteLine(((A)new B1(1)).Equals(new B1(2))); WriteLine(((A)new B2(3)).Equals(new B2(3))); WriteLine(((A)new B2(3)).Equals(new B2(4))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); // init-only is unverifiable CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"True False True False True False True False").VerifyDiagnostics(); var actualMembers = comp.GetMember<NamedTypeSymbol>("B1").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "B1..ctor(System.Int32 P)", "System.Type B1.EqualityContract.get", "System.Type B1.EqualityContract { get; }", "System.Int32 B1.<P>k__BackingField", "System.Int32 B1.P.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B1.P.init", "System.Int32 B1.P { get; init; }", "System.String B1.ToString()", "System.Boolean B1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B1.op_Inequality(B1? left, B1? right)", "System.Boolean B1.op_Equality(B1? left, B1? right)", "System.Int32 B1.GetHashCode()", "System.Boolean B1.Equals(System.Object? obj)", "System.Boolean B1.Equals(A? other)", "System.Boolean B1.Equals(B1? other)", "A B1." + WellKnownMemberNames.CloneMethodName + "()", "B1..ctor(B1 original)", "void B1.Deconstruct(out System.Int32 P)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Theory] [InlineData(false)] [InlineData(true)] public void Equality_18(bool useCompilationReference) { var sourceA = @"public record A;"; var comp = CreateCompilation(sourceA); comp.VerifyDiagnostics(); var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference(); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.get_EqualityContract"), isOverride: false); VerifyVirtualMethods(comp.GetMembers("A.Equals"), ("System.Boolean A.Equals(A? other)", false), ("System.Boolean A.Equals(System.Object? obj)", true)); var sourceB = @"record B : A;"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.get_EqualityContract"), isOverride: true); VerifyVirtualMethods(comp.GetMembers("B.Equals"), ("System.Boolean B.Equals(B? other)", false), ("System.Boolean B.Equals(A? other)", true), ("System.Boolean B.Equals(System.Object? obj)", true)); } [Fact] public void Equality_19() { var source = @"using static System.Console; record A<T>; record B : A<int>; class Program { static void Main() { WriteLine(new A<int>().Equals(new A<int>())); WriteLine(new A<int>().Equals(new B())); WriteLine(new B().Equals(new A<int>())); WriteLine(new B().Equals(new B())); WriteLine(((A<int>)new B()).Equals(new A<int>())); WriteLine(((A<int>)new B()).Equals(new B())); WriteLine(new B().Equals((A<int>)new B())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"True False False True False True True").VerifyDiagnostics(); verifier.VerifyIL("A<T>.Equals(A<T>)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A<T>.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A<T>.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("B.Equals(A<int>)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A<int>.Equals(A<int>)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); } [Fact] public void Equality_20() { var source = @" record C; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__GetHashCode); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // record C; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C;").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1) ); } [Fact] public void Equality_21() { var source = @" record C; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // record C; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C;").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1) ); } [Fact] [WorkItem(44988, "https://github.com/dotnet/roslyn/issues/44988")] public void Equality_22() { var source = @" record C { int x = 0; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // record C Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record C { int x = 0; }").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // record C Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record C { int x = 0; }").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1), // (4,9): warning CS0414: The field 'C.x' is assigned but its value is never used // int x = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x").WithLocation(4, 9) ); } [Fact] public void IEquatableT_01() { var source = @"record A<T>; record B : A<int>; class Program { static void F<T>(System.IEquatable<T> t) { } static void M<T>() { F(new A<T>()); F(new B()); F<A<int>>(new B()); F<B>(new B()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,9): error CS0411: The type arguments for method 'Program.F<T>(IEquatable<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(new B()); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.IEquatable<T>)").WithLocation(11, 9)); } [Fact] public void IEquatableT_02() { var source = @"using System; record A; record B<T> : A; record C : B<int>; class Program { static string F<T>(IEquatable<T> t) { return typeof(T).Name; } static void Main() { Console.WriteLine(F(new A())); Console.WriteLine(F<A>(new C())); Console.WriteLine(F<B<int>>(new C())); Console.WriteLine(F<C>(new C())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A A B`1 C").VerifyDiagnostics(); } [Fact] public void IEquatableT_03() { var source = @"#nullable enable using System; record A<T> : IEquatable<A<T>> { } record B : A<object>, IEquatable<A<object>>, IEquatable<B?>; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B?>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B?>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_04() { var source = @"using System; record A<T> { internal static bool Report(string s) { Console.WriteLine(s); return false; } public virtual bool Equals(A<T> other) => Report(""A<T>.Equals(A<T>)""); } record B : A<object> { public virtual bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { var a = new A<object>(); var b = new B(); _ = a.Equals(b); _ = ((A<object>)b).Equals(b); _ = b.Equals(a); _ = b.Equals(b); _ = ((IEquatable<A<object>>)a).Equals(b); _ = ((IEquatable<A<object>>)b).Equals(b); _ = ((IEquatable<B>)b).Equals(b); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A<T>.Equals(A<T>) B.Equals(B) B.Equals(B) B.Equals(B) A<T>.Equals(A<T>) B.Equals(B) B.Equals(B)").VerifyDiagnostics( // (5,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A<T> other) => Report("A<T>.Equals(A<T>)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 25), // (9,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_05() { var source = @"using System; record A<T> : IEquatable<A<T>> { internal static bool Report(string s) { Console.WriteLine(s); return false; } public virtual bool Equals(A<T> other) => Report(""A<T>.Equals(A<T>)""); } record B : A<object>, IEquatable<A<object>>, IEquatable<B> { public virtual bool Equals(B other) => Report(""B.Equals(B)""); } record C : A<object>, IEquatable<A<object>>, IEquatable<C> { } class Program { static void Main() { var a = new A<object>(); var b = new B(); _ = a.Equals(b); _ = ((A<object>)b).Equals(b); _ = b.Equals(a); _ = b.Equals(b); _ = ((IEquatable<A<object>>)a).Equals(b); _ = ((IEquatable<A<object>>)b).Equals(b); _ = ((IEquatable<B>)b).Equals(b); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A<T>.Equals(A<T>) B.Equals(B) B.Equals(B) B.Equals(B) A<T>.Equals(A<T>) B.Equals(B) B.Equals(B)", symbolValidator: m => { var b = m.GlobalNamespace.GetTypeMember("B"); Assert.Equal("B.Equals(B)", b.FindImplementationForInterfaceMember(b.InterfacesNoUseSiteDiagnostics()[1].GetMember("Equals")).ToDisplayString()); var c = m.GlobalNamespace.GetTypeMember("C"); Assert.Equal("C.Equals(C?)", c.FindImplementationForInterfaceMember(c.InterfacesNoUseSiteDiagnostics()[1].GetMember("Equals")).ToDisplayString()); }).VerifyDiagnostics( // (5,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A<T> other) => Report("A<T>.Equals(A<T>)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 25), // (9,25): warning CS8851: '{B}' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_06() { var source = @"using System; record A<T> : IEquatable<A<T>> { internal static bool Report(string s) { Console.WriteLine(s); return false; } bool IEquatable<A<T>>.Equals(A<T> other) => Report(""A<T>.Equals(A<T>)""); } record B : A<object>, IEquatable<A<object>>, IEquatable<B> { bool IEquatable<A<object>>.Equals(A<object> other) => Report(""B.Equals(A<object>)""); bool IEquatable<B>.Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { var a = new A<object>(); var b = new B(); _ = a.Equals(b); _ = ((A<object>)b).Equals(b); _ = b.Equals(a); _ = b.Equals(b); _ = ((IEquatable<A<object>>)a).Equals(b); _ = ((IEquatable<A<object>>)b).Equals(b); _ = ((IEquatable<B>)b).Equals(b); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A<T>.Equals(A<T>) B.Equals(A<object>) B.Equals(B)").VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_07() { var source = @"using System; record A<T> : IEquatable<B1>, IEquatable<B2> { bool IEquatable<B1>.Equals(B1 other) => false; bool IEquatable<B2>.Equals(B2 other) => false; } record B1 : A<object>; record B2 : A<int>; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<B2>", "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<B2>", "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B1"); AssertEx.Equal(new[] { "System.IEquatable<B1>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<B2>", "System.IEquatable<A<System.Object>>", "System.IEquatable<B1>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B2"); AssertEx.Equal(new[] { "System.IEquatable<B2>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<A<System.Int32>>", "System.IEquatable<B2>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_08() { var source = @"interface I<T> { } record A<T> : I<A<T>> { } record B : A<object>, I<A<object>>, I<B> { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "I<A<T>>", "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "I<A<T>>", "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "I<A<System.Object>>", "I<B>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "I<A<System.Object>>", "I<B>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_09() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"record A<T>; record B : A<int>; "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record B : A<int>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(2, 8) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_10() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"record A<T> : System.IEquatable<A<T>>; record B : A<int>, System.IEquatable<B>; "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.ToString()': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,22): error CS0234: The type or namespace name 'IEquatable<>' does not exist in the namespace 'System' (are you missing an assembly reference?) // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IEquatable<A<T>>").WithArguments("IEquatable<>", "System").WithLocation(1, 22), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(2, 8), // (2,27): error CS0234: The type or namespace name 'IEquatable<>' does not exist in the namespace 'System' (are you missing an assembly reference?) // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IEquatable<B>").WithArguments("IEquatable<>", "System").WithLocation(2, 27)); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<B>", "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "System.IEquatable<B>", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_11() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"using System; record A<T> : IEquatable<A<T>>; record B : A<int>, IEquatable<B>; "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,1): hidden CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(1, 1), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.ToString()': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,15): error CS0246: The type or namespace name 'IEquatable<>' could not be found (are you missing a using directive or an assembly reference?) // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IEquatable<A<T>>").WithArguments("IEquatable<>").WithLocation(2, 15), // (3,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(3, 8), // (3,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(3, 8), // (3,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(3, 8), // (3,20): error CS0246: The type or namespace name 'IEquatable<>' could not be found (are you missing a using directive or an assembly reference?) // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IEquatable<B>").WithArguments("IEquatable<>").WithLocation(3, 20)); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "IEquatable<B>", "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "IEquatable<B>", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_12() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); void Other(); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"record A; class Program { static void Main() { System.IEquatable<A> a = new A(); _ = a.Equals(null); } }"; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8), // (1,8): error CS0535: 'A' does not implement interface member 'IEquatable<A>.Other()' // record A; Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("A", "System.IEquatable<A>.Other()").WithLocation(1, 8)); } [Fact] public void IEquatableT_13() { var source = @"record A { internal virtual bool Equals(A other) => false; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,8): error CS0737: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is not public. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(1, 8), // (3,27): error CS8873: Record member 'A.Equals(A)' must be public. // internal virtual bool Equals(A other) => false; Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(3, 27), // (3,27): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // internal virtual bool Equals(A other) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(3, 27) ); } [Fact] public void IEquatableT_14() { var source = @"record A { public bool Equals(A other) => false; } record B : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,17): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed. // public bool Equals(A other) => false; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(3, 17), // (3,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(3, 17), // (5,8): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // record B : A Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(5, 8)); } [WorkItem(45026, "https://github.com/dotnet/roslyn/issues/45026")] [Fact] public void IEquatableT_15() { var source = @"using System; record R { bool IEquatable<R>.Equals(R other) => false; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void IEquatableT_16() { var source = @"using System; class A<T> { record B<U> : IEquatable<B<T>> { bool IEquatable<B<T>>.Equals(B<T> other) => false; bool IEquatable<B<U>>.Equals(B<U> other) => false; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,12): error CS0695: 'A<T>.B<U>' cannot implement both 'IEquatable<A<T>.B<T>>' and 'IEquatable<A<T>.B<U>>' because they may unify for some type parameter substitutions // record B<U> : IEquatable<B<T>> Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "B").WithArguments("A<T>.B<U>", "System.IEquatable<A<T>.B<T>>", "System.IEquatable<A<T>.B<U>>").WithLocation(4, 12)); } [Fact] public void InterfaceImplementation() { var source = @" interface I { int P1 { get; init; } int P2 { get; init; } int P3 { get; set; } } record R(int P1) : I { public int P2 { get; init; } int I.P3 { get; set; } public static void Main() { I r = new R(42) { P2 = 43 }; r.P3 = 44; System.Console.Write((r.P1, r.P2, r.P3)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44)", verify: Verification.Skipped /* init-only */); } [Fact] public void Initializers_01() { var src = @" using System; record C(int X) { int Z = X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Single(); Assert.Equal("C", recordDeclaration.Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclaration)); } [Fact] public void Initializers_02() { var src = @" record C(int X) { static int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,20): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // static int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 20) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; init; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_03() { var src = @" record C(int X) { const int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // const int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 19) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; init; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_04() { var src = @" using System; record C(int X) { Func<int> Z = () => X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z()); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("() => X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("lambda expression", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_05() { var src = @" using System; record Base { public Base(Func<int> X) { Console.WriteLine(X()); } public Base() {} } record C(int X) : Base(() => 100 + X++) { Func<int> Y = () => 200 + X++; Func<int> Z = () => 300 + X++; public static void Main() { var c = new C(1); Console.WriteLine(c.Y()); Console.WriteLine(c.Z()); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 101 202 303 ").VerifyDiagnostics(); } [Fact] public void SynthesizedRecordPointerProperty() { var src = @" record R(int P1, int* P2, delegate*<int> P3);"; var comp = CreateCompilation(src); var p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P1"); Assert.False(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P2"); Assert.True(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P3"); Assert.True(p.HasPointerType); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_RefOrOut() { var src = @" record R(ref int P1, out int P2); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0177: The out parameter 'P2' must be assigned to before control leaves the current method // record R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_ParamUnassigned, "R").WithArguments("P2").WithLocation(2, 8), // (2,10): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(2, 10), // (2,22): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(2, 22) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_RefOrOut_WithBase() { var src = @" record Base(int I); record R(ref int P1, out int P2) : Base(P2 = 1); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,10): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2) : Base(P2 = 1); Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(3, 10), // (3,22): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2) : Base(P2 = 1); Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(3, 22) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_In() { var src = @" record R(in int P1); public class C { public static void Main() { var r = new R(42); int i = 43; var r2 = new R(in i); System.Console.Write((r.P1, r2.P1)); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43)", verify: Verification.Skipped /* init-only */); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(in System.Int32 P1)", "R..ctor(R original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_This() { var src = @" record R(this int i); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,10): error CS0027: Keyword 'this' is not available in the current context // record R(this int i); Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(2, 10) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_Params() { var src = @" record R(params int[] Array); public class C { public static void Main() { var r = new R(42, 43); var r2 = new R(new[] { 44, 45 }); System.Console.Write((r.Array[0], r.Array[1], r2.Array[0], r2.Array[1])); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44, 45)", verify: Verification.Skipped /* init-only */); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(params System.Int32[] Array)", "R..ctor(R original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue() { var src = @" record R(int P = 42) { public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue_AndPropertyWithInitializer() { var src = @" record R(int P = 1) { public int P { get; init; } = 42; public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record R(int P = 1) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14) ); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: stfld ""int R.<P>k__BackingField"" IL_0008: ldarg.0 IL_0009: call ""object..ctor()"" IL_000e: nop IL_000f: ret }"); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue_AndPropertyWithoutInitializer() { var src = @" record R(int P = 42) { public int P { get; init; } public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record R(int P = 42) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14) ); var verifier = CompileAndVerify(comp, expectedOutput: "0", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int)", @" { // Code size 8 (0x8) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: ret }"); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue_AndPropertyWithInitializer_CopyingParameter() { var src = @" record R(int P = 42) { public int P { get; init; } = P; public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<P>k__BackingField"" IL_0007: ldarg.0 IL_0008: call ""object..ctor()"" IL_000d: nop IL_000e: ret }"); } [Fact] public void AttributesOnPrimaryConstructorParameters_01() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public record Test( [field: A] [property: B] [param: C] [D] int P1) { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => a.AttributeClass!.Name is "A" or "B" or "C" or "D")); } } [Fact] public void AttributesOnPrimaryConstructorParameters_02() { string source = @" [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class D : System.Attribute { } public record Test( [field: A] [property: B] [param: C] [D] int P1) { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_03() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public abstract int P1 { get; init; } } public record Test( [field: A] [property: B] [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_04() { string source = @" [System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = true) ] public class A : System.Attribute { } public record Test( [method: A] int P1) { [method: A] void M1() {} } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new string[] { }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new string[] { }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new string[] { }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (8,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property, param'. All attributes in this block will be ignored. // [method: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field, property, param").WithLocation(8, 6) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_05() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public virtual int P1 { get; init; } } public record Test( [field: A] [property: B] [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); Assert.Null(@class.GetMember<PropertySymbol>("P1")); Assert.Null(@class.GetMember<FieldSymbol>("<P1>k__BackingField")); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (27,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param").WithLocation(27, 6), // (28,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. // [property: B] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param").WithLocation(28, 6), // (31,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // int P1) : Base Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(31, 9) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_06() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public int P1 { get; init; } } public record Test( [field: A] [property: B] [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); Assert.Null(@class.GetMember<PropertySymbol>("P1")); Assert.Null(@class.GetMember<FieldSymbol>("<P1>k__BackingField")); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (27,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param").WithLocation(27, 6), // (28,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. // [property: B] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param").WithLocation(28, 6), // (31,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // int P1) : Base Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(31, 9) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_07() { string source = @" [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public int P1 { get; init; } } public record Test( [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (20,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // int P1) : Base Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(20, 9) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_08() { string source = @" #nullable enable using System.Diagnostics.CodeAnalysis; record C<T>([property: NotNull] T? P1, T? P2) where T : class { protected C(C<T> other) { T x = P1; T y = P2; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition, NotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = P2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P2").WithLocation(10, 15) ); } [Fact] public void AttributesOnPrimaryConstructorParameters_09_CallerMemberName() { string source = @" using System.Runtime.CompilerServices; record R([CallerMemberName] string S = """"); class C { public static void Main() { var r = new R(); System.Console.Write(r.S); } } "; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, expectedOutput: "Main", parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe, verify: Verification.Skipped /* init-only */); comp.VerifyDiagnostics(); } [Fact] public void RecordWithConstraints_NullableWarning() { var src = @" #nullable enable record R<T>(T P) where T : class; record R2<T>(T P) where T : class { } public class C { public static void Main() { var r = new R<string?>(""R""); var r2 = new R2<string?>(""R2""); System.Console.Write((r.P, r2.P)); } }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (10,23): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r = new R<string?>("R"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R<T>", "T", "string?").WithLocation(10, 23), // (11,25): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R2<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r2 = new R2<string?>("R2"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R2<T>", "T", "string?").WithLocation(11, 25) ); CompileAndVerify(comp, expectedOutput: "(R, R2)", verify: Verification.Skipped /* init-only */); } [Fact] public void RecordWithConstraints_ConstraintError() { var src = @" record R<T>(T P) where T : class; record R2<T>(T P) where T : class { } public class C { public static void Main() { _ = new R<int>(1); _ = new R2<int>(2); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,19): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R<T>' // _ = new R<int>(1); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R<T>", "T", "int").WithLocation(9, 19), // (10,20): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R2<T>' // _ = new R2<int>(2); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R2<T>", "T", "int").WithLocation(10, 20) ); } [Fact] public void AccessCheckProtected03() { CSharpCompilation c = CreateCompilation(@" record X<T> { } record A { } record B { record C : X<C.D.E> { protected record D : A { public record E { } } } } ", targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, c.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (c.Assembly.RuntimeSupportsCovariantReturnsOfClasses) { c.VerifyDiagnostics( // (8,12): error CS0060: Inconsistent accessibility: base type 'X<B.C.D.E>' is less accessible than class 'B.C' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("B.C", "X<B.C.D.E>").WithLocation(8, 12), // (8,12): error CS0051: Inconsistent accessibility: parameter type 'X<B.C.D.E>' is less accessible than method 'B.C.Equals(X<B.C.D.E>?)' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisParamType, "C").WithArguments("B.C.Equals(X<B.C.D.E>?)", "X<B.C.D.E>").WithLocation(8, 12) ); } else { c.VerifyDiagnostics( // (8,12): error CS0060: Inconsistent accessibility: base type 'X<B.C.D.E>' is less accessible than class 'B.C' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("B.C", "X<B.C.D.E>").WithLocation(8, 12), // (8,12): error CS0050: Inconsistent accessibility: return type 'X<B.C.D.E>' is less accessible than method 'B.C.<Clone>$()' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisReturnType, "C").WithArguments("B.C.<Clone>$()", "X<B.C.D.E>").WithLocation(8, 12), // (8,12): error CS0051: Inconsistent accessibility: parameter type 'X<B.C.D.E>' is less accessible than method 'B.C.Equals(X<B.C.D.E>?)' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisParamType, "C").WithArguments("B.C.Equals(X<B.C.D.E>?)", "X<B.C.D.E>").WithLocation(8, 12) ); } } [Fact] public void TestTargetType_Abstract() { var source = @" abstract record C { void M() { C x0 = new(); var x1 = (C)new(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,16): error CS0144: Cannot create an instance of the abstract type or interface 'C' // C x0 = new(); Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(6, 16), // (7,21): error CS0144: Cannot create an instance of the abstract type or interface 'C' // var x1 = (C)new(); Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(7, 21) ); } [Fact] public void CyclicBases4() { var text = @" record A<T> : B<A<T>> { } record B<T> : A<B<T>> { A<T> F() { return null; } } "; var comp = CreateCompilation(text); comp.GetDeclarationDiagnostics().Verify( // (2,8): error CS0146: Circular base type dependency involving 'B<A<T>>' and 'A<T>' // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("B<A<T>>", "A<T>").WithLocation(2, 8), // (3,8): error CS0146: Circular base type dependency involving 'A<B<T>>' and 'B<T>' // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("A<B<T>>", "B<T>").WithLocation(3, 8), // (2,8): error CS0115: 'A<T>.ToString()': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (3,8): error CS0115: 'B<T>.EqualityContract': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.EqualityContract").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.Equals(object?)': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.Equals(object?)").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.GetHashCode()': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.GetHashCode()").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.PrintMembers(StringBuilder)': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.ToString()': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.ToString()").WithLocation(3, 8) ); } [Fact] public void CS0250ERR_CallingBaseFinalizeDeprecated() { var text = @" record B { } record C : B { ~C() { base.Finalize(); // CS0250 } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (10,7): error CS0250: Do not directly call your base type Finalize method. It is called automatically from your destructor. Diagnostic(ErrorCode.ERR_CallingBaseFinalizeDeprecated, "base.Finalize()") ); } [Fact] public void PartialClassWithDifferentTupleNamesInBaseTypes() { var source = @" public record Base<T> { } public partial record C1 : Base<(int a, int b)> { } public partial record C1 : Base<(int notA, int notB)> { } public partial record C2 : Base<(int a, int b)> { } public partial record C2 : Base<(int, int)> { } public partial record C3 : Base<(int a, int b)> { } public partial record C3 : Base<(int a, int b)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,23): error CS0263: Partial declarations of 'C2' must not specify different base classes // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C2").WithArguments("C2").WithLocation(5, 23), // (3,23): error CS0263: Partial declarations of 'C1' must not specify different base classes // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C1").WithArguments("C1").WithLocation(3, 23), // (5,23): error CS0115: 'C2.ToString()': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.ToString()").WithLocation(5, 23), // (5,23): error CS0115: 'C2.EqualityContract': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.EqualityContract").WithLocation(5, 23), // (5,23): error CS0115: 'C2.Equals(object?)': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.Equals(object?)").WithLocation(5, 23), // (5,23): error CS0115: 'C2.GetHashCode()': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.GetHashCode()").WithLocation(5, 23), // (5,23): error CS0115: 'C2.PrintMembers(StringBuilder)': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 23), // (3,23): error CS0115: 'C1.ToString()': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.ToString()").WithLocation(3, 23), // (3,23): error CS0115: 'C1.EqualityContract': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.EqualityContract").WithLocation(3, 23), // (3,23): error CS0115: 'C1.Equals(object?)': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.Equals(object?)").WithLocation(3, 23), // (3,23): error CS0115: 'C1.GetHashCode()': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.GetHashCode()").WithLocation(3, 23), // (3,23): error CS0115: 'C1.PrintMembers(StringBuilder)': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 23) ); } [Fact] public void CS0267ERR_PartialMisplaced() { var test = @" partial public record C // CS0267 { } "; CreateCompilation(test).VerifyDiagnostics( // (2,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial public class C // CS0267 Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1)); } [Fact] public void AttributeContainsGeneric() { string source = @" [Goo<int>] class G { } record Goo<T> { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2) ); } [Fact] public void CS0406ERR_ClassBoundNotFirst() { var source = @"interface I { } record A { } record B { } class C<T, U> where T : I, A where U : A, B { void M<V>() where V : U, A, B { } }"; CreateCompilation(source).VerifyDiagnostics( // (5,18): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(5, 18), // (6,18): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(6, 18), // (8,30): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(8, 30), // (8,33): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(8, 33)); } [Fact] public void SealedStaticRecord() { var source = @" sealed static record R; "; CreateCompilation(source).VerifyDiagnostics( // (2,22): error CS0106: The modifier 'static' is not valid for this item // sealed static record R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 22) ); } [Fact] public void CS0513ERR_AbstractInConcreteClass02() { var text = @" record C { public abstract event System.Action E; public abstract int this[int x] { get; set; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,41): error CS0513: 'C.E' is abstract but it is contained in non-abstract type 'C' // public abstract event System.Action E; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("C.E", "C"), // (5,39): error CS0513: 'C.this[int].get' is abstract but it is contained in non-abstract type 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("C.this[int].get", "C"), // (5,44): error CS0513: 'C.this[int].set' is abstract but it is contained in non-abstract type 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("C.this[int].set", "C")); } [Fact] public void ConversionToBase() { var source = @" public record Base<T> { } public record Derived : Base<(int a, int b)> { public static explicit operator Base<(int, int)>(Derived x) { return null; } public static explicit operator Derived(Base<(int, int)> x) { return null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,37): error CS0553: 'Derived.explicit operator Derived(Base<(int, int)>)': user-defined conversions to or from a base type are not allowed // public static explicit operator Derived(Base<(int, int)> x) Diagnostic(ErrorCode.ERR_ConversionWithBase, "Derived").WithArguments("Derived.explicit operator Derived(Base<(int, int)>)").WithLocation(9, 37), // (5,37): error CS0553: 'Derived.explicit operator Base<(int, int)>(Derived)': user-defined conversions to or from a base type are not allowed // public static explicit operator Base<(int, int)>(Derived x) Diagnostic(ErrorCode.ERR_ConversionWithBase, "Base<(int, int)>").WithArguments("Derived.explicit operator Base<(int, int)>(Derived)").WithLocation(5, 37) ); } [Fact] public void CS0554ERR_ConversionWithDerived() { var text = @" public record B { public static implicit operator B(D d) // CS0554 { return null; } } public record D : B {} "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,37): error CS0554: 'B.implicit operator B(D)': user-defined conversions to or from a derived type are not allowed // public static implicit operator B(D d) // CS0554 Diagnostic(ErrorCode.ERR_ConversionWithDerived, "B").WithArguments("B.implicit operator B(D)") ); } [Fact] public void CS0574ERR_BadDestructorName() { var test = @" namespace x { public record iii { ~iiii(){} public static void Main() { } } } "; CreateCompilation(test).VerifyDiagnostics( // (6,10): error CS0574: Name of destructor must match name of type // ~iiii(){} Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(6, 10)); } [Fact] public void StaticBasePartial() { var text = @" static record NV { } public partial record C1 { } partial record C1 : NV { } public partial record C1 { } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses) { comp.VerifyDiagnostics( // (2,15): error CS0106: The modifier 'static' is not valid for this item // static record NV Diagnostic(ErrorCode.ERR_BadMemberFlag, "NV").WithArguments("static").WithLocation(2, 15), // (6,23): error CS0051: Inconsistent accessibility: parameter type 'NV' is less accessible than method 'C1.Equals(NV?)' // public partial record C1 Diagnostic(ErrorCode.ERR_BadVisParamType, "C1").WithArguments("C1.Equals(NV?)", "NV").WithLocation(6, 23), // (10,16): error CS0060: Inconsistent accessibility: base class 'NV' is less accessible than class 'C1' // partial record C1 : NV Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 16) ); } else { comp.VerifyDiagnostics( // (2,15): error CS0106: The modifier 'static' is not valid for this item // static record NV Diagnostic(ErrorCode.ERR_BadMemberFlag, "NV").WithArguments("static").WithLocation(2, 15), // (6,23): error CS0050: Inconsistent accessibility: return type 'NV' is less accessible than method 'C1.<Clone>$()' // public partial record C1 Diagnostic(ErrorCode.ERR_BadVisReturnType, "C1").WithArguments("C1.<Clone>$()", "NV").WithLocation(6, 23), // (6,23): error CS0051: Inconsistent accessibility: parameter type 'NV' is less accessible than method 'C1.Equals(NV?)' // public partial record C1 Diagnostic(ErrorCode.ERR_BadVisParamType, "C1").WithArguments("C1.Equals(NV?)", "NV").WithLocation(6, 23), // (10,16): error CS0060: Inconsistent accessibility: base class 'NV' is less accessible than class 'C1' // partial record C1 : NV Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 16) ); } } [Fact] public void StaticRecordWithConstructorAndDestructor() { var text = @" static record R(int I) { R() : this(0) { } ~R() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,15): error CS0106: The modifier 'static' is not valid for this item // static record R(int I) Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 15) ); } [Fact] public void RecordWithPartialMethodExplicitImplementation() { var source = @"record R { partial void M(); }"; CreateCompilation(source).VerifyDiagnostics( // (3,18): error CS0751: A partial method must be declared within a partial type // partial void M(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 18) ); } [Fact] public void RecordWithMultipleBaseTypes() { var source = @" record Base1; record Base2; record R : Base1, Base2 { }"; CreateCompilation(source).VerifyDiagnostics( // (4,19): error CS1721: Class 'R' cannot have multiple base classes: 'Base1' and 'Base2' // record R : Base1, Base2 Diagnostic(ErrorCode.ERR_NoMultipleInheritance, "Base2").WithArguments("R", "Base1", "Base2").WithLocation(4, 19) ); } [Fact] public void RecordWithInterfaceBeforeBase() { var source = @" record Base; interface I { } record R : I, Base; "; CreateCompilation(source).VerifyDiagnostics( // (4,15): error CS1722: Base class 'Base' must come before any interfaces // record R : I, Base; Diagnostic(ErrorCode.ERR_BaseClassMustBeFirst, "Base").WithArguments("Base").WithLocation(4, 15) ); } [Fact] public void RecordLoadedInVisualBasicDisplaysAsClass() { var src = @" public record A; "; var compRef = CreateCompilation(src).EmitToImageReference(); var vbComp = CreateVisualBasicCompilation("", referencedAssemblies: new[] { compRef }); var symbol = vbComp.GlobalNamespace.GetTypeMember("A"); Assert.False(symbol.IsRecord); Assert.Equal("class A", SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void AnalyzerActions_01() { var text1 = @" record A([Attr1]int X = 0) : I1 {} record B([Attr2]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3]int Z = 4) : base(5) {} } interface I1 {} class Attr1 : System.Attribute {} class Attr2 : System.Attribute {} class Attr3 : System.Attribute {} "; var analyzer = new AnalyzerActions_01_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount13); Assert.Equal(1, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(1, analyzer.FireCount17); Assert.Equal(1, analyzer.FireCount18); Assert.Equal(1, analyzer.FireCount19); Assert.Equal(1, analyzer.FireCount20); Assert.Equal(1, analyzer.FireCount21); Assert.Equal(1, analyzer.FireCount22); Assert.Equal(1, analyzer.FireCount23); Assert.Equal(1, analyzer.FireCount24); Assert.Equal(1, analyzer.FireCount25); Assert.Equal(1, analyzer.FireCount26); Assert.Equal(1, analyzer.FireCount27); Assert.Equal(1, analyzer.FireCount28); Assert.Equal(1, analyzer.FireCount29); Assert.Equal(1, analyzer.FireCount30); Assert.Equal(1, analyzer.FireCount31); } private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer { public int FireCount0; public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; public int FireCount13; public int FireCount14; public int FireCount15; public int FireCount16; public int FireCount17; public int FireCount18; public int FireCount19; public int FireCount20; public int FireCount21; public int FireCount22; public int FireCount23; public int FireCount24; public int FireCount25; public int FireCount26; public int FireCount27; public int FireCount28; public int FireCount29; public int FireCount30; public int FireCount31; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Handle5, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); } protected void Handle1(SyntaxNodeAnalysisContext context) { var literal = (LiteralExpressionSyntax)context.Node; switch (literal.ToString()) { case "0": Interlocked.Increment(ref FireCount0); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "1": Interlocked.Increment(ref FireCount1); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "2": Interlocked.Increment(ref FireCount2); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "3": Interlocked.Increment(ref FireCount3); Assert.Equal("System.Int32 B.M()", context.ContainingSymbol.ToTestDisplayString()); break; case "4": Interlocked.Increment(ref FireCount4); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; case "5": Interlocked.Increment(ref FireCount5); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(literal.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle2(SyntaxNodeAnalysisContext context) { var equalsValue = (EqualsValueClauseSyntax)context.Node; switch (equalsValue.ToString()) { case "= 0": Interlocked.Increment(ref FireCount15); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "= 1": Interlocked.Increment(ref FireCount16); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "= 4": Interlocked.Increment(ref FireCount6); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(equalsValue.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle3(SyntaxNodeAnalysisContext context) { var initializer = (ConstructorInitializerSyntax)context.Node; switch (initializer.ToString()) { case ": base(5)": Interlocked.Increment(ref FireCount7); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(initializer.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle4(SyntaxNodeAnalysisContext context) { Interlocked.Increment(ref FireCount8); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); } protected void Handle5(SyntaxNodeAnalysisContext context) { var baseType = (PrimaryConstructorBaseTypeSyntax)context.Node; switch (baseType.ToString()) { case "A(2)": switch (context.ContainingSymbol.ToTestDisplayString()) { case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount9); break; case "B": Interlocked.Increment(ref FireCount17); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } Assert.Same(baseType.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle6(SyntaxNodeAnalysisContext context) { var record = (RecordDeclarationSyntax)context.Node; switch (context.ContainingSymbol.ToTestDisplayString()) { case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount10); break; case "B": Interlocked.Increment(ref FireCount11); break; case "A": Interlocked.Increment(ref FireCount12); break; case "C": Interlocked.Increment(ref FireCount13); break; case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount14); break; default: Assert.True(false); break; } Assert.Same(record.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle7(SyntaxNodeAnalysisContext context) { var identifier = (IdentifierNameSyntax)context.Node; switch (identifier.Identifier.ValueText) { case "A": switch (identifier.Parent!.ToString()) { case "A(2)": Interlocked.Increment(ref FireCount18); Assert.Equal("B", context.ContainingSymbol.ToTestDisplayString()); break; case "A": Interlocked.Increment(ref FireCount19); Assert.Equal(SyntaxKind.SimpleBaseType, identifier.Parent.Kind()); Assert.Equal("C", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } break; case "Attr1": Interlocked.Increment(ref FireCount24); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "Attr2": Interlocked.Increment(ref FireCount25); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "Attr3": Interlocked.Increment(ref FireCount26); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; } } protected void Handle8(SyntaxNodeAnalysisContext context) { var baseType = (SimpleBaseTypeSyntax)context.Node; switch (baseType.ToString()) { case "I1": switch (context.ContainingSymbol.ToTestDisplayString()) { case "A": Interlocked.Increment(ref FireCount20); break; case "B": Interlocked.Increment(ref FireCount21); break; case "C": Interlocked.Increment(ref FireCount22); break; default: Assert.True(false); break; } break; case "A": switch (context.ContainingSymbol.ToTestDisplayString()) { case "C": Interlocked.Increment(ref FireCount23); break; default: Assert.True(false); break; } break; case "System.Attribute": break; default: Assert.True(false); break; } } protected void Handle9(SyntaxNodeAnalysisContext context) { var parameterList = (ParameterListSyntax)context.Node; switch (parameterList.ToString()) { case "([Attr1]int X = 0)": Interlocked.Increment(ref FireCount27); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "([Attr2]int Y = 1)": Interlocked.Increment(ref FireCount28); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "([Attr3]int Z = 4)": Interlocked.Increment(ref FireCount29); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; case "()": break; default: Assert.True(false); break; } } protected void Handle10(SyntaxNodeAnalysisContext context) { var argumentList = (ArgumentListSyntax)context.Node; switch (argumentList.ToString()) { case "(2)": Interlocked.Increment(ref FireCount30); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "(5)": Interlocked.Increment(ref FireCount31); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_02() { var text1 = @" record A(int X = 0) {} record C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_02_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); } private class AnalyzerActions_02_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.Method); context.RegisterSymbolAction(Handle, SymbolKind.Property); context.RegisterSymbolAction(Handle, SymbolKind.Parameter); context.RegisterSymbolAction(Handle, SymbolKind.NamedType); } private void Handle(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount2); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount6); break; case "C": Interlocked.Increment(ref FireCount7); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_03() { var text1 = @" record A(int X = 0) {} record C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_03_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(0, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(0, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); } private class AnalyzerActions_03_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolStartAction(Handle1, SymbolKind.Method); context.RegisterSymbolStartAction(Handle1, SymbolKind.Property); context.RegisterSymbolStartAction(Handle1, SymbolKind.Parameter); context.RegisterSymbolStartAction(Handle1, SymbolKind.NamedType); } private void Handle1(SymbolStartAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); context.RegisterSymbolEndAction(Handle2); break; case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount2); context.RegisterSymbolEndAction(Handle3); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); context.RegisterSymbolEndAction(Handle4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount9); Assert.Equal(0, FireCount1); Assert.Equal(0, FireCount2); Assert.Equal(0, FireCount6); Assert.Equal(0, FireCount7); context.RegisterSymbolEndAction(Handle5); break; case "C": Interlocked.Increment(ref FireCount10); Assert.Equal(0, FireCount4); Assert.Equal(0, FireCount8); context.RegisterSymbolEndAction(Handle6); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { Assert.Equal("A..ctor([System.Int32 X = 0])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); } private void Handle3(SymbolAnalysisContext context) { Assert.Equal("System.Int32 A.X { get; init; }", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); } private void Handle4(SymbolAnalysisContext context) { Assert.Equal("C..ctor([System.Int32 Z = 4])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); } private void Handle5(SymbolAnalysisContext context) { Assert.Equal("A", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount11); Assert.Equal(1, FireCount1); Assert.Equal(1, FireCount2); Assert.Equal(1, FireCount6); Assert.Equal(1, FireCount7); } private void Handle6(SymbolAnalysisContext context) { Assert.Equal("C", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount12); Assert.Equal(1, FireCount4); Assert.Equal(1, FireCount8); } } [Fact] public void AnalyzerActions_04() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_04_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(0, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount13); Assert.Equal(1, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(1, analyzer.FireCount17); } private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; public int FireCount13; public int FireCount14; public int FireCount15; public int FireCount16; public int FireCount17; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationAction(Handle1, OperationKind.ConstructorBody); context.RegisterOperationAction(Handle2, OperationKind.Invocation); context.RegisterOperationAction(Handle3, OperationKind.Literal); context.RegisterOperationAction(Handle4, OperationKind.ParameterInitializer); context.RegisterOperationAction(Handle5, OperationKind.PropertyInitializer); context.RegisterOperationAction(Handle5, OperationKind.FieldInitializer); } protected void Handle1(OperationAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind()); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind()); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); Assert.Equal(SyntaxKind.ConstructorDeclaration, context.Operation.Syntax.Kind()); break; default: Assert.True(false); break; } } protected void Handle2(OperationAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount4); Assert.Equal(SyntaxKind.PrimaryConstructorBaseType, context.Operation.Syntax.Kind()); VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation, @" IInvocationOperation ( A..ctor([System.Int32 X = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'A(2)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'A(2)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') 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) "); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount5); Assert.Equal(SyntaxKind.BaseConstructorInitializer, context.Operation.Syntax.Kind()); VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation, @" IInvocationOperation ( A..ctor([System.Int32 X = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base(5)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: ': base(5)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '5') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') 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) "); break; default: Assert.True(false); break; } } protected void Handle3(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "100": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); break; case "0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); break; case "200": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); break; case "1": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount9); break; case "2": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount10); break; case "300": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount11); break; case "4": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount12); break; case "5": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount13); break; case "3": Assert.Equal("System.Int32 B.M()", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount17); break; default: Assert.True(false); break; } } protected void Handle4(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "= 0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount14); break; case "= 1": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount15); break; case "= 4": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount16); break; default: Assert.True(false); break; } } protected void Handle5(OperationAnalysisContext context) { Assert.True(false); } } [Fact] public void AnalyzerActions_05() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_05_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockAction(Handle); } private void Handle(OperationBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); Assert.Equal(3, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind); Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString()); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); Assert.Equal(4, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind); Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString()); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4); Assert.Equal(1, context.OperationBlocks.Length); Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_06() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_06_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount100); Assert.Equal(1, analyzer.FireCount200); Assert.Equal(1, analyzer.FireCount300); Assert.Equal(1, analyzer.FireCount400); Assert.Equal(0, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount13); Assert.Equal(1, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(1, analyzer.FireCount17); Assert.Equal(1, analyzer.FireCount1000); Assert.Equal(1, analyzer.FireCount2000); Assert.Equal(1, analyzer.FireCount3000); Assert.Equal(1, analyzer.FireCount4000); } private class AnalyzerActions_06_Analyzer : AnalyzerActions_04_Analyzer { public int FireCount100; public int FireCount200; public int FireCount300; public int FireCount400; public int FireCount1000; public int FireCount2000; public int FireCount3000; public int FireCount4000; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle); } private void Handle(OperationBlockStartAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount100); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount200); Assert.Equal(3, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind); Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString()); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount300); Assert.Equal(4, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind); Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString()); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount400); Assert.Equal(1, context.OperationBlocks.Length); Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; default: Assert.True(false); break; } } private void RegisterOperationAction(OperationBlockStartAnalysisContext context) { context.RegisterOperationAction(Handle1, OperationKind.ConstructorBody); context.RegisterOperationAction(Handle2, OperationKind.Invocation); context.RegisterOperationAction(Handle3, OperationKind.Literal); context.RegisterOperationAction(Handle4, OperationKind.ParameterInitializer); context.RegisterOperationAction(Handle5, OperationKind.PropertyInitializer); context.RegisterOperationAction(Handle5, OperationKind.FieldInitializer); } private void Handle6(OperationBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1000); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2000); Assert.Equal(3, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind); Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString()); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3000); Assert.Equal(4, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind); Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString()); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4000); Assert.Equal(1, context.OperationBlocks.Length); Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_07() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_07_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(Handle); } private void Handle(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1); break; default: Assert.True(false); break; } break; case "B..ctor([System.Int32 Y = 1])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }: Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } break; case "C..ctor([System.Int32 Z = 4])": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }: Interlocked.Increment(ref FireCount3); break; default: Assert.True(false); break; } break; case "System.Int32 B.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_08() { var text1 = @" record A([Attr1]int X = 0) : I1 {} record B([Attr2]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_08_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount100); Assert.Equal(1, analyzer.FireCount200); Assert.Equal(1, analyzer.FireCount300); Assert.Equal(1, analyzer.FireCount400); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(0, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(0, analyzer.FireCount10); Assert.Equal(0, analyzer.FireCount11); Assert.Equal(0, analyzer.FireCount12); Assert.Equal(0, analyzer.FireCount13); Assert.Equal(0, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(0, analyzer.FireCount17); Assert.Equal(0, analyzer.FireCount18); Assert.Equal(0, analyzer.FireCount19); Assert.Equal(0, analyzer.FireCount20); Assert.Equal(0, analyzer.FireCount21); Assert.Equal(0, analyzer.FireCount22); Assert.Equal(0, analyzer.FireCount23); Assert.Equal(1, analyzer.FireCount24); Assert.Equal(1, analyzer.FireCount25); Assert.Equal(1, analyzer.FireCount26); Assert.Equal(0, analyzer.FireCount27); Assert.Equal(0, analyzer.FireCount28); Assert.Equal(0, analyzer.FireCount29); Assert.Equal(1, analyzer.FireCount30); Assert.Equal(1, analyzer.FireCount31); Assert.Equal(1, analyzer.FireCount1000); Assert.Equal(1, analyzer.FireCount2000); Assert.Equal(1, analyzer.FireCount3000); Assert.Equal(1, analyzer.FireCount4000); } private class AnalyzerActions_08_Analyzer : AnalyzerActions_01_Analyzer { public int FireCount100; public int FireCount200; public int FireCount300; public int FireCount400; public int FireCount1000; public int FireCount2000; public int FireCount3000; public int FireCount4000; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(Handle); } private void Handle(CodeBlockStartAnalysisContext<SyntaxKind> context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount100); break; default: Assert.True(false); break; } break; case "B..ctor([System.Int32 Y = 1])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }: Interlocked.Increment(ref FireCount200); break; default: Assert.True(false); break; } break; case "C..ctor([System.Int32 Z = 4])": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }: Interlocked.Increment(ref FireCount300); break; default: Assert.True(false); break; } break; case "System.Int32 B.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount400); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Handle5, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); context.RegisterCodeBlockEndAction(Handle11); } private void Handle11(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1000); break; default: Assert.True(false); break; } break; case "B..ctor([System.Int32 Y = 1])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }: Interlocked.Increment(ref FireCount2000); break; default: Assert.True(false); break; } break; case "C..ctor([System.Int32 Z = 4])": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }: Interlocked.Increment(ref FireCount3000); break; default: Assert.True(false); break; } break; case "System.Int32 B.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4000); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_09() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_09_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); } private class AnalyzerActions_09_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle1, SymbolKind.Method); context.RegisterSymbolAction(Handle2, SymbolKind.Property); context.RegisterSymbolAction(Handle3, SymbolKind.Parameter); } private void Handle1(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount5); break; case "System.Int32 B.Y { get; init; }": Interlocked.Increment(ref FireCount6); break; default: Assert.True(false); break; } } private void Handle3(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount7); break; case "[System.Int32 Y = 1]": Interlocked.Increment(ref FireCount8); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount9); break; default: Assert.True(false); break; } } } [Fact] [WorkItem(46657, "https://github.com/dotnet/roslyn/issues/46657")] public void CanDeclareIteratorInRecord() { var source = @" using System.Collections.Generic; public record X(int a) { public static void Main() { foreach(var i in new X(42).GetItems()) { System.Console.Write(i); } } public IEnumerable<int> GetItems() { yield return a; yield return a + 1; } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9) .VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "4243", verify: Verification.Skipped /* init-only */); } [Fact] public void DefaultCtor_01() { var src = @" record C { } class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); } [Fact] public void DefaultCtor_02() { var src = @" record B(int x); record C : B { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,8): error CS1729: 'B' does not contain a constructor that takes 0 arguments // record C : B Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(4, 8) ); } [Fact] public void DefaultCtor_03() { var src = @" record C { public C(C c){} } class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); } [Fact] public void DefaultCtor_04() { var src = @" record B(int x); record C : B { public C(C c) : base(c) {} } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,8): error CS1729: 'B' does not contain a constructor that takes 0 arguments // record C : B Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(4, 8) ); } [Fact] public void DefaultCtor_05() { var src = @" record C(int x); class Program { static void Main() { _ = new C(); } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (8,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'C.C(int)' // _ = new C(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("x", "C.C(int)").WithLocation(8, 17) ); } [Fact] public void DefaultCtor_06() { var src = @" record C { C(int x) {} } class Program { static void Main() { _ = new C(); } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (11,17): error CS1729: 'C' does not contain a constructor that takes 0 arguments // _ = new C(); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("C", "0").WithLocation(11, 17) ); } [Fact] public void DefaultCtor_07() { var src = @" class C { C(C x) {} } class Program { static void Main() { _ = new C(); } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (11,17): error CS1729: 'C' does not contain a constructor that takes 0 arguments // _ = new C(); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("C", "0").WithLocation(11, 17) ); } [Fact] [WorkItem(47867, "https://github.com/dotnet/roslyn/issues/47867")] public void ToString_RecordWithStaticMembers() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); record C1(int I1) { public static int field1 = 44; public const int field2 = 44; public static int P1 { set { } } public static int P2 { get { return 1; } set { } } public static int P3 { get { return 1; } } } "; var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.ReleaseExe); CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compDebug.VerifyEmitDiagnostics(); CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compRelease.VerifyEmitDiagnostics(); } [Fact] [WorkItem(47867, "https://github.com/dotnet/roslyn/issues/47867")] public void ToString_NestedRecord() { var src = @" var c1 = new Outer.C1(42); System.Console.Write(c1.ToString()); public class Outer { public record C1(int I1); } "; var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.ReleaseExe); CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compDebug.VerifyEmitDiagnostics(); CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compRelease.VerifyEmitDiagnostics(); } [Fact] public void ToString_Cycle_01() { var src = @" using System; var rec = new Rec(); rec.Inner = rec; try { rec.ToString(); } catch (Exception ex) { Console.Write(ex.GetType().FullName); } public record Rec { public Rec Inner; } "; CompileAndVerify(src, expectedOutput: "System.InsufficientExecutionStackException"); } [Fact] public void ToString_Cycle_02() { var src = @" using System; var rec = new Rec(); rec.Inner = rec; try { rec.ToString(); } catch (Exception ex) { Console.Write(ex.GetType().FullName); } public record Base { public Rec Inner; } public record Rec : Base { } "; CompileAndVerify(src, expectedOutput: "System.InsufficientExecutionStackException"); } [Fact] public void ToString_Cycle_03() { var src = @" using System; var rec = new Rec(); rec.RecStruct.Rec = rec; try { rec.ToString(); } catch (Exception ex) { Console.Write(ex.GetType().FullName); } public record Rec { public RecStruct RecStruct; } public record struct RecStruct { public Rec Rec; } "; CompileAndVerify(src, expectedOutput: "System.InsufficientExecutionStackException"); } [Fact] public void ToString_Cycle_04() { var src = @" public record Rec { public RecStruct RecStruct; } public record struct RecStruct { public Rec Rec; } "; var comp = CreateCompilation(src); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("Rec.PrintMembers", @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""RecStruct = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldflda ""RecStruct Rec.RecStruct"" IL_0018: constrained. ""RecStruct"" IL_001e: callvirt ""string object.ToString()"" IL_0023: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0028: pop IL_0029: ldc.i4.1 IL_002a: ret }"); comp.MakeMemberMissing(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__EnsureSufficientExecutionStack); verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("Rec.PrintMembers", @" { // Code size 38 (0x26) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""RecStruct = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldflda ""RecStruct Rec.RecStruct"" IL_0013: constrained. ""RecStruct"" IL_0019: callvirt ""string object.ToString()"" IL_001e: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0023: pop IL_0024: ldc.i4.1 IL_0025: ret }"); } [Fact] [WorkItem(50040, "https://github.com/dotnet/roslyn/issues/50040")] public void RaceConditionInAddMembers() { var src = @" #nullable enable using System; using System.Linq.Expressions; using System.Threading.Tasks; var collection = new Collection<Hamster>(); Hamster h = null!; await collection.MethodAsync(entity => entity.Name! == ""bar"", h); public record Collection<T> where T : Document { public Task MethodAsync<TDerived>(Expression<Func<TDerived, bool>> filter, TDerived td) where TDerived : T => throw new NotImplementedException(); public Task MethodAsync<TDerived2>(Task<TDerived2> filterDefinition, TDerived2 td) where TDerived2 : T => throw new NotImplementedException(); } public sealed record HamsterCollection : Collection<Hamster> { } public abstract class Document { } public sealed class Hamster : Document { public string? Name { get; private set; } } "; for (int i = 0; i < 100; i++) { var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); } } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact] public void XmlDoc_RecordClass() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record class C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Cref() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for <see cref=""I1""/></param> public record C(int I1) { /// <summary>Summary</summary> /// <param name=""x"">Description for <see cref=""x""/></param> public void M(int x) { } } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,52): warning CS1574: XML comment has cref attribute 'x' that could not be resolved // /// <param name="x">Description for <see cref="x"/></param> Diagnostic(ErrorCode.WRN_BadXMLRef, "x").WithArguments("x").WithLocation(7, 52) ); var tree = comp.SyntaxTrees.Single(); var docComments = tree.GetCompilationUnitRoot().DescendantTrivia().Select(trivia => trivia.GetStructure()).OfType<DocumentationCommentTriviaSyntax>(); var cref = docComments.First().DescendantNodes().OfType<XmlCrefAttributeSyntax>().First().Cref; Assert.Equal("I1", cref.ToString()); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal(SymbolKind.Property, model.GetSymbolInfo(cref).Symbol!.Kind); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Error() { var src = @" /// <summary>Summary</summary> /// <param name=""Error""></param> /// <param name=""I1""></param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (3,18): warning CS1572: XML comment has a param tag for 'Error', but there is no parameter by that name // /// <param name="Error"></param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Error").WithArguments("Error").WithLocation(3, 18), // (3,18): warning CS1572: XML comment has a param tag for 'Error', but there is no parameter by that name // /// <param name="Error"></param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Error").WithArguments("Error").WithLocation(3, 18) ); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Duplicate() { var src = @" /// <summary>Summary</summary> /// <param name=""I1""></param> /// <param name=""I1""></param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (4,12): warning CS1571: XML comment has a duplicate param tag for 'I1' // /// <param name="I1"></param> Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""I1""").WithArguments("I1").WithLocation(4, 12), // (4,12): warning CS1571: XML comment has a duplicate param tag for 'I1' // /// <param name="I1"></param> Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""I1""").WithArguments("I1").WithLocation(4, 12) ); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_ParamRef() { var src = @" /// <summary>Summary <paramref name=""I1""/></summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary <paramref name=""I1""/></summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_ParamRef_Error() { var src = @" /// <summary>Summary <paramref name=""Error""/></summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,38): warning CS1734: XML comment on 'C' has a paramref tag for 'Error', but there is no parameter by that name // /// <summary>Summary <paramref name="Error"/></summary> Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "Error").WithArguments("Error", "C").WithLocation(2, 38), // (2,38): warning CS1734: XML comment on 'C.C(int)' has a paramref tag for 'Error', but there is no parameter by that name // /// <summary>Summary <paramref name="Error"/></summary> Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "Error").WithArguments("Error", "C.C(int)").WithLocation(2, 38) ); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_WithExplicitProperty() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record C(int I1) { /// <summary>Property summary</summary> public int I1 { get; init; } = I1; } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal( @"<member name=""P:C.I1""> <summary>Property summary</summary> </member> ", property.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_EmptyParameterList() { var src = @" /// <summary>Summary</summary> public record C(); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.IsEmpty).Single(); Assert.Equal( @"<member name=""M:C.#ctor""> <summary>Summary</summary> </member> ", constructor.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListSecond() { var src = @" public partial record C; /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var c = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", c.GetDocumentationCommentXml()); var cConstructor = c.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cConstructor.GetDocumentationCommentXml()); Assert.Equal("", cConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", c.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListFirst() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record D(int I1); public partial record D; namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var d = comp.GetMember<NamedTypeSymbol>("D"); Assert.Equal( @"<member name=""T:D""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", d.GetDocumentationCommentXml()); var dConstructor = d.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:D.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", dConstructor.GetDocumentationCommentXml()); Assert.Equal("", dConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", d.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListFirst_XmlDocSecond() { var src = @" public partial record E(int I1); /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record E; namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)' // public partial record E(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(2, 23), // (5,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(5, 18) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal("", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListSecond_XmlDocFirst() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record E; public partial record E(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (3,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(3, 18), // (6,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)' // public partial record E(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(6, 23) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal("", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DuplicateParameterList_XmlDocSecond() { var src = @" public partial record C(int I1); /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'C.C(int)' // public partial record C(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "C").WithArguments("C.C(int)").WithLocation(2, 23), // (5,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(5, 18), // (6,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record C(int I1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(6, 24) ); var c = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", c.GetDocumentationCommentXml()); var cConstructor = c.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, cConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal("", cConstructor.GetDocumentationCommentXml()); Assert.Equal("", cConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", c.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DuplicateParameterList_XmlDocFirst() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record D(int I1); public partial record D(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (6,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record D(int I1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(6, 24) ); var d = comp.GetMember<NamedTypeSymbol>("D"); Assert.Equal( @"<member name=""T:D""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", d.GetDocumentationCommentXml()); var dConstructor = d.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:D.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", dConstructor.GetDocumentationCommentXml()); Assert.Equal("", dConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", d.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DuplicateParameterList_XmlDocOnBoth() { var src = @" /// <summary>Summary1</summary> /// <param name=""I1"">Description1 for I1</param> public partial record E(int I1); /// <summary>Summary2</summary> /// <param name=""I1"">Description2 for I1</param> public partial record E(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description2 for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(7, 18), // (8,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record E(int I1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(8, 24) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> <summary>Summary2</summary> <param name=""I1"">Description2 for I1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal( @"<member name=""M:E.#ctor(System.Int32)""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> </member> ", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DifferentParameterLists_XmlDocSecond() { var src = @" public partial record E(int I1); /// <summary>Summary2</summary> /// <param name=""S1"">Description2 for S1</param> public partial record E(string S1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)' // public partial record E(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(2, 23), // (5,18): warning CS1572: XML comment has a param tag for 'S1', but there is no parameter by that name // /// <param name="S1">Description2 for S1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "S1").WithArguments("S1").WithLocation(5, 18), // (6,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record E(string S1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(string S1)").WithLocation(6, 24) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary2</summary> <param name=""S1"">Description2 for S1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal("", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DifferentParameterLists_XmlDocOnBoth() { var src = @" /// <summary>Summary1</summary> /// <param name=""I1"">Description1 for I1</param> public partial record E(int I1); /// <summary>Summary2</summary> /// <param name=""S1"">Description2 for S1</param> public partial record E(string S1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,18): warning CS1572: XML comment has a param tag for 'S1', but there is no parameter by that name // /// <param name="S1">Description2 for S1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "S1").WithArguments("S1").WithLocation(7, 18), // (8,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record E(string S1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(string S1)").WithLocation(8, 24) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> <summary>Summary2</summary> <param name=""S1"">Description2 for S1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal( @"<member name=""M:E.#ctor(System.Int32)""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> </member> ", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Nested() { var src = @" /// <summary>Summary</summary> public class Outer { /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("Outer.C"); Assert.Equal( @"<member name=""T:Outer.C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:Outer.C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Nested_ReferencingOuterParam() { var src = @" /// <summary>Summary</summary> /// <param name=""O1"">Description for O1</param> public record Outer(object O1) { /// <summary>Summary</summary> public int P1 { get; set; } /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> /// <param name=""O1"">Error O1</param> /// <param name=""P1"">Error P1</param> /// <param name=""C"">Error C</param> public record C(int I1); } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (11,22): warning CS1572: XML comment has a param tag for 'O1', but there is no parameter by that name // /// <param name="O1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "O1").WithArguments("O1").WithLocation(11, 22), // (11,22): warning CS1572: XML comment has a param tag for 'O1', but there is no parameter by that name // /// <param name="O1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "O1").WithArguments("O1").WithLocation(11, 22), // (12,22): warning CS1572: XML comment has a param tag for 'P1', but there is no parameter by that name // /// <param name="P1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "P1").WithArguments("P1").WithLocation(12, 22), // (12,22): warning CS1572: XML comment has a param tag for 'P1', but there is no parameter by that name // /// <param name="P1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "P1").WithArguments("P1").WithLocation(12, 22), // (13,22): warning CS1572: XML comment has a param tag for 'C', but there is no parameter by that name // /// <param name="C">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "C").WithArguments("C").WithLocation(13, 22), // (13,22): warning CS1572: XML comment has a param tag for 'C', but there is no parameter by that name // /// <param name="C">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "C").WithArguments("C").WithLocation(13, 22) ); var cMember = comp.GetMember<NamedTypeSymbol>("Outer.C"); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:Outer.C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> <param name=""O1"">Error O1</param> <param name=""P1"">Error P1</param> <param name=""C"">Error C</param> </member> ", constructor.GetDocumentationCommentXml()); } [Fact, WorkItem(51590, "https://github.com/dotnet/roslyn/issues/51590")] public void SealedIncomplete() { var source = @" public sealed record("; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,21): error CS1001: Identifier expected // public sealed record( Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(2, 21), // (2,22): error CS1026: ) expected // public sealed record( Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(2, 22), // (2,22): error CS1514: { expected // public sealed record( Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(2, 22), // (2,22): error CS1513: } expected // public sealed record( Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(2, 22) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } // hiding } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } // hiding Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Field() { var source = @" public record Base { public int I = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } // hiding } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } // hiding Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Field_HiddenWithConstant() { var source = @" public record Base { public int I = 0; public Base(int ignored) { } } public record C(int I) : Base(I) { public const int I = 0; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,22): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public const int I = 0; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 22) ); } [Fact] public void FieldAsPositionalMember() { var source = @" var a = new A(42); System.Console.Write(a.X); System.Console.Write("" - ""); a.Deconstruct(out int x); System.Console.Write(x); record A(int X) { public int X = X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,10): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(8, 10) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42"); verifier.VerifyIL("A.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_TwoParameters() { var source = @" var a = new A(42, 43); System.Console.Write(a.Y); System.Console.Write("" - ""); a.Deconstruct(out int x, out int y); System.Console.Write(y); record A(int X, int Y) { public int X = X; public int Y = Y; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "43 - 43"); verifier.VerifyIL("A.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: ldfld ""int A.Y"" IL_000f: stind.i4 IL_0010: ret } "); } [Fact] public void FieldAsPositionalMember_Readonly() { var source = @" var a = new A(42); System.Console.Write(a.X); System.Console.Write("" - ""); a.Deconstruct(out int x); System.Console.Write(x); record A(int X) { public readonly int X = X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("A.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_UnusedParameter() { var source = @" record A(int X) { public int X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14), // (4,16): warning CS0649: Field 'A.X' is never assigned to, and will always have its default value 0 // public int X; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "X").WithArguments("A.X", "0").WithLocation(4, 16) ); } [Fact] public void FieldAsPositionalMember_CurrentTypeComesFirst() { var source = @" var c = new C(42); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I { get; set; } = 0; } public record C(int I) : Base { public int I = I; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,16): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public int I = I; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(12, 16) ); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int C.I"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_CurrentTypeComesFirst_FieldInBase() { var source = @" var c = new C(42); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I = 0; } public record C(int I) : Base { public int I { get; set; } = I; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,16): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public int I { get; set; } = I; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(12, 16) ); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int C.I.get"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_FieldFromBase() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int Base.I"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_FieldFromBase_StaticFieldInDerivedType() { var source = @" public record Base { public int I = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public static int I = 42; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public static int I = 42; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23) ); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public static int I = 42; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23) ); source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public static int I { get; set; } = 42; } "; comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public static int I { get; set; } = 42; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23) ); } [Fact] public void FieldAsPositionalMember_Static() { var source = @" record A(int X) { public static int X = 0; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record A(int X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 14) ); } [Fact] public void FieldAsPositionalMember_Const() { var src = @" record C(int P) { const int P = 4; } record C2(int P) { const int P = P; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (2,14): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'. // record C(int P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int", "P").WithLocation(2, 14), // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C(int P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14), // (6,15): error CS8866: Record member 'C2.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'. // record C2(int P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C2.P", "int", "P").WithLocation(6, 15), // (6,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C2(int P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(6, 15), // (8,15): error CS0110: The evaluation of the constant value for 'C2.P' involves a circular definition // const int P = P; Diagnostic(ErrorCode.ERR_CircConstValue, "P").WithArguments("C2.P").WithLocation(8, 15) ); } [Fact] public void FieldAsPositionalMember_Volatile() { var src = @" record C(int P) { public volatile int P = P; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); } [Fact] public void FieldAsPositionalMember_DifferentAccessibility() { var src = @" record C(int P) { private int P = P; } record C2(int P) { protected int P = P; } record C3(int P) { internal int P = P; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); } [Fact] public void FieldAsPositionalMember_WrongType() { var src = @" record C(int P) { public string P = null; public int Q = P; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (2,14): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'. // record C(int P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int", "P").WithLocation(2, 14) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } } "; var expected = new[] { // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(expected); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expected); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod_DeconstructInSource() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } public void Deconstruct(out int i) { i = 0; } } "; var expected = new[] { // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(expected); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expected); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod_WithNew() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) // 1 { public new void I() { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) // 1 Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithGenericMethod() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I<T>() { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (11,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(11, 21), // (13,17): warning CS0108: 'C.I<T>()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I<T>() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I<T>()", "Base.I").WithLocation(13, 17) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_FromGrandBase() { var source = @" public record GrandBase { public int I { get; set; } = 42; } public record Base : GrandBase { public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } } "; var expected = new[] { // (10,21): error CS8913: The positional member 'GrandBase.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("GrandBase.I").WithLocation(10, 21), // (12,17): warning CS0108: 'C.I()' hides inherited member 'GrandBase.I'. Use the new keyword if hiding was intended. // public void I() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "GrandBase.I").WithLocation(12, 17) }; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expected); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_NotHiddenByIndexer() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int Item { get; set; } = 42; public Base(int ignored) { } } public record C(int Item) : Base(Item) { public int this[int x] { get => throw null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int Base.Item.get"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_NotHiddenByIndexer_WithIndexerName() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { [System.Runtime.CompilerServices.IndexerName(""I"")] public int this[int x] { get => throw null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int Base.I.get"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithType() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public class I { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,18): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public class I { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 18) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithEvent() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public event System.Action I; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,32): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public event System.Action I; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 32), // (9,32): warning CS0067: The event 'C.I' is never used // public event System.Action I; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "I").WithArguments("C.I").WithLocation(9, 32) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithConstant() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public const string I = null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,25): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public const string I = null; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 25) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_AbstractInBase() { var source = @" abstract record Base { public abstract int I { get; init; } } record Derived(int I) : Base { public int I() { return 0; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (8,16): warning CS0108: 'Derived.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public int I() { return 0; } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("Derived.I()", "Base.I").WithLocation(8, 16), // (8,16): error CS0102: The type 'Derived' already contains a definition for 'I' // public int I() { return 0; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("Derived", "I").WithLocation(8, 16) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_AbstractInBase_AbstractInDerived() { var source = @" abstract record Base { public abstract int I { get; init; } } abstract record Derived(int I) : Base { public int I() { return 0; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (8,16): error CS0533: 'Derived.I()' hides inherited abstract member 'Base.I' // public int I() { return 0; } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "I").WithArguments("Derived.I()", "Base.I").WithLocation(8, 16), // (8,16): error CS0102: The type 'Derived' already contains a definition for 'I' // public int I() { return 0; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("Derived", "I").WithLocation(8, 16) ); } [Fact] public void InterfaceWithParameters() { var src = @" public interface I { } record R(int X) : I() { } record R2(int X) : I(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,20): error CS8861: Unexpected argument list. // record R(int X) : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 20), // (10,21): error CS8861: Unexpected argument list. // record R2(int X) : I(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 21), // (10,21): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R2(int X) : I(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(10, 21) ); } [Fact] public void InterfaceWithParameters_RecordClass() { var src = @" public interface I { } record class R(int X) : I() { } record class R2(int X) : I(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,26): error CS8861: Unexpected argument list. // record class R(int X) : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 26), // (10,27): error CS8861: Unexpected argument list. // record class R2(int X) : I(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 27), // (10,27): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record class R2(int X) : I(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(10, 27) ); } [Fact] public void BaseErrorTypeWithParameters() { var src = @" record R2(int X) : Error(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0115: 'R2.ToString()': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'R2.EqualityContract': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'R2.Equals(object?)': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'R2.GetHashCode()': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'R2.PrintMembers(StringBuilder)': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,20): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(2, 20), // (2,25): error CS1729: 'Error' does not contain a constructor that takes 1 arguments // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("Error", "1").WithLocation(2, 25) ); } [Fact] public void BaseDynamicTypeWithParameters() { var src = @" record R(int X) : dynamic(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,19): error CS1965: 'R': cannot derive from the dynamic type // record R(int X) : dynamic(X) Diagnostic(ErrorCode.ERR_DeriveFromDynamic, "dynamic").WithArguments("R").WithLocation(2, 19), // (2,26): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : dynamic(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 26) ); } [Fact] public void BaseTypeParameterTypeWithParameters() { var src = @" class C<T> { record R(int X) : T(X) { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,23): error CS0689: Cannot derive from 'T' because it is a type parameter // record R(int X) : T(X) Diagnostic(ErrorCode.ERR_DerivingFromATyVar, "T").WithArguments("T").WithLocation(4, 23), // (4,24): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : T(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(4, 24) ); } [Fact] public void BaseObjectTypeWithParameters() { var src = @" record R(int X) : object(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,25): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : object(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 25) ); } [Fact] public void BaseValueTypeTypeWithParameters() { var src = @" record R(int X) : System.ValueType(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,19): error CS0644: 'R' cannot derive from special class 'ValueType' // record R(int X) : System.ValueType(X) Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "System.ValueType").WithArguments("R", "System.ValueType").WithLocation(2, 19), // (2,35): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : System.ValueType(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 35) ); } [Fact] public void InterfaceWithParameters_NoPrimaryConstructor() { var src = @" public interface I { } record R : I() { } record R2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,13): error CS8861: Unexpected argument list. // record R : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 13), // (10,14): error CS8861: Unexpected argument list. // record R2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 14) ); } [Fact] public void InterfaceWithParameters_Class() { var src = @" public interface I { } class C : I() { } class C2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,12): error CS8861: Unexpected argument list. // class C : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 12), // (10,13): error CS8861: Unexpected argument list. // class C2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 13) ); } [Theory, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [CombinatorialData] public void CrossAssemblySupportingAndNotSupportingCovariantReturns(bool useCompilationReference) { var sourceA = @"public record B(int I) { } public record C(int I) : B(I);"; var compA = CreateEmptyCompilation(new[] { sourceA, IsExternalInitTypeDefinition }, references: TargetFrameworkUtil.GetReferences(TargetFramework.NetStandard20)); compA.VerifyDiagnostics(); Assert.False(compA.Assembly.RuntimeSupportsCovariantReturnsOfClasses); var actualMembers = compA.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 I)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(B? other)", "System.Boolean C.Equals(C? other)", "B C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 I)", }; AssertEx.Equal(expectedMembers, actualMembers); var refA = useCompilationReference ? compA.ToMetadataReference() : compA.EmitToImageReference(); var sourceB = "record D(int I) : C(I);"; // CS1701: Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy var compB = CreateCompilation(sourceB, references: new[] { refA }, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions("CS1701", ReportDiagnostic.Suppress), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compB.VerifyDiagnostics(); Assert.True(compB.Assembly.RuntimeSupportsCovariantReturnsOfClasses); actualMembers = compB.GetMember<NamedTypeSymbol>("D").GetMembers().ToTestDisplayStrings(); expectedMembers = new[] { "D..ctor(System.Int32 I)", "System.Type D.EqualityContract.get", "System.Type D.EqualityContract { get; }", "System.String D.ToString()", "System.Boolean D." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean D.op_Inequality(D? left, D? right)", "System.Boolean D.op_Equality(D? left, D? right)", "System.Int32 D.GetHashCode()", "System.Boolean D.Equals(System.Object? obj)", "System.Boolean D.Equals(C? other)", "System.Boolean D.Equals(D? other)", "D D." + WellKnownMemberNames.CloneMethodName + "()", "D..ctor(D original)", "void D.Deconstruct(out System.Int32 I)" }; AssertEx.Equal(expectedMembers, actualMembers); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class RecordTests : CompilingTestBase { private static CSharpCompilation CreateCompilation(CSharpTestSource source) => CSharpTestBase.CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); private CompilationVerifier CompileAndVerify( CSharpTestSource src, string? expectedOutput = null, IEnumerable<MetadataReference>? references = null) => base.CompileAndVerify( new[] { src, IsExternalInitTypeDefinition }, expectedOutput: expectedOutput, parseOptions: TestOptions.RegularPreview, references: references, // init-only is unverifiable verify: Verification.Skipped); [Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")] public void RecordLanguageVersion() { var src1 = @" class Point(int x, int y); "; var src2 = @" record Point { } "; var src3 = @" record Point(int x, int y); "; var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,12): error CS8805: Program using top-level statements must be an executable. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 12), // (2,12): error CS8803: Top-level statements must precede namespace and type declarations. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // class Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 12), // (2,13): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 13), // (2,13): error CS0165: Use of unassigned local variable 'x' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 13), // (2,20): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 20), // (2,20): error CS0165: Use of unassigned local variable 'y' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 20) ); comp = CreateCompilation(src2, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,1): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(2, 1), // (2,8): error CS0116: A namespace cannot directly contain members such as fields or methods // record Point { } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Point").WithLocation(2, 8), // (2,8): error CS0548: '<invalid-global-code>.Point': property or indexer must have at least one accessor // record Point { } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "Point").WithArguments("<invalid-global-code>.Point").WithLocation(2, 8) ); comp = CreateCompilation(src3, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,1): error CS8805: Program using top-level statements must be an executable. // record Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "record Point(int x, int y);").WithLocation(2, 1), // (2,1): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // record Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "record Point(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 1), // (2,1): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point(int x, int y); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(2, 1), // (2,8): error CS8112: Local function 'Point(int, int)' must declare a body because it is not marked 'static extern'. // record Point(int x, int y); Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Point").WithArguments("Point(int, int)").WithLocation(2, 8), // (2,8): warning CS8321: The local function 'Point' is declared but never used // record Point(int x, int y); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Point").WithArguments("Point").WithLocation(2, 8) ); comp = CreateCompilation(src1, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,12): error CS8805: Program using top-level statements must be an executable. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS8803: Top-level statements must precede namespace and type declarations. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // class Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 12), // (2,13): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 13), // (2,13): error CS0165: Use of unassigned local variable 'x' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 13), // (2,20): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 20), // (2,20): error CS0165: Use of unassigned local variable 'y' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 20) ); comp = CreateCompilation(src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src3); comp.VerifyDiagnostics(); var point = comp.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsReferenceType); Assert.False(point.IsValueType); Assert.Equal(TypeKind.Class, point.TypeKind); Assert.Equal(SpecialType.System_Object, point.BaseTypeNoUseSiteDiagnostics.SpecialType); } [Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")] public void RecordLanguageVersion_Nested() { var src1 = @" class C { class Point(int x, int y); } "; var src2 = @" class D { record Point { } } "; var src3 = @" class E { record Point(int x, int y); } "; var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,16): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 16), // (4,16): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 16), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30) ); comp = CreateCompilation(src2, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(4, 5), // (4,12): error CS0548: 'D.Point': property or indexer must have at least one accessor // record Point { } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "Point").WithArguments("D.Point").WithLocation(4, 12) ); comp = CreateCompilation(src3, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point(int x, int y); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(4, 5), // (4,12): error CS0501: 'E.Point(int, int)' must declare a body because it is not marked abstract, extern, or partial // record Point(int x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "Point").WithArguments("E.Point(int, int)").WithLocation(4, 12) ); comp = CreateCompilation(src1); comp.VerifyDiagnostics( // (4,16): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 16), // (4,16): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 16), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30) ); comp = CreateCompilation(src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src3); comp.VerifyDiagnostics(); } [Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")] public void RecordClassLanguageVersion() { var src = @" record class Point(int x, int y); "; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,1): error CS0116: A namespace cannot directly contain members such as fields or methods // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "record").WithLocation(2, 1), // (2,19): error CS1514: { expected // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 19), // (2,19): error CS1513: } expected // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 19), // (2,19): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 19), // (2,19): error CS8803: Top-level statements must precede namespace and type declarations. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 19), // (2,19): error CS8805: Program using top-level statements must be an executable. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 19), // (2,19): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 19), // (2,20): error CS8185: A declaration is not allowed in this context. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 20), // (2,20): error CS0165: Use of unassigned local variable 'x' // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 20), // (2,27): error CS8185: A declaration is not allowed in this context. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 27), // (2,27): error CS0165: Use of unassigned local variable 'y' // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 27) ); comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "class").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [CombinatorialData] [Theory, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")] public void GetSimpleNonTypeMembers(bool useCompilationReference) { var lib_src = @" public record RecordA(RecordB B); public record RecordB(int C); "; var lib_comp = CreateCompilation(lib_src); var src = @" class C { void M(RecordA a, RecordB b) { _ = a.B == b; } } "; var comp = CreateCompilation(src, references: new[] { AsReference(lib_comp, useCompilationReference) }); comp.VerifyEmitDiagnostics(); } [Fact, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")] public void GetSimpleNonTypeMembers_SingleCompilation() { var src = @" public record RecordA(RecordB B); public record RecordB(int C); class C { void M(RecordA a, RecordB b) { _ = a.B == b; } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); Assert.Equal("System.Boolean RecordB.op_Equality(RecordB? left, RecordB? right)", model.GetSymbolInfo(node).Symbol.ToTestDisplayString()); } [Fact, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")] public void GetSimpleNonTypeMembers_DirectApiCheck() { var src = @" public record RecordB(); "; var comp = CreateCompilation(src); var b = comp.GlobalNamespace.GetTypeMember("RecordB"); AssertEx.SetEqual(new[] { "System.Boolean RecordB.op_Equality(RecordB? left, RecordB? right)" }, b.GetSimpleNonTypeMembers("op_Equality").ToTestDisplayStrings()); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor() { var src = @" record R(R x); #nullable enable record R2(R2? x) { } record R3([System.Diagnostics.CodeAnalysis.NotNull] R3 x); "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyEmitDiagnostics( // (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R(R x); Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8), // (5,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R2(R2? x) { } Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R2").WithLocation(5, 8), // (7,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R3([System.Diagnostics.CodeAnalysis.NotNull] R3 x); Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R3").WithLocation(7, 8) ); var r = comp.GlobalNamespace.GetTypeMember("R"); Assert.Equal(new[] { "R..ctor(R x)", "R..ctor(R original)" }, r.GetMembers(".ctor").ToTestDisplayStrings()); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_Generic() { var src = @" record R<T>(R<T> x); #nullable enable record R2<T>(R2<T?> x) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R<T>(R<T> x); Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8), // (5,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R2<T>(R2<T?> x) { } Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R2").WithLocation(5, 8) ); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_WithExplicitCopyCtor() { var src = @" record R(R x) { public R(R x) => throw null; } "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyEmitDiagnostics( // (4,12): error CS0111: Type 'R' already defines a member called 'R' with the same parameter types // public R(R x) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R").WithArguments("R", "R").WithLocation(4, 12) ); var r = comp.GlobalNamespace.GetTypeMember("R"); Assert.Equal(new[] { "R..ctor(R x)", "R..ctor(R x)" }, r.GetMembers(".ctor").ToTestDisplayStrings()); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_WithBase() { var src = @" record Base; record R(R x) : Base; // 1 record Derived(Derived y) : R(y) // 2 { public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 } record Derived2(Derived2 y) : R(y); // 6, 7, 8 record R2(R2 x) : Base { public R2(R2 x) => throw null; // 9, 10 } record R3(R3 x) : Base { public R3(R3 x) : base(x) => throw null; // 11 } "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyEmitDiagnostics( // (4,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R(R x) : Base; // 1 Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(4, 8), // (6,30): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)' // record Derived(Derived y) : R(y) // 2 Diagnostic(ErrorCode.ERR_AmbigCall, "(y)").WithArguments("R.R(R)", "R.R(R)").WithLocation(6, 30), // (8,12): error CS0111: Type 'Derived' already defines a member called 'Derived' with the same parameter types // public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Derived").WithArguments("Derived", "Derived").WithLocation(8, 12), // (8,33): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)' // public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 Diagnostic(ErrorCode.ERR_AmbigCall, "base").WithArguments("R.R(R)", "R.R(R)").WithLocation(8, 33), // (8,33): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(8, 33), // (11,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record Derived2(Derived2 y) : R(y); // 6, 7, 8 Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "Derived2").WithLocation(11, 8), // (11,8): error CS8867: No accessible copy constructor found in base type 'R'. // record Derived2(Derived2 y) : R(y); // 6, 7, 8 Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "Derived2").WithArguments("R").WithLocation(11, 8), // (11,32): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)' // record Derived2(Derived2 y) : R(y); // 6, 7, 8 Diagnostic(ErrorCode.ERR_AmbigCall, "(y)").WithArguments("R.R(R)", "R.R(R)").WithLocation(11, 32), // (15,12): error CS0111: Type 'R2' already defines a member called 'R2' with the same parameter types // public R2(R2 x) => throw null; // 9, 10 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R2").WithArguments("R2", "R2").WithLocation(15, 12), // (15,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public R2(R2 x) => throw null; // 9, 10 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "R2").WithLocation(15, 12), // (20,12): error CS0111: Type 'R3' already defines a member called 'R3' with the same parameter types // public R3(R3 x) : base(x) => throw null; // 11 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R3").WithArguments("R3", "R3").WithLocation(20, 12) ); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_WithPropertyInitializer() { var src = @" record R(R X) { public R X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R(R X) Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var parameterSyntax = tree.GetRoot().DescendantNodes().OfType<ParameterSyntax>().Single(); var parameter = model.GetDeclaredSymbol(parameterSyntax)!; Assert.Equal("R X", parameter.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, parameter.Kind); Assert.Equal("R..ctor(R X)", parameter.ContainingSymbol.ToTestDisplayString()); var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); var initializer = model.GetSymbolInfo(initializerSyntax.Value).Symbol!; Assert.Equal("R X", initializer.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, initializer.Kind); Assert.Equal("R..ctor(R X)", initializer.ContainingSymbol.ToTestDisplayString()); } [Fact] public void GetDeclaredSymbolOnAnOutLocalInPropertyInitializer() { var src = @" record R(int I) { public int I { get; init; } = M(out int i) ? i : 0; static bool M(out int i) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,14): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // record R(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 14) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var outVarSyntax = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Single(); var outVar = model.GetDeclaredSymbol(outVarSyntax)!; Assert.Equal("System.Int32 i", outVar.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, outVar.Kind); Assert.Equal("System.Int32 R.<I>k__BackingField", outVar.ContainingSymbol.ToTestDisplayString()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord() { string source = @" public record A(int i,) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,23): error CS1031: Type expected // public record A(int i,) { } Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(2, 23), // (2,23): error CS1001: Identifier expected // public record A(int i,) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 23) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A.i { get; init; }", "? A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); AssertEx.Equal(new[] { "A..ctor(System.Int32 i, ?)", "A..ctor(A original)" }, comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings()); var primaryCtor = comp.GetMember<NamedTypeSymbol>("A").Constructors.First(); Assert.Equal("A..ctor(System.Int32 i, ?)", primaryCtor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTrivia() { string source = @" public record A(int i, // A // B , /* C */ ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,23): error CS1031: Type expected // public record A(int i, // A Diagnostic(ErrorCode.ERR_TypeExpected, "").WithLocation(2, 23), // (2,23): error CS1001: Identifier expected // public record A(int i, // A Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(2, 23), // (4,15): error CS1031: Type expected // , /* C */ ) { } Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(4, 15), // (4,15): error CS1001: Identifier expected // , /* C */ ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 15), // (4,15): error CS0102: The type 'A' already contains a definition for '' // , /* C */ ) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(4, 15) ); var primaryCtor = comp.GetMember<NamedTypeSymbol>("A").Constructors.First(); Assert.Equal("A..ctor(System.Int32 i, ?, ?)", primaryCtor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[0].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[2].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompleteConstructor() { string source = @" public class C { C(int i, ) { } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,14): error CS1031: Type expected // C(int i, ) { } Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(4, 14), // (4,14): error CS1001: Identifier expected // C(int i, ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 14) ); var ctor = comp.GetMember<NamedTypeSymbol>("C").Constructors.Single(); Assert.Equal("C..ctor(System.Int32 i, ?)", ctor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(0, ctor.Parameters[1].Locations.Single().SourceSpan.Length); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithType() { string source = @" public record A(int i, int ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,28): error CS1001: Identifier expected // public record A(int i, int ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 28) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A.i { get; init; }", "System.Int32 A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var ctor = comp.GetMember<NamedTypeSymbol>("A").Constructors[0]; Assert.Equal("A..ctor(System.Int32 i, System.Int32)", ctor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(0, ctor.Parameters[1].Locations.Single().SourceSpan.Length); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTwoTypes() { string source = @" public record A(int, string ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,20): error CS1001: Identifier expected // public record A(int, string ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(2, 20), // (2,29): error CS1001: Identifier expected // public record A(int, string ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 29), // (2,29): error CS0102: The type 'A' already contains a definition for '' // public record A(int, string ) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(2, 29) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A. { get; init; }", "System.String A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); AssertEx.Equal(new[] { "A..ctor(System.Int32, System.String)", "A..ctor(A original)" }, comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings()); Assert.IsType<ParameterSyntax>(comp.GetMember<NamedTypeSymbol>("A").Constructors[0].Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTwoTypes_SameType() { string source = @" public record A(int, int ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,20): error CS1001: Identifier expected // public record A(int, int ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(2, 20), // (2,26): error CS1001: Identifier expected // public record A(int, int ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 26), // (2,26): error CS0102: The type 'A' already contains a definition for '' // public record A(int, int ) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(2, 26) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A. { get; init; }", "System.Int32 A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); AssertEx.Equal(new[] { "A..ctor(System.Int32, System.Int32)", "A..ctor(A original)" }, comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings()); Assert.IsType<ParameterSyntax>(comp.GetMember<NamedTypeSymbol>("A").Constructors[0].Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTwoTypes_WithTrivia() { string source = @" public record A(int // A // B , int /* C */) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,20): error CS1001: Identifier expected // public record A(int // A Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(2, 20), // (4,18): error CS1001: Identifier expected // , int /* C */) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 18), // (4,18): error CS0102: The type 'A' already contains a definition for '' // , int /* C */) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(4, 18) ); var ctor = comp.GetMember<NamedTypeSymbol>("A").Constructors[0]; Assert.IsType<ParameterSyntax>(ctor.Parameters[0].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46083, "https://github.com/dotnet/roslyn/issues/46083")] public void IncompletePositionalRecord_SingleParameter() { string source = @" record A(x) "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,10): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?) // record A(x) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(2, 10), // (2,11): error CS1001: Identifier expected // record A(x) Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 11), // (2,12): error CS1514: { expected // record A(x) Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(2, 12), // (2,12): error CS1513: } expected // record A(x) Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(2, 12) ); } [Fact] public void TestWithInExpressionTree() { var source = @" using System; using System.Linq.Expressions; public record C(int i) { public static void M() { Expression<Func<C, C>> expr = c => c with { i = 5 }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,44): error CS8849: An expression tree may not contain a with-expression. // Expression<Func<C, C>> expr = c => c with { i = 5 }; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsWithExpression, "c with { i = 5 }").WithLocation(8, 44) ); } [Fact] public void PartialRecord_MixedWithClass() { var src = @" partial record C(int X, int Y) { } partial class C { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,15): error CS0261: Partial declarations of 'C' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class C Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C").WithArguments("C").WithLocation(5, 15) ); } [Fact] public void PartialRecord_ParametersInScopeOfBothParts() { var src = @" var c = new C(2); System.Console.Write((c.P1, c.P2)); public partial record C(int X) { public int P1 { get; set; } = X; } public partial record C { public int P2 { get; set; } = X; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */).VerifyDiagnostics(); } [Fact] public void PartialRecord_ParametersInScopeOfBothParts_RecordClass() { var src = @" var c = new C(2); System.Console.Write((c.P1, c.P2)); public partial record C(int X) { public int P1 { get; set; } = X; } public partial record class C { public int P2 { get; set; } = X; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */).VerifyDiagnostics(); } [Fact] public void PartialRecord_DuplicateMemberNames() { var src = @" public partial record C(int X) { public void M(int i) { } } public partial record C { public void M(string s) { } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }); var expectedMemberNames = new string[] { ".ctor", "get_EqualityContract", "EqualityContract", "<X>k__BackingField", "get_X", "set_X", "X", "M", "M", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordInsideGenericType() { var src = @" var c = new C<int>.Nested(2); System.Console.Write(c.T); public class C<T> { public record Nested(T T); } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2", verify: Verification.Skipped /* init-only */); } [Fact] public void RecordProperties_01() { var src = @" using System; record C(int X, int Y) { int Z = 123; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); Console.WriteLine(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2 123").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.s 123 IL_0011: stfld ""int C.Z"" IL_0016: ldarg.0 IL_0017: call ""object..ctor()"" IL_001c: ret } "); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); var x = (IPropertySymbol)c.GetMember("X"); Assert.Equal("System.Int32 C.X.get", x.GetMethod.ToTestDisplayString()); Assert.Equal("void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init", x.SetMethod.ToTestDisplayString()); Assert.True(x.SetMethod!.IsInitOnly); var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField"); Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString()); Assert.True(xBackingField.IsReadOnly); } [Fact] public void RecordProperties_02() { var src = @" using System; record C(int X, int Y) { public C(int a, int b) { } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } private int X1 = X; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types // public C(int a, int b) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(5, 12), // (5,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public C(int a, int b) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(5, 12), // (11,21): error CS0121: The call is ambiguous between the following methods or properties: 'C.C(int, int)' and 'C.C(int, int)' // var c = new C(1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "C").WithArguments("C.C(int, int)", "C.C(int, int)").WithLocation(11, 21) ); } [Fact] public void RecordProperties_03() { var src = @" using System; record C(int X, int Y) { public int X { get; } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } }"; CompileAndVerify(src, expectedOutput: @" 0 2").VerifyDiagnostics( // (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14) ); } [Fact] public void RecordProperties_04() { var src = @" using System; record C(int X, int Y) { public int X { get; } = 3; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } }"; CompileAndVerify(src, expectedOutput: @" 3 2").VerifyDiagnostics( // (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14) ); } [Fact, WorkItem(48947, "https://github.com/dotnet/roslyn/issues/48947")] public void RecordProperties_05() { var src = @" record C(int X, int X) { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,21): error CS0100: The parameter name 'X' is a duplicate // record C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 21), // (2,21): error CS0102: The type 'C' already contains a definition for 'X' // record C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 21) ); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; init; }", "System.Int32 C.X { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var expectedMemberNames = new[] { ".ctor", "get_EqualityContract", "EqualityContract", "<X>k__BackingField", "get_X", "set_X", "X", "<X>k__BackingField", "get_X", "set_X", "X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordProperties_05_RecordClass() { var src = @" record class C(int X, int X) { }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (2,27): error CS0100: The parameter name 'X' is a duplicate // record class C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 27), // (2,27): error CS0102: The type 'C' already contains a definition for 'X' // record class C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 27) ); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; init; }", "System.Int32 C.X { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var expectedMemberNames = new[] { ".ctor", "get_EqualityContract", "EqualityContract", "<X>k__BackingField", "get_X", "set_X", "X", "<X>k__BackingField", "get_X", "set_X", "X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordProperties_06() { var src = @" record C(int X, int Y) { public void get_X() { } public void set_X() { } int get_Y(int value) => value; int set_Y(int value) => value; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,14): error CS0082: Type 'C' already reserves a member called 'get_X' with the same parameter types // record C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "X").WithArguments("get_X", "C").WithLocation(2, 14), // (2,21): error CS0082: Type 'C' already reserves a member called 'set_Y' with the same parameter types // record C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "Y").WithArguments("set_Y", "C").WithLocation(2, 21)); var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.Int32 C.<X>k__BackingField", "System.Int32 C.X.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init", "System.Int32 C.X { get; init; }", "System.Int32 C.<Y>k__BackingField", "System.Int32 C.Y.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.Y.init", "System.Int32 C.Y { get; init; }", "void C.get_X()", "void C.set_X()", "System.Int32 C.get_Y(System.Int32 value)", "System.Int32 C.set_Y(System.Int32 value)", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void RecordProperties_07() { var comp = CreateCompilation(@" record C1(object P, object get_P); record C2(object get_P, object P);"); comp.VerifyDiagnostics( // (2,18): error CS0102: The type 'C1' already contains a definition for 'get_P' // record C1(object P, object get_P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C1", "get_P").WithLocation(2, 18), // (3,32): error CS0102: The type 'C2' already contains a definition for 'get_P' // record C2(object get_P, object P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C2", "get_P").WithLocation(3, 32) ); } [Fact] public void RecordProperties_08() { var comp = CreateCompilation(@" record C1(object O1) { public object O1 { get; } = O1; public object O2 { get; } = O1; }"); comp.VerifyDiagnostics(); } [Fact] public void RecordProperties_09() { var src = @"record C(object P1, object P2, object P3, object P4) { class P1 { } object P2 = 2; int P3(object o) => 3; int P4<T>(T t) => 4; }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,17): error CS0102: The type 'C' already contains a definition for 'P1' // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(1, 17), // (1,21): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object P2").WithArguments("positional fields in records", "10.0").WithLocation(1, 21), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (5,9): error CS0102: The type 'C' already contains a definition for 'P3' // int P3(object o) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(5, 9), // (6,9): error CS0102: The type 'C' already contains a definition for 'P4' // int P4<T>(T t) => 4; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(6, 9) ); comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (1,17): error CS0102: The type 'C' already contains a definition for 'P1' // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(1, 17), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (5,9): error CS0102: The type 'C' already contains a definition for 'P3' // int P3(object o) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(5, 9), // (6,9): error CS0102: The type 'C' already contains a definition for 'P4' // int P4<T>(T t) => 4; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(6, 9) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes() { var src = @" class C<T> { } static class C2 { } ref struct RefLike{} unsafe record C( // 1 int* P1, // 2 int*[] P2, // 3 C<int*[]> P3, delegate*<int, int> P4, // 4 void P5, // 5 C2 P6, // 6, 7 System.ArgIterator P7, // 8 System.TypedReference P8, // 9 RefLike P9); // 10 "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (6,15): error CS0721: 'C2': static types cannot be used as parameters // unsafe record C( // 1 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C").WithArguments("C2").WithLocation(6, 15), // (7,10): error CS8908: The type 'int*' may not be used for a field of a record. // int* P1, // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P1").WithArguments("int*").WithLocation(7, 10), // (8,12): error CS8908: The type 'int*[]' may not be used for a field of a record. // int*[] P2, // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P2").WithArguments("int*[]").WithLocation(8, 12), // (10,25): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // delegate*<int, int> P4, // 4 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P4").WithArguments("delegate*<int, int>").WithLocation(10, 25), // (11,5): error CS1536: Invalid parameter type 'void' // void P5, // 5 Diagnostic(ErrorCode.ERR_NoVoidParameter, "void").WithLocation(11, 5), // (12,8): error CS0722: 'C2': static types cannot be used as return types // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (12,8): error CS0721: 'C2': static types cannot be used as parameters // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (13,5): error CS0610: Field or property cannot be of type 'ArgIterator' // System.ArgIterator P7, // 8 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 5), // (14,5): error CS0610: Field or property cannot be of type 'TypedReference' // System.TypedReference P8, // 9 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 5), // (15,5): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // RefLike P9); // 10 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 5) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public int* f1; // 1 public int*[] f2; // 2 public C<int*[]> f3; public delegate*<int, int> f4; // 3 public void f5; // 4 public C2 f6; // 5 public System.ArgIterator f7; // 6 public System.TypedReference f8; // 7 public RefLike f9; // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1; // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2; // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4; // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,12): error CS0670: Field cannot have void type // public void f5; // 4 Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void").WithLocation(12, 12), // (13,15): error CS0723: Cannot declare a variable of static type 'C2' // public C2 f6; // 5 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(13, 15), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7; // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8; // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9; // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers_AutoProperties() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public int* f1 { get; set; } // 1 public int*[] f2 { get; set; } // 2 public C<int*[]> f3 { get; set; } public delegate*<int, int> f4 { get; set; } // 3 public void f5 { get; set; } // 4 public C2 f6 { get; set; } // 5, 6 public System.ArgIterator f7 { get; set; } // 6 public System.TypedReference f8 { get; set; } // 7 public RefLike f9 { get; set; } // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1 { get; set; } // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2 { get; set; } // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4 { get; set; } // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,17): error CS0547: 'C.f5': property or indexer cannot have void type // public void f5 { get; set; } // 4 Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "f5").WithArguments("C.f5").WithLocation(12, 17), // (13,20): error CS0722: 'C2': static types cannot be used as return types // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("C2").WithLocation(13, 20), // (13,25): error CS0721: 'C2': static types cannot be used as parameters // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("C2").WithLocation(13, 25), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7 { get; set; } // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8 { get; set; } // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9 { get; set; } // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [Fact] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_PointerTypeAllowedForParameterAndProperty() { var src = @" class C<T> { } unsafe record C(int* P1, int*[] P2, C<int*[]> P3) { int* P1 { get { System.Console.Write(""P1 ""); return null; } init { } } int*[] P2 { get { System.Console.Write(""P2 ""); return null; } init { } } C<int*[]> P3 { get { System.Console.Write(""P3 ""); return null; } init { } } public unsafe static void Main() { var x = new C(null, null, null); var (x1, x2, x3) = x; System.Console.Write(""RAN""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugExe); comp.VerifyEmitDiagnostics( // (4,22): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // unsafe record C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(4, 22), // (4,33): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // unsafe record C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(4, 33), // (4,47): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // unsafe record C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(4, 47) ); CompileAndVerify(comp, expectedOutput: "P1 P2 P3 RAN", verify: Verification.Skipped /* pointers */); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_StaticFields() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public static int* f1; public static int*[] f2; public static C<int*[]> f3; public static delegate*<int, int> f4; public static C2 f6; // 1 public static System.ArgIterator f7; // 2 public static System.TypedReference f8; // 3 public static RefLike f9; // 4 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (12,22): error CS0723: Cannot declare a variable of static type 'C2' // public static C2 f6; // 1 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(12, 22), // (13,19): error CS0610: Field or property cannot be of type 'ArgIterator' // public static System.ArgIterator f7; // 2 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 19), // (14,19): error CS0610: Field or property cannot be of type 'TypedReference' // public static System.TypedReference f8; // 3 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 19), // (15,19): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public static RefLike f9; // 4 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 19) ); } [Fact, WorkItem(48584, "https://github.com/dotnet/roslyn/issues/48584")] public void RecordProperties_11_UnreadPositionalParameter() { var comp = CreateCompilation(@" record C1(object O1, object O2, object O3) // 1, 2 { public object O1 { get; init; } public object O2 { get; init; } = M(O2); public object O3 { get; init; } = M(O3 = null); private static object M(object o) => o; } record Base(object O); record C2(object O4) : Base(O4) // we didn't complain because the parameter is read { public object O4 { get; init; } } record C3(object O5) : Base((System.Func<object, object>)(x => x)) // 3 { public object O5 { get; init; } } record C4(object O6) : Base((System.Func<object, object>)(_ => O6)) { public object O6 { get; init; } } record C5(object O7) : Base((System.Func<object, object>)(_ => (O7 = 42) )) // 4 { public object O7 { get; init; } } "); comp.VerifyDiagnostics( // (2,18): warning CS8907: Parameter 'O1' is unread. Did you forget to use it to initialize the property with that name? // record C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O1").WithArguments("O1").WithLocation(2, 18), // (2,40): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 40), // (16,18): warning CS8907: Parameter 'O5' is unread. Did you forget to use it to initialize the property with that name? // record C3(object O5) : Base((System.Func<object, object>)(x => x)) // 3 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O5").WithArguments("O5").WithLocation(16, 18), // (26,18): warning CS8907: Parameter 'O7' is unread. Did you forget to use it to initialize the property with that name? // record C5(object O7) : Base((System.Func<object, object>)(_ => (O7 = 42) )) // 4 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O7").WithArguments("O7").WithLocation(26, 18) ); } [Fact, WorkItem(48584, "https://github.com/dotnet/roslyn/issues/48584")] public void RecordProperties_11_UnreadPositionalParameter_InRefOut() { var comp = CreateCompilation(@" record C1(object O1, object O2, object O3) // 1 { public object O1 { get; init; } = MIn(in O1); public object O2 { get; init; } = MRef(ref O2); public object O3 { get; init; } = MOut(out O3); static object MIn(in object o) => o; static object MRef(ref object o) => o; static object MOut(out object o) => throw null; } "); comp.VerifyDiagnostics( // (2,40): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record C1(object O1, object O2, object O3) // 1 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 40) ); } [Fact] public void EmptyRecord_01() { var src = @" record C(); class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); var comp = (CSharpCompilation)verifier.Compilation; var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor()", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void EmptyRecord_01_RecordClass() { var src = @" record class C(); class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True", parseOptions: TestOptions.Regular10); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); var comp = (CSharpCompilation)verifier.Compilation; var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor()", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void EmptyRecord_02() { var src = @" record C() { C(int x) {} } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,5): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // C(int x) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C", isSuppressed: false).WithLocation(4, 5) ); } [Fact] public void EmptyRecord_03() { var src = @" record B { public B(int x) { System.Console.WriteLine(x); } } record C() : B(12) { C(int x) : this() {} } class Program { static void Main() { _ = new C(); } } "; var verifier = CompileAndVerify(src, expectedOutput: "12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 12 IL_0003: call ""B..ctor(int)"" IL_0008: ret } "); } [Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")] public void StaticCtor() { var src = @" record R(int x) { static void Main() { } static R() { System.Console.Write(""static ctor""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); // [ : R::set_x] Cannot change initonly field outside its .ctor. CompileAndVerify(comp, expectedOutput: "static ctor", verify: Verification.Skipped); } [Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")] public void StaticCtor_ParameterlessPrimaryCtor() { var src = @" record R() { static R() { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")] public void StaticCtor_CopyCtor() { var src = @" record R() { static R(R r) { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,12): error CS0132: 'R.R(R)': a static constructor must be parameterless // static R(R r) { } Diagnostic(ErrorCode.ERR_StaticConstParam, "R").WithArguments("R.R(R)").WithLocation(4, 12) ); } [Fact] public void WithExpr1() { var src = @" record C(int X) { public static void Main() { var c = new C(0); _ = Main() with { }; _ = default with { }; _ = null with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,13): error CS8802: The receiver of a `with` expression must have a valid non-void type. // _ = Main() with { }; Diagnostic(ErrorCode.ERR_InvalidWithReceiverType, "Main()").WithLocation(7, 13), // (8,13): error CS8716: There is no target type for the default literal. // _ = default with { }; Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(8, 13), // (9,13): error CS8802: The receiver of a `with` expression must have a valid non-void type. // _ = null with { }; Diagnostic(ErrorCode.ERR_InvalidWithReceiverType, "null").WithLocation(9, 13) ); } [Fact] public void WithExpr2() { var src = @" using System; record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; Console.WriteLine(c1.X); Console.WriteLine(c2.X); } }"; CompileAndVerify(src, expectedOutput: @"1 11").VerifyDiagnostics(); } [Fact] public void WithExpr3() { var src = @" record C(int X) { public static void Main() { var c = new C(0); c = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var root = comp.SyntaxTrees[0].GetRoot(); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0)') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0)') Right: IObjectCreationOperation (Constructor: C..ctor(System.Int32 X)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') 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) Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with { };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with { }') Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Right: IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { }') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr4() { var src = @" class B { public B Clone() => null; } record C(int X) : B { public static void Main() { var c = new C(0); c = c with { }; } public new C Clone() => null; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr6() { var src = @" record B { public int X { get; init; } } record C : B { public static void Main() { var c = new C(); c = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr7() { var src = @" record B { public int X { get; } } record C : B { public new int X { get; init; } public static void Main() { var c = new C(); B b = c; b = b with { X = 0 }; var b2 = c with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (14,22): error CS0200: Property or indexer 'B.X' cannot be assigned to -- it is read only // b = b with { X = 0 }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "X").WithArguments("B.X").WithLocation(14, 22) ); } [Fact] public void WithExpr8() { var src = @" record B { public int X { get; } } record C : B { public string Y { get; } public static void Main() { var c = new C(); B b = c; b = b with { }; b = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr9() { var src = @" record C(int X) { public string Clone() => null; public static void Main() { var c = new C(0); c = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS8859: Members named 'Clone' are disallowed in records. // public string Clone() => null; Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(4, 19) ); } [Fact] public void WithExpr11() { var src = @" record C(int X) { public static void Main() { var c = new C(0); c = c with { X = """"}; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int' // c = c with { X = ""}; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(8, 26) ); } [Fact] public void WithExpr12() { var src = @" using System; record C(int X) { public static void Main() { var c = new C(0); Console.WriteLine(c.X); c = c with { X = 5 }; Console.WriteLine(c.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 5").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 40 (0x28) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: newobj ""C..ctor(int)"" IL_0006: dup IL_0007: callvirt ""int C.X.get"" IL_000c: call ""void System.Console.WriteLine(int)"" IL_0011: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0016: dup IL_0017: ldc.i4.5 IL_0018: callvirt ""void C.X.init"" IL_001d: callvirt ""int C.X.get"" IL_0022: call ""void System.Console.WriteLine(int)"" IL_0027: ret }"); } [Fact] public void WithExpr13() { var src = @" using System; record C(int X, int Y) { public override string ToString() => X + "" "" + Y; public static void Main() { var c = new C(0, 1); Console.WriteLine(c); c = c with { X = 5 }; Console.WriteLine(c); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 1 5 1").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 31 (0x1f) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""C..ctor(int, int)"" IL_0007: dup IL_0008: call ""void System.Console.WriteLine(object)"" IL_000d: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0012: dup IL_0013: ldc.i4.5 IL_0014: callvirt ""void C.X.init"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ret }"); } [Fact] public void WithExpr14() { var src = @" using System; record C(int X, int Y) { public override string ToString() => X + "" "" + Y; public static void Main() { var c = new C(0, 1); Console.WriteLine(c); c = c with { X = 5 }; Console.WriteLine(c); c = c with { Y = 2 }; Console.WriteLine(c); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 1 5 1 5 2").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 49 (0x31) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""C..ctor(int, int)"" IL_0007: dup IL_0008: call ""void System.Console.WriteLine(object)"" IL_000d: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0012: dup IL_0013: ldc.i4.5 IL_0014: callvirt ""void C.X.init"" IL_0019: dup IL_001a: call ""void System.Console.WriteLine(object)"" IL_001f: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0024: dup IL_0025: ldc.i4.2 IL_0026: callvirt ""void C.Y.init"" IL_002b: call ""void System.Console.WriteLine(object)"" IL_0030: ret }"); } [Fact] public void WithExpr15() { var src = @" record C(int X, int Y) { public static void Main() { var c = new C(0, 0); c = c with { = 5 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,22): error CS1525: Invalid expression term '=' // c = c with { = 5 }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(8, 22) ); } [Fact] public void WithExpr16() { var src = @" record C(int X, int Y) { public static void Main() { var c = new C(0, 0); c = c with { X = }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS1525: Invalid expression term '}' // c = c with { X = }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "}").WithArguments("}").WithLocation(8, 26) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr17() { var src = @" record B { public int X { get; } private B Clone() => null; } record C(int X) : B { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8803: The 'with' expression requires the receiver type 'B' to have a single accessible non-inherited instance method named "Clone". // b = b with { }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr18() { var src = @" class B { public int X { get; } protected B Clone() => null; } record C(int X) : B { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8803: The receiver type 'B' does not have an accessible parameterless instance method named "Clone". // b = b with { }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13) ); } [Fact] public void WithExpr19() { var src = @" class B { public int X { get; } protected B Clone() => null; } record C(int X) { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8803: The 'with' expression requires the receiver type 'B' to have a single accessible non-inherited instance method named "Clone". // b = b with { }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13) ); } [Fact] public void WithExpr20() { var src = @" using System; record C { public event Action X; public static void Main() { var c = new C(); c = c with { X = null }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,25): warning CS0067: The event 'C.X' is never used // public event Action X; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "X").WithArguments("C.X").WithLocation(5, 25) ); } [Fact] public void WithExpr21() { var src = @" record B { public class X { } } class C { public static void Main() { var b = new B(); b = b with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,22): error CS0572: 'X': cannot reference a type through an expression; try 'B.X' instead // b = b with { X = 0 }; Diagnostic(ErrorCode.ERR_BadTypeReference, "X").WithArguments("X", "B.X").WithLocation(11, 22), // (11,22): error CS1913: Member 'X' cannot be initialized. It is not a field or property. // b = b with { X = 0 }; Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "X").WithArguments("X").WithLocation(11, 22) ); } [Fact] public void WithExpr22() { var src = @" record B { public int X = 0; } class C { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr23() { var src = @" class B { public int X = 0; public B Clone() => null; } record C(int X) { public static void Main() { var b = new B(); b = b with { Y = 2 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8858: The receiver type 'B' is not a valid record type. // b = b with { Y = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13), // (12,22): error CS0117: 'B' does not contain a definition for 'Y' // b = b with { Y = 2 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Y").WithArguments("B", "Y").WithLocation(12, 22) ); } [Fact] public void WithExpr24_Dynamic() { var src = @" record C(int X) { public static void Main() { dynamic c = new C(1); var x = c with { X = 2 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,17): error CS8858: The receiver type 'dynamic' is not a valid record type. // var x = c with { X = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("dynamic").WithLocation(7, 17) ); } [Fact, WorkItem(46427, "https://github.com/dotnet/roslyn/issues/46427"), WorkItem(46249, "https://github.com/dotnet/roslyn/issues/46249")] public void WithExpr25_TypeParameterWithRecordConstraint() { var src = @" record R(int X); class C { public static T M<T>(T t) where T : R { return t with { X = 2 }; } static void Main() { System.Console.Write(M(new R(-1)).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: "2").VerifyDiagnostics(); verifier.VerifyIL("C.M<T>(T)", @" { // Code size 29 (0x1d) .maxstack 3 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: callvirt ""R R.<Clone>$()"" IL_000b: unbox.any ""T"" IL_0010: dup IL_0011: box ""T"" IL_0016: ldc.i4.2 IL_0017: callvirt ""void R.X.init"" IL_001c: ret } "); } [Fact, WorkItem(46427, "https://github.com/dotnet/roslyn/issues/46427"), WorkItem(46249, "https://github.com/dotnet/roslyn/issues/46249")] public void WithExpr26_TypeParameterWithRecordAndInterfaceConstraint() { var src = @" record R { public int X { get; set; } } interface I { int Property { get; set; } } record T : R, I { public int Property { get; set; } } class C { public static T M<T>(T t) where T : R, I { return t with { X = 2, Property = 3 }; } static void Main() { System.Console.WriteLine(M(new T()).X); System.Console.WriteLine(M(new T()).Property); } }"; var verifier = CompileAndVerify( new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, verify: Verification.Passes, expectedOutput: @"2 3").VerifyDiagnostics(); verifier.VerifyIL("C.M<T>(T)", @" { // Code size 41 (0x29) .maxstack 3 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: callvirt ""R R.<Clone>$()"" IL_000b: unbox.any ""T"" IL_0010: dup IL_0011: box ""T"" IL_0016: ldc.i4.2 IL_0017: callvirt ""void R.X.set"" IL_001c: dup IL_001d: box ""T"" IL_0022: ldc.i4.3 IL_0023: callvirt ""void I.Property.set"" IL_0028: ret } "); } [Fact] public void WithExpr27_InExceptionFilter() { var src = @" var r = new R(1); try { throw new System.Exception(); } catch (System.Exception) when ((r = r with { X = 2 }).X == 2) { System.Console.Write(""RAN ""); System.Console.Write(r.X); } record R(int X); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN 2", verify: Verification.Skipped /* init-only */); } [Fact] public void WithExpr28_WithAwait() { var src = @" var r = new R(1); r = r with { X = await System.Threading.Tasks.Task.FromResult(42) }; System.Console.Write(r.X); record R(int X); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Last().Left; Assert.Equal("X", x.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal("System.Int32 R.X { get; init; }", symbol.ToTestDisplayString()); } [Fact, WorkItem(46465, "https://github.com/dotnet/roslyn/issues/46465")] public void WithExpr29_DisallowedAsExpressionStatement() { var src = @" record R(int X) { void M() { var r = new R(1); r with { X = 2 }; } } "; // Note: we didn't parse the `with` as a `with` expression, but as a broken local declaration // Tracked by https://github.com/dotnet/roslyn/issues/46465 var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (7,9): error CS0118: 'r' is a variable but is used like a type // r with { X = 2 }; Diagnostic(ErrorCode.ERR_BadSKknown, "r").WithArguments("r", "variable", "type").WithLocation(7, 9), // (7,11): warning CS0168: The variable 'with' is declared but never used // r with { X = 2 }; Diagnostic(ErrorCode.WRN_UnreferencedVar, "with").WithArguments("with").WithLocation(7, 11), // (7,16): error CS1002: ; expected // r with { X = 2 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(7, 16), // (7,18): error CS8852: Init-only property or indexer 'R.X' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // r with { X = 2 }; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "X").WithArguments("R.X").WithLocation(7, 18), // (7,24): error CS1002: ; expected // r with { X = 2 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 24) ); } [Fact] public void WithExpr30_TypeParameterNoConstraint() { var src = @" class C { public static void M<T>(T t) { _ = t with { X = 2 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (6,13): error CS8858: The receiver type 'T' is not a valid record type. // _ = t with { X = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(6, 13), // (6,22): error CS0117: 'T' does not contain a definition for 'X' // _ = t with { X = 2 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(6, 22) ); } [Fact] public void WithExpr31_TypeParameterWithInterfaceConstraint() { var src = @" interface I { int Property { get; set; } } class C { public static void M<T>(T t) where T : I { _ = t with { X = 2, Property = 3 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS8858: The receiver type 'T' is not a valid record type. // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(8, 13), // (8,22): error CS0117: 'T' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(8, 22) ); } [Fact] public void WithExpr32_TypeParameterWithInterfaceConstraint() { var ilSource = @" .class interface public auto ansi abstract I { // Methods .method public hidebysig specialname newslot abstract virtual instance class I '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { } // end of method I::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname newslot abstract virtual instance int32 get_Property () cil managed { } // end of method I::get_Property .method public hidebysig specialname newslot abstract virtual instance void set_Property ( int32 'value' ) cil managed { } // end of method I::set_Property // Properties .property instance int32 Property() { .get instance int32 I::get_Property() .set instance void I::set_Property(int32) } } // end of class I "; var src = @" class C { public static void M<T>(T t) where T : I { _ = t with { X = 2, Property = 3 }; } }"; var comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS8858: The receiver type 'T' is not a valid record type. // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(6, 13), // (6,22): error CS0117: 'T' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(6, 22) ); } [Fact] public void WithExpr33_TypeParameterWithStructureConstraint() { var ilSource = @" .class public sequential ansi sealed beforefieldinit S extends System.ValueType { .pack 0 .size 1 // Methods .method public hidebysig instance valuetype S '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { // Method begins at RVA 0x2150 // Code size 2 (0x2) .maxstack 1 .locals init ( [0] valuetype S ) IL_0000: ldnull IL_0001: throw } // end of method S::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname instance int32 get_Property () cil managed { // Method begins at RVA 0x215e // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method S::get_Property .method public hidebysig specialname instance void set_Property ( int32 'value' ) cil managed { // Method begins at RVA 0x215e // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method S::set_Property // Properties .property instance int32 Property() { .get instance int32 S::get_Property() .set instance void S::set_Property(int32) } } // end of class S "; var src = @" abstract class Base<T> { public abstract void M<U>(U t) where U : T; } class C : Base<S> { public override void M<U>(U t) { _ = t with { X = 2, Property = 3 }; } }"; var comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS8773: Feature 'with on structs' is not available in C# 9.0. Please use language version 10.0 or greater. // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "t with { X = 2, Property = 3 }").WithArguments("with on structs", "10.0").WithLocation(11, 13), // (11,22): error CS0117: 'U' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("U", "X").WithLocation(11, 22), // (11,29): error CS0117: 'U' does not contain a definition for 'Property' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("U", "Property").WithLocation(11, 29) ); comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (11,22): error CS0117: 'U' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("U", "X").WithLocation(11, 22), // (11,29): error CS0117: 'U' does not contain a definition for 'Property' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("U", "Property").WithLocation(11, 29) ); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void BothGetHashCodeAndEqualsAreDefined() { var src = @" public sealed record C { public object Data; public bool Equals(C c) { return false; } public override int GetHashCode() { return 0; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void BothGetHashCodeAndEqualsAreNotDefined() { var src = @" public sealed record C { public object Data; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void GetHashCodeIsDefinedButEqualsIsNot() { var src = @" public sealed record C { public object Data; public override int GetHashCode() { return 0; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void EqualsIsDefinedButGetHashCodeIsNot() { var src = @" public sealed record C { public object Data; public bool Equals(C c) { return false; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public bool Equals(C c) { return false; } Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(5, 17)); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord() { var src = @" class record { } class C { record M(record r) => r; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,7): error CS8860: Types and aliases should not be named 'record'. // class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7), // (6,24): error CS1514: { expected // record M(record r) => r; Diagnostic(ErrorCode.ERR_LbraceExpected, "=>").WithLocation(6, 24), // (6,24): error CS1513: } expected // record M(record r) => r; Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(6, 24), // (6,24): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration // record M(record r) => r; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(6, 24), // (6,28): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // record M(record r) => r; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(6, 28), // (6,28): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // record M(record r) => r; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(6, 28) ); comp = CreateCompilation(src, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Struct() { var src = @" struct record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,8): warning CS8860: Types and aliases should not be named 'record'. // struct record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 8) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Interface() { var src = @" interface record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,11): warning CS8860: Types and aliases should not be named 'record'. // interface record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 11) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Enum() { var src = @" enum record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,6): warning CS8860: Types and aliases should not be named 'record'. // enum record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 6) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Delegate() { var src = @" delegate void record(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): warning CS8860: Types and aliases should not be named 'record'. // delegate void record(); Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Delegate_Escaped() { var src = @" delegate void @record(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Alias() { var src = @" using record = System.Console; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using record = System.Console; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using record = System.Console;").WithLocation(2, 1), // (2,7): warning CS8860: Types and aliases should not be named 'record'. // using record = System.Console; Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Alias_Escaped() { var src = @" using @record = System.Console; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using @record = System.Console; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using @record = System.Console;").WithLocation(2, 1) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TypeParameter() { var src = @" class C<record> { } // 1 class C2 { class Nested<record> { } // 2 } class C3 { void Method<record>() { } // 3 void Method2() { void local<record>() // 4 { local<record>(); } } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,9): warning CS8860: Types and aliases should not be named 'record'. // class C<record> { } // 1 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 9), // (5,18): warning CS8860: Types and aliases should not be named 'record'. // class Nested<record> { } // 2 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(5, 18), // (9,17): warning CS8860: Types and aliases should not be named 'record'. // void Method<record>() { } // 3 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(9, 17), // (13,20): warning CS8860: Types and aliases should not be named 'record'. // void local<record>() // 4 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(13, 20) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TypeParameter_Escaped() { var src = @" class C<@record> { } class C2 { class Nested<@record> { } } class C3 { void Method<@record>() { } void Method2() { void local<@record>() { local<record>(); } } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TypeParameter_Escaped_Partial() { var src = @" partial class C<@record> { } partial class C<record> { } // 1 partial class D<record> { } // 2 partial class D<@record> { } partial class D<record> { } // 3 partial class D<record> { } // 4 partial class E<@record> { } partial class E<@record> { } partial class C2 { partial class Nested<record> { } // 5 partial class Nested<@record> { } } partial class C3 { partial void Method<@record>(); partial void Method<record>() { } // 6 partial void Method2<@record>() { } partial void Method2<record>(); // 7 partial void Method3<record>(); // 8 partial void Method3<@record>() { } partial void Method4<record>() { } // 9 partial void Method4<@record>(); } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,17): warning CS8860: Types and aliases should not be named 'record'. // partial class C<record> { } // 1 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 17), // (5,17): warning CS8860: Types and aliases should not be named 'record'. // partial class D<record> { } // 2 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(5, 17), // (8,17): warning CS8860: Types and aliases should not be named 'record'. // partial class D<record> { } // 3 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(8, 17), // (9,17): warning CS8860: Types and aliases should not be named 'record'. // partial class D<record> { } // 4 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(9, 17), // (16,26): warning CS8860: Types and aliases should not be named 'record'. // partial class Nested<record> { } // 5 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(16, 26), // (22,25): warning CS8860: Types and aliases should not be named 'record'. // partial void Method<record>() { } // 6 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(22, 25), // (25,26): warning CS8860: Types and aliases should not be named 'record'. // partial void Method2<record>(); // 7 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(25, 26), // (27,26): warning CS8860: Types and aliases should not be named 'record'. // partial void Method3<record>(); // 8 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(27, 26), // (30,26): warning CS8860: Types and aliases should not be named 'record'. // partial void Method4<record>() { } // 9 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(30, 26) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Record() { var src = @" record record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,8): warning CS8860: Types and aliases should not be named 'record'. // record record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 8) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TwoParts() { var src = @" partial class record { } partial class record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15), // (3,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Escaped() { var src = @" class @record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_MixedEscapedPartial() { var src = @" partial class @record { } partial class record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_MixedEscapedPartial_ReversedOrder() { var src = @" partial class record { } partial class @record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_BothEscapedPartial() { var src = @" partial class @record { } partial class @record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void TypeNamedRecord_EscapedReturnType() { var src = @" class record { } class C { @record M(record r) { System.Console.Write(""RAN""); return r; } public static void Main() { var c = new C(); _ = c.M(new record()); } }"; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (2,7): warning CS8860: Types and aliases should not be named 'record'. // class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7) ); CompileAndVerify(comp, expectedOutput: "RAN"); } [Fact, WorkItem(45591, "https://github.com/dotnet/roslyn/issues/45591")] public void Clone_DisallowedInSource() { var src = @" record C1(string Clone); // 1 record C2 { string Clone; // 2 } record C3 { string Clone { get; set; } // 3 } record C4 { data string Clone; // 4 not yet supported } record C5 { void Clone() { } // 5 void Clone(int i) { } // 6 } record C6 { class Clone { } // 7 } record C7 { delegate void Clone(); // 8 } record C8 { event System.Action Clone; // 9 } record Clone { Clone(int i) => throw null; } record C9 : System.ICloneable { object System.ICloneable.Clone() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,18): error CS8859: Members named 'Clone' are disallowed in records. // record C1(string Clone); // 1 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(2, 18), // (5,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone; // 2 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(5, 12), // (5,12): warning CS0169: The field 'C2.Clone' is never used // string Clone; // 2 Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C2.Clone").WithLocation(5, 12), // (9,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone { get; set; } // 3 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(9, 12), // (13,10): error CS1519: Invalid token 'string' in class, record, struct, or interface member declaration // data string Clone; // 4 not yet supported Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "string").WithArguments("string").WithLocation(13, 10), // (13,17): error CS8859: Members named 'Clone' are disallowed in records. // data string Clone; // 4 not yet supported Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(13, 17), // (13,17): warning CS0169: The field 'C4.Clone' is never used // data string Clone; // 4 not yet supported Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C4.Clone").WithLocation(13, 17), // (17,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone() { } // 5 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(17, 10), // (18,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone(int i) { } // 6 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(18, 10), // (22,11): error CS8859: Members named 'Clone' are disallowed in records. // class Clone { } // 7 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(22, 11), // (26,19): error CS8859: Members named 'Clone' are disallowed in records. // delegate void Clone(); // 8 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(26, 19), // (30,25): error CS8859: Members named 'Clone' are disallowed in records. // event System.Action Clone; // 9 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(30, 25), // (30,25): warning CS0067: The event 'C8.Clone' is never used // event System.Action Clone; // 9 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Clone").WithArguments("C8.Clone").WithLocation(30, 25) ); } [Fact] public void Clone_LoadedFromMetadata() { // IL for ' public record Base(int i);' with a 'void Clone()' method added var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object implements class [mscorlib]System.IEquatable`1<class Base> { .field private initonly int32 '<i>k__BackingField' .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname newslot virtual instance class Base '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldarg.0 IL_0001: newobj instance void Base::.ctor(class Base) IL_0006: ret } .method family hidebysig specialname newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldtoken Base IL_0005: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_000a: ret } .method public hidebysig specialname rtspecialname instance void .ctor ( int32 i ) cil managed { IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld int32 Base::'<i>k__BackingField' IL_0007: ldarg.0 IL_0008: call instance void [mscorlib]System.Object::.ctor() IL_000d: ret } .method public hidebysig specialname instance int32 get_i () cil managed { IL_0000: ldarg.0 IL_0001: ldfld int32 Base::'<i>k__BackingField' IL_0006: ret } .method public hidebysig specialname instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_i ( int32 'value' ) cil managed { IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld int32 Base::'<i>k__BackingField' IL_0007: ret } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<class [mscorlib]System.Type>::get_Default() IL_0005: ldarg.0 IL_0006: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract() IL_000b: callvirt instance int32 class [mscorlib]System.Collections.Generic.EqualityComparer`1<class [mscorlib]System.Type>::GetHashCode(!0) IL_0010: ldc.i4 -1521134295 IL_0015: mul IL_0016: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::get_Default() IL_001b: ldarg.0 IL_001c: ldfld int32 Base::'<i>k__BackingField' IL_0021: callvirt instance int32 class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::GetHashCode(!0) IL_0026: add IL_0027: ret } .method public hidebysig virtual instance bool Equals ( object obj ) cil managed { IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst Base IL_0007: callvirt instance bool Base::Equals(class Base) IL_000c: ret } .method public newslot virtual instance bool Equals ( class Base '' ) cil managed { IL_0000: ldarg.1 IL_0001: brfalse.s IL_002d IL_0003: ldarg.0 IL_0004: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract() IL_0009: ldarg.1 IL_000a: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract() IL_000f: call bool [mscorlib]System.Type::op_Equality(class [mscorlib]System.Type, class [mscorlib]System.Type) IL_0014: brfalse.s IL_002d IL_0016: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::get_Default() IL_001b: ldarg.0 IL_001c: ldfld int32 Base::'<i>k__BackingField' IL_0021: ldarg.1 IL_0022: ldfld int32 Base::'<i>k__BackingField' IL_0027: callvirt instance bool class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::Equals(!0, !0) IL_002c: ret IL_002d: ldc.i4.0 IL_002e: ret } .method family hidebysig specialname rtspecialname instance void .ctor ( class Base '' ) cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld int32 Base::'<i>k__BackingField' IL_000d: stfld int32 Base::'<i>k__BackingField' IL_0012: ret } .method public hidebysig instance void Deconstruct ( [out] int32& i ) cil managed { IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call instance int32 Base::get_i() IL_0007: stind.i4 IL_0008: ret } .method public hidebysig instance void Clone () cil managed { IL_0000: ldstr ""RAN"" IL_0005: call void [mscorlib]System.Console::Write(string) IL_000a: ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type Base::get_EqualityContract() } .property instance int32 i() { .get instance int32 Base::get_i() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) Base::set_i(int32) } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi abstract sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends [mscorlib]System.Object { } "; var src = @" record R(int i) : Base(i); public class C { public static void Main() { var r = new R(1); r.Clone(); } } "; var comp = CreateCompilationWithIL(src, il, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics(); // Note: we do load the Clone method from metadata } [Fact] public void Clone_01() { var src = @" abstract sealed record C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static // abstract sealed record C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24) ); var clone = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1"); Assert.True(namedTypeSymbol.IsRecord); Assert.Equal("record C1", namedTypeSymbol .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_02() { var src = @" sealed abstract record C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static // sealed abstract record C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24) ); var clone = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1"); Assert.True(namedTypeSymbol.IsRecord); Assert.Equal("record C1", namedTypeSymbol .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_03() { var src = @" record C1; abstract sealed record C2 : C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static // abstract sealed record C2 : C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24) ); var clone = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); } [Fact] public void Clone_04() { var src = @" record C1; sealed abstract record C2 : C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static // sealed abstract record C2 : C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24) ); var clone = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1"); Assert.True(namedTypeSymbol.IsRecord); Assert.Equal("record C1", namedTypeSymbol .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_05_IntReturnType_UsedAsBaseType() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_06_IntReturnType_UsedInWith() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A "; var source = @" public class Program { static void Main() { A x = new A() with { }; } } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS8858: The receiver type 'A' is not a valid record type. // A x = new A() with { }; Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_07_Ambiguous_UsedAsBaseType() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_08_Ambiguous_UsedInWith() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A "; var source = @" public class Program { static void Main() { A x = new A() with { }; } } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS8858: The receiver type 'A' is not a valid record type. // A x = new A() with { }; Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_09_AmbiguousReverseOrder_UsedAsBaseType() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_10_AmbiguousReverseOrder_UsedInWith() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A "; var source = @" public class Program { static void Main() { A x = new A() with { }; } } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS8858: The receiver type 'A' is not a valid record type. // A x = new A() with { }; Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_11() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(source1).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" class Program { public static void Main() { var c1 = new B(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; CompileAndVerify(source3, references: new[] { comp1Ref, comp2Ref }, expectedOutput: @"1 11").VerifyDiagnostics(); } [Fact] public void Clone_12() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, assemblyName: "Clone_12", parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" class Program { public static void Main() { var c1 = new B(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; var comp3 = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp2Ref }, parseOptions: TestOptions.Regular9); comp3.VerifyEmitDiagnostics( // (7,18): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_12, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("A", "Clone_12, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18) ); } [Fact] public void Clone_13() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, assemblyName: "Clone_13", references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" public record C(int X) : B(X); "; var comp3Ref = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp2Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source4 = @" class Program { public static void Main() { var c1 = new C(1); var c2 = c1 with { X = 11 }; } } "; var comp4 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp3Ref }, parseOptions: TestOptions.Regular9); comp4.VerifyEmitDiagnostics( // (7,18): error CS8858: The receiver type 'C' is not a valid record type. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_CannotClone, "c1").WithArguments("C").WithLocation(7, 18), // (7,18): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18), // (7,28): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "X").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 28), // (7,28): error CS0117: 'C' does not contain a definition for 'X' // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("C", "X").WithLocation(7, 28) ); var comp5 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp3Ref }, parseOptions: TestOptions.Regular9); comp5.VerifyEmitDiagnostics( // (7,18): error CS8858: The receiver type 'C' is not a valid record type. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_CannotClone, "c1").WithArguments("C").WithLocation(7, 18), // (7,18): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18), // (7,28): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "X").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 28), // (7,28): error CS0117: 'C' does not contain a definition for 'X' // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("C", "X").WithLocation(7, 28) ); } [Fact] public void Clone_14() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(source1).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" record C(int X) : B(X) { public static void Main() { var c1 = new C(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; CompileAndVerify(source3, references: new[] { comp1Ref, comp2Ref }, expectedOutput: @"1 11").VerifyDiagnostics(); } [Fact] public void Clone_15() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, assemblyName: "Clone_15", parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" record C(int X) : B(X) { public static void Main() { var c1 = new C(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; var comp3 = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp2Ref }, parseOptions: TestOptions.Regular9); comp3.VerifyEmitDiagnostics( // (2,8): error CS8869: 'C.Equals(object?)' does not override expected method from 'object'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.Equals(object?)").WithLocation(2, 8), // (2,8): error CS8869: 'C.GetHashCode()' does not override expected method from 'object'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.GetHashCode()").WithLocation(2, 8), // (2,8): error CS8869: 'C.ToString()' does not override expected method from 'object'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.ToString()").WithLocation(2, 8), // (2,8): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 8), // (2,19): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (2,19): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (6,22): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c1 = new C(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22), // (7,18): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18), // (8,9): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine(c1.X); Diagnostic(ErrorCode.ERR_NoTypeDef, "System").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 9), // (9,9): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine(c2.X); Diagnostic(ErrorCode.ERR_NoTypeDef, "System").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 9) ); } [Fact] public void Clone_16() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, assemblyName: "Clone_16", references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" public record C(int X) : B(X); "; var comp3Ref = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp2Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source4 = @" record D(int X) : C(X) { public static void Main() { var c1 = new D(1); var c2 = c1 with { X = 11 }; } } "; var comp4 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp3Ref }, parseOptions: TestOptions.Regular9); comp4.VerifyEmitDiagnostics( // (2,8): error CS8869: 'D.Equals(object?)' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.Equals(object?)").WithLocation(2, 8), // (2,8): error CS8869: 'D.GetHashCode()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.GetHashCode()").WithLocation(2, 8), // (2,8): error CS8869: 'D.ToString()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.ToString()").WithLocation(2, 8), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (2,19): error CS8864: Records may only inherit from object or another record // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_BadRecordBase, "C").WithLocation(2, 19), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (6,22): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c1 = new D(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22) ); var comp5 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp3Ref }, parseOptions: TestOptions.Regular9); comp5.VerifyEmitDiagnostics( // (2,8): error CS8869: 'D.Equals(object?)' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.Equals(object?)").WithLocation(2, 8), // (2,8): error CS8869: 'D.GetHashCode()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.GetHashCode()").WithLocation(2, 8), // (2,8): error CS8869: 'D.ToString()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.ToString()").WithLocation(2, 8), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (2,19): error CS8864: Records may only inherit from object or another record // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_BadRecordBase, "C").WithLocation(2, 19), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (6,22): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c1 = new D(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22) ); } [Fact] public void Clone_17_NonOverridable() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_18_NonOverridable() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual final instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_19() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A .class public auto ansi beforefieldinit B extends A { // Methods .method public hidebysig specialname virtual final instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class B "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0239: 'C.<Clone>$()': cannot override inherited member 'B.<Clone>$()' because it is sealed // public record C : B { Diagnostic(ErrorCode.ERR_CantOverrideSealed, "C").WithArguments("C.<Clone>$()", "B.<Clone>$()").WithLocation(2, 15) ); } [Fact, WorkItem(47093, "https://github.com/dotnet/roslyn/issues/47093")] public void ToString_TopLevelRecord_Empty() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1; "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.True(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: callvirt ""bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_AbstractRecord() { var src = @" var c2 = new C2(); System.Console.Write(c2); abstract record C1; record C2 : C1 { public override string ToString() => base.ToString(); } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.True(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: callvirt ""bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_DerivedRecord_AbstractRecord() { var src = @" var c2 = new C2(); System.Console.Write(c2); record Base; abstract record C1 : Base; record C2 : C1 { public override string ToString() => base.ToString(); } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.True(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool Base.PrintMembers(System.Text.StringBuilder)"" IL_0007: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: callvirt ""bool Base.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilder() { var src = @" record C1; "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Text_StringBuilder); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "record C1;").WithArguments("System.Text.StringBuilder").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1), // (2,8): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C1").WithArguments("System.Text.StringBuilder").WithLocation(2, 8) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderCtor() { var src = @" record C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__ctor); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderAppendString() { var src = @" record C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendString() { var src = @" record C1(int P); "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendStringAndChar() { var src = @" record C1(int P); "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendChar); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_Empty_Sealed() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); sealed record C1; "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); } [Fact] public void ToString_AbstractRecord() { var src = @" var c2 = new C2(42, 43); System.Console.Write(c2.ToString()); abstract record C1(int I1); sealed record C2(int I1, int I2) : C1(I1); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2 { I1 = 42, I2 = 43 }", verify: Verification.Skipped /* init-only */); } [Fact, WorkItem(47672, "https://github.com/dotnet/roslyn/issues/47672")] public void ToString_RecordWithIndexer() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); record C1(int I1) { private int field = 44; public int this[int i] => 0; public int PropertyWithoutGetter { set { } } public int P2 { get => 43; } public ref int P3 { get => ref field; } public event System.Action a; private int field1 = 100; internal int field2 = 100; protected int field3 = 100; private protected int field4 = 100; internal protected int field5 = 100; private int Property1 { get; set; } = 100; internal int Property2 { get; set; } = 100; protected int Property3 { get; set; } = 100; private protected int Property4 { get; set; } = 100; internal protected int Property5 { get; set; } = 100; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "C1 { I1 = 42, P2 = 43, P3 = 44 }", verify: Verification.Skipped /* init-only */); comp.VerifyEmitDiagnostics( // (12,32): warning CS0067: The event 'C1.a' is never used // public event System.Action a; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "a", isSuppressed: false).WithArguments("C1.a").WithLocation(12, 32), // (14,17): warning CS0414: The field 'C1.field1' is assigned but its value is never used // private int field1 = 100; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field1", isSuppressed: false).WithArguments("C1.field1").WithLocation(14, 17) ); } [Fact, WorkItem(47672, "https://github.com/dotnet/roslyn/issues/47672")] public void ToString_PrivateGetter() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1 { public int P1 { private get => 43; set => throw null; } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "C1 { P1 = 43 }"); comp.VerifyEmitDiagnostics(); } [Fact, WorkItem(47797, "https://github.com/dotnet/roslyn/issues/47797")] public void ToString_OverriddenVirtualProperty_NoRepetition() { var src = @" System.Console.WriteLine(new B() { P = 2 }.ToString()); abstract record A { public virtual int P { get; set; } } record B : A { public override int P { get; set; } } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "B { P = 2 }"); } [Fact, WorkItem(47797, "https://github.com/dotnet/roslyn/issues/47797")] public void ToString_OverriddenAbstractProperty_NoRepetition() { var src = @" System.Console.Write(new B1() { P = 1 }); System.Console.Write("" ""); System.Console.Write(new B2(2)); abstract record A1 { public abstract int P { get; set; } } record B1 : A1 { public override int P { get; set; } } abstract record A2(int P); record B2(int P) : A2(P); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "B1 { P = 1 } B2 { P = 2 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_ErrorBase() { var src = @" record C2: Error; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0115: 'C2.ToString()': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'C2.EqualityContract': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'C2.Equals(object?)': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'C2.GetHashCode()': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'C2.PrintMembers(StringBuilder)': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,12): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // record C2: Error; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(2, 12) ); } [Fact, WorkItem(49263, "https://github.com/dotnet/roslyn/issues/49263")] public void ToString_SelfReferentialBase() { var src = @" record R : R; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0146: Circular base type dependency involving 'R' and 'R' // record R : R; Diagnostic(ErrorCode.ERR_CircularBase, "R").WithArguments("R", "R").WithLocation(2, 8), // (2,8): error CS0115: 'R.ToString()': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'R.EqualityContract': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'R.Equals(object?)': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'R.GetHashCode()': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'R.PrintMembers(StringBuilder)': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8) ); } [Fact] public void ToString_TopLevelRecord_Empty_AbstractSealed() { var src = @" abstract sealed record C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static // abstract sealed record C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24) ); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_ValueType() { var src = @" var c1 = new C1() { field = 42 }; System.Console.Write(c1.ToString()); record C1 { public int field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.True(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldflda ""int C1.field"" IL_0018: constrained. ""int"" IL_001e: callvirt ""string object.ToString()"" IL_0023: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0028: pop IL_0029: ldc.i4.1 IL_002a: ret } "); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_ConstrainedValueType() { var src = @" var c1 = new C1<int>() { field = 42 }; System.Console.Write(c1.ToString()); record C1<T> where T : struct { public T field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldflda ""T C1<T>.field"" IL_0018: constrained. ""T"" IL_001e: callvirt ""string object.ToString()"" IL_0023: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0028: pop IL_0029: ldc.i4.1 IL_002a: ret } "); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_ReferenceType() { var src = @" var c1 = new C1() { field = ""hello"" }; System.Console.Write(c1.ToString()); record C1 { public string field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 32 (0x20) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldfld ""string C1.field"" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_001d: pop IL_001e: ldc.i4.1 IL_001f: ret } "); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_Unconstrained() { var src = @" var c1 = new C1<string>() { field = ""hello"" }; System.Console.Write(c1.ToString()); System.Console.Write("" ""); var c2 = new C1<int>() { field = 42 }; System.Console.Write(c2.ToString()); record C1<T> { public T field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello } C1 { field = 42 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 37 (0x25) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldfld ""T C1<T>.field"" IL_0018: box ""T"" IL_001d: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0022: pop IL_0023: ldc.i4.1 IL_0024: ret } "); } [Fact] public void ToString_TopLevelRecord_OneField_ErrorType() { var src = @" record C1 { public Error field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,12): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // public Error field; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 12), // (4,18): warning CS0649: Field 'C1.field' is never assigned to, and will always have its default value null // public Error field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C1.field", "null").WithLocation(4, 18) ); } [Fact] public void ToString_TopLevelRecord_TwoFields_ReferenceType() { var src = @" var c1 = new C1() { field1 = ""hi"", field2 = null }; System.Console.Write(c1.ToString()); record C1 { public string field1; public string field2; private string field3; internal string field4; protected string field5; protected internal string field6; private protected string field7; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (10,20): warning CS0169: The field 'C1.field3' is never used // private string field3; Diagnostic(ErrorCode.WRN_UnreferencedField, "field3").WithArguments("C1.field3").WithLocation(10, 20), // (11,21): warning CS0649: Field 'C1.field4' is never assigned to, and will always have its default value null // internal string field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field4").WithArguments("C1.field4", "null").WithLocation(11, 21), // (12,22): warning CS0649: Field 'C1.field5' is never assigned to, and will always have its default value null // protected string field5; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field5").WithArguments("C1.field5", "null").WithLocation(12, 22), // (13,31): warning CS0649: Field 'C1.field6' is never assigned to, and will always have its default value null // protected internal string field6; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field6").WithArguments("C1.field6", "null").WithLocation(13, 31), // (14,30): warning CS0649: Field 'C1.field7' is never assigned to, and will always have its default value null // private protected string field7; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field7").WithArguments("C1.field7", "null").WithLocation(14, 30) ); var v = CompileAndVerify(comp, expectedOutput: "C1 { field1 = hi, field2 = }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 57 (0x39) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field1 = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldfld ""string C1.field1"" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_001d: pop IL_001e: ldarg.1 IL_001f: ldstr "", field2 = "" IL_0024: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0029: pop IL_002a: ldarg.1 IL_002b: ldarg.0 IL_002c: ldfld ""string C1.field2"" IL_0031: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0036: pop IL_0037: ldc.i4.1 IL_0038: ret } "); } [Fact] public void ToString_TopLevelRecord_OneProperty() { var src = @" var c1 = new C1(Property: 42); System.Console.Write(c1.ToString()); record C1(int Property) { private int Property2; internal int Property3; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,17): warning CS0169: The field 'C1.Property2' is never used // private int Property2; Diagnostic(ErrorCode.WRN_UnreferencedField, "Property2").WithArguments("C1.Property2").WithLocation(7, 17), // (8,18): warning CS0649: Field 'C1.Property3' is never assigned to, and will always have its default value 0 // internal int Property3; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Property3").WithArguments("C1.Property3", "0").WithLocation(8, 18) ); var v = CompileAndVerify(comp, expectedOutput: "C1 { Property = 42 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 46 (0x2e) .maxstack 2 .locals init (int V_0) IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""Property = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: call ""int C1.Property.get"" IL_0018: stloc.0 IL_0019: ldloca.s V_0 IL_001b: constrained. ""int"" IL_0021: callvirt ""string object.ToString()"" IL_0026: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_002b: pop IL_002c: ldc.i4.1 IL_002d: ret }"); } [Fact] public void ToString_TopLevelRecord_TwoFieldsAndTwoProperties() { var src = @" var c1 = new C1<int, string>(42, null) { field1 = 43, field2 = ""hi"" }; System.Console.Write(c1.ToString()); record C1<T1, T2>(T1 Property1, T2 Property2) { public T1 field1; public T2 field2; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { Property1 = 42, Property2 = , field1 = 43, field2 = hi }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties() { var src = @" var c1 = new C1(42, 43) { A2 = 100, B2 = 101 }; System.Console.Write(c1.ToString()); record Base(int A1) { public int A2; } record C1(int A1, int B1) : Base(A1) { public int B2; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { A1 = 42, A2 = 100, B1 = 43, B2 = 101 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 98 (0x62) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool Base.PrintMembers(System.Text.StringBuilder)"" IL_0007: brfalse.s IL_0015 IL_0009: ldarg.1 IL_000a: ldstr "", "" IL_000f: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0014: pop IL_0015: ldarg.1 IL_0016: ldstr ""B1 = "" IL_001b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0020: pop IL_0021: ldarg.1 IL_0022: ldarg.0 IL_0023: call ""int C1.B1.get"" IL_0028: stloc.0 IL_0029: ldloca.s V_0 IL_002b: constrained. ""int"" IL_0031: callvirt ""string object.ToString()"" IL_0036: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_003b: pop IL_003c: ldarg.1 IL_003d: ldstr "", B2 = "" IL_0042: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0047: pop IL_0048: ldarg.1 IL_0049: ldarg.0 IL_004a: ldflda ""int C1.B2"" IL_004f: constrained. ""int"" IL_0055: callvirt ""string object.ToString()"" IL_005a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_005f: pop IL_0060: ldc.i4.1 IL_0061: ret } "); } [Fact] public void ToString_DerivedRecord_AbstractSealed() { var src = @" record C1; abstract sealed record C2 : C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static // abstract sealed record C2 : C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24) ); var print = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.True(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); } [Theory] [InlineData(false)] [InlineData(true)] public void ToString_DerivedRecord_BaseHasSealedToString(bool usePreview) { var src = @" var c = new C2(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1; "; var comp = CreateCompilation(src, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9, options: TestOptions.DebugExe); if (usePreview) { comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); } else { comp.VerifyEmitDiagnostics( // (7,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater. // public sealed override string ToString() => "C1"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(7, 35) ); } } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1; record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseTriesToOverride() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public override string ToString() => ""C2""; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (11,28): error CS0239: 'C2.ToString()': cannot override inherited member 'C1.ToString()' because it is sealed // public override string ToString() => "C2"; Diagnostic(ErrorCode.ERR_CantOverrideSealed, "ToString").WithArguments("C2.ToString()", "C1.ToString()").WithLocation(11, 28) ); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseShadowsToStringPrivate() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { private new string ToString() => ""C2""; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseShadowsToStringNonSealed() { var src = @" C3 c3 = new C3(); System.Console.Write(c3.ToString()); C1 c1 = c3; System.Console.Write(c1.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public new virtual string ToString() => ""C2""; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseHasToStringWithDifferentSignature() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public string ToString(int n) => throw null; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseHasToStringWithDifferentReturnType() { var src = @" C1 c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public new int ToString() => throw null; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_ReverseOrder() { var src = @" var c1 = new C1(42, 43) { A1 = 100, B1 = 101 }; System.Console.Write(c1.ToString()); record Base(int A2) { public int A1; } record C1(int A2, int B2) : Base(A2) { public int B1; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { A2 = 42, A1 = 100, B2 = 43, B1 = 101 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_Partial() { var src1 = @" var c1 = new C1() { A1 = 100, B1 = 101 }; System.Console.Write(c1.ToString()); partial record C1 { public int A1; } "; var src2 = @" partial record C1 { public int B1; } "; var comp = CreateCompilation(new[] { src1, src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { A1 = 100, B1 = 101 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_Partial_ReverseOrder() { var src1 = @" var c1 = new C1() { A1 = 100, B1 = 101 }; System.Console.Write(c1.ToString()); partial record C1 { public int B1; } "; var src2 = @" partial record C1 { public int A1; } "; var comp = CreateCompilation(new[] { src1, src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { B1 = 101, A1 = 100 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_BadBase_MissingToString() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldstr ""RAN"" IL_0005: ret } } .class public auto ansi beforefieldinit B extends A { .method family hidebysig specialname virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Inequality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Equality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object obj ) cil managed { IL_0000: ldnull IL_0001: throw } .method public final hidebysig virtual instance bool Equals ( class A other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance bool Equals ( class B other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class B original ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void A::.ctor() IL_0006: ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } // no override for ToString } "; var source = @" var c = new C(); System.Console.Write(c); public record C : B { public override string ToString() => base.ToString(); } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); } [Fact] public void ToString_BadBase_PrintMembersSealed() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method final family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.PrintMembers(StringBuilder)': cannot override inherited member 'A.PrintMembers(StringBuilder)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)", "A.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersInaccessible() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method private hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // public record B : A { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersReturnsInt() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance int32 '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.PrintMembers(StringBuilder)': return type must be 'int' to match overridden member 'A.PrintMembers(StringBuilder)' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)", "A.PrintMembers(System.Text.StringBuilder)", "int").WithLocation(2, 15) ); } [Fact] public void EqualityContract_BadBase_ReturnsInt() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance int32 get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 EqualityContract() { .get instance int32 A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS1715: 'B.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "B").WithArguments("B.EqualityContract", "A.EqualityContract", "int").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersIsAmbiguous() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance int32 '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_BadBase_MissingPrintMembers() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // public record B : A { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_DuplicatePrintMembers() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder modopt(int64) builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_BadBase_PrintMembersNotOverriddenInBase() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi beforefieldinit B extends A { .method family hidebysig specialname virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Inequality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Equality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object obj ) cil managed { IL_0000: ldnull IL_0001: throw } .method public final hidebysig virtual instance bool Equals ( class A other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance bool Equals ( class B other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class B original ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } // no override for PrintMembers } "; var source = @" public record C : B { protected override bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,29): error CS8871: 'C.PrintMembers(StringBuilder)' does not override expected method from 'B'. // protected override bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(4, 29) ); var source2 = @" public record C : B; "; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8871: 'C.PrintMembers(StringBuilder)' does not override expected method from 'B'. // public record C : B; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersWithModOpt() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder modopt(int64) builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); var print = comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal("System.Boolean B.PrintMembers(System.Text.StringBuilder modopt(System.Int64) builder)", print.ToTestDisplayString()); Assert.Equal("System.Boolean A.PrintMembers(System.Text.StringBuilder modopt(System.Int64) builder)", print.OverriddenMethod.ToTestDisplayString()); } [Fact] public void ToString_BadBase_NewToString() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.ToString()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.ToString()").WithLocation(2, 15) ); } [Fact] public void ToString_NewToString_SealedBaseToString() { var source = @" B b = new B(); System.Console.Write(b.ToString()); A a = b; System.Console.Write(a.ToString()); public record A { public sealed override string ToString() => ""A""; } public record B : A { public new string ToString() => ""B""; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "BA"); } [Theory] [InlineData(false)] [InlineData(true)] public void ToString_BadBase_SealedToString(bool usePreview) { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public final hidebysig virtual instance string ToString () cil managed { IL_0000: ldstr ""A"" IL_0001: ret } } "; var source = @" var b = new B(); System.Console.Write(b.ToString()); public record B : A { }"; var comp = CreateCompilationWithIL( new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9); if (usePreview) { comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "A"); } else { comp.VerifyEmitDiagnostics( // (5,15): error CS8912: Inheriting from a record with a sealed 'Object.ToString' is not supported in C# 9.0. Please use language version '10.0' or greater. // public record B : A { Diagnostic(ErrorCode.ERR_InheritingFromRecordWithSealedToString, "B").WithArguments("9.0", "10.0").WithLocation(5, 15) ); } } [Fact] public void ToString_TopLevelRecord_UserDefinedToString() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1 { public override string ToString() => ""RAN""; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal("System.Boolean C1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", print.ToTestDisplayString()); } [Theory] [InlineData(false)] [InlineData(true)] public void ToString_TopLevelRecord_UserDefinedToString_Sealed(bool usePreview) { var src = @" record C1 { public sealed override string ToString() => throw null; } "; var comp = CreateCompilation(src, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9); if (usePreview) { comp.VerifyEmitDiagnostics(); } else { comp.VerifyEmitDiagnostics( // (4,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater. // public sealed override string ToString() => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(4, 35) ); } } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_Sealed_InSealedRecord() { var src = @" sealed record C1 { public sealed override string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_WithNullableStringBuilder() { var src = @" #nullable enable record C1 { protected virtual bool PrintMembers(System.Text.StringBuilder? builder) => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_ErrorReturnType() { var src = @" record C1 { protected virtual Error PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,23): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // protected virtual Error PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 23) ); } [Fact] public void ToString_UserDefinedPrintMembers_WrongReturnType() { var src = @" record C1 { protected virtual int PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,27): error CS8874: Record member 'C1.PrintMembers(StringBuilder)' must return 'bool'. // protected virtual int PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "bool").WithLocation(4, 27) ); } [Fact] public void ToString_UserDefinedPrintMembers_Sealed() { var src = @" record C1(int I1); record C2(int I1, int I2) : C1(I1) { protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,36): error CS8872: 'C2.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed. // protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 36) ); } [Fact] public void ToString_UserDefinedPrintMembers_NonVirtual() { var src = @" record C1 { protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,20): error CS8872: 'C1.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed. // protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20) ); } [Fact] public void ToString_UserDefinedPrintMembers_SealedInSealedRecord() { var src = @" record C1(int I1); sealed record C2(int I1, int I2) : C1(I1) { protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_Static() { var src = @" sealed record C { private static bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,25): error CS8877: Record member 'C.PrintMembers(StringBuilder)' may not be static. // private static bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "PrintMembers").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25) ); } [Fact] public void ToString_UserDefinedPrintMembers() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1 { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { builder.Append(""RAN""); return true; } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { RAN }"); } [Fact] public void ToString_UserDefinedPrintMembers_WrongAccessibility() { var src = @" record C1 { public virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,25): error CS8875: Record member 'C1.PrintMembers(StringBuilder)' must be protected. // public virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25) ); } [Fact] public void ToString_UserDefinedPrintMembers_WrongAccessibility_SealedRecord() { var src = @" sealed record C1 { protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,20): warning CS0628: 'C1.PrintMembers(StringBuilder)': new protected member declared in sealed type // protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20), // (4,20): error CS8879: Record member 'C1.PrintMembers(StringBuilder)' must be private. // protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20) ); } [Fact] public void ToString_UserDefinedPrintMembers_DerivedRecord_WrongAccessibility() { var src = @" record B; record C1 : B { public bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,17): error CS8875: Record member 'C1.PrintMembers(StringBuilder)' must be protected. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17), // (5,17): error CS8860: 'C1.PrintMembers(StringBuilder)' does not override expected method from 'B'. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(5, 17), // (5,17): error CS8872: 'C1.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17), // (5,17): warning CS0114: 'C1.PrintMembers(StringBuilder)' hides inherited member 'B.PrintMembers(StringBuilder)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17) ); } [Fact] public void ToString_UserDefinedPrintMembers_New() { var src = @" record B; record C1 : B { protected new virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,32): error CS8860: 'C1.PrintMembers(StringBuilder)' does not override expected method from 'B'. // protected new virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(5, 32) ); } [Fact] public void ToString_TopLevelRecord_EscapedNamed() { var src = @" var c1 = new @base(); System.Console.Write(c1.ToString()); record @base; "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "base { }"); } [Fact] public void ToString_DerivedDerivedRecord() { var src = @" var r1 = new R1(1); System.Console.Write(r1.ToString()); System.Console.Write("" ""); var r2 = new R2(10, 11); System.Console.Write(r2.ToString()); System.Console.Write("" ""); var r3 = new R3(20, 21, 22); System.Console.Write(r3.ToString()); record R1(int I1); record R2(int I1, int I2) : R1(I1); record R3(int I1, int I2, int I3) : R2(I1, I2); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "R1 { I1 = 1 } R2 { I1 = 10, I2 = 11 } R3 { I1 = 20, I2 = 21, I3 = 22 }", verify: Verification.Skipped /* init-only */); } [Fact] public void WithExpr24() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(ref C other) : this(-1) { } protected C(C other) { X = other.X; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); var clone = verifier.Compilation.GetMember("C." + WellKnownMemberNames.CloneMethodName); Assert.Equal("<Clone>$", clone.Name); } [Fact] public void WithExpr25() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(in C other) : this(-1) { } protected C(C other) { X = other.X; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr26() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(out C other) : this(-1) { other = null; } protected C(C other) { X = other.X; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr27() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(ref C other) : this(-1) { } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr28() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(in C other) : this(-1) { } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr29() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(out C other) : this(-1) { other = null; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void AccessibilityOfBaseCtor_01() { var src = @" using System; record Base { protected Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} public static void Main() { var c = new C(1, 2); } } record C(int X, int Y) : Base(X, Y); "; CompileAndVerify(src, expectedOutput: @" 1 2 ").VerifyDiagnostics(); } [Fact] public void AccessibilityOfBaseCtor_02() { var src = @" using System; record Base { protected Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} public static void Main() { var c = new C(1, 2); } } record C(int X, int Y) : Base(X, Y) {} "; CompileAndVerify(src, expectedOutput: @" 1 2 ").VerifyDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_03() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B(object P) : A; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_04() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B(object P) : A {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_05() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B : A; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_06() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B : A {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExprNestedErrors() { var src = @" class C { public int X { get; init; } public static void Main() { var c = new C(); c = c with { X = """"-3 }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone". // c = c with { X = ""-3 }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(8, 13), // (8,26): error CS0019: Operator '-' cannot be applied to operands of type 'string' and 'int' // c = c with { X = ""-3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, @"""""-3").WithArguments("-", "string", "int").WithLocation(8, 26) ); } [Fact] public void WithExprNoExpressionToPropertyTypeConversion() { var src = @" record C(int X) { public static void Main() { var c = new C(0); c = c with { X = """" }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int' // c = c with { X = "" }; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(8, 26) ); } [Fact] public void WithExprPropertyInaccessibleSet() { var src = @" record C { public int X { get; private set; } } class D { public static void Main() { var c = new C(); c = c with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,22): error CS0272: The property or indexer 'C.X' cannot be used in this context because the set accessor is inaccessible // c = c with { X = 0 }; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "X").WithArguments("C.X").WithLocation(11, 22) ); } [Fact] public void WithExprSideEffects1() { var src = @" using System; record C(int X, int Y, int Z) { public static void Main() { var c = new C(0, 1, 2); c = c with { Y = W(""Y""), X = W(""X"") }; } public static int W(string s) { Console.WriteLine(s); return 0; } } "; var verifier = CompileAndVerify(src, expectedOutput: @" Y X").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 47 (0x2f) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""C..ctor(int, int, int)"" IL_0008: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_000d: dup IL_000e: ldstr ""Y"" IL_0013: call ""int C.W(string)"" IL_0018: callvirt ""void C.Y.init"" IL_001d: dup IL_001e: ldstr ""X"" IL_0023: call ""int C.W(string)"" IL_0028: callvirt ""void C.X.init"" IL_002d: pop IL_002e: ret }"); var comp = (CSharpCompilation)verifier.Compilation; var tree = comp.SyntaxTrees.First(); var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); var withExpr1 = root.DescendantNodes().OfType<WithExpressionSyntax>().First(); comp.VerifyOperationTree(withExpr1, @" IWithOperation (OperationKind.With, Type: C) (Syntax: 'c with { Y ... = W(""X"") }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ Y = W(""Y"" ... = W(""X"") }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'Y = W(""Y"")') Left: IPropertyReferenceOperation: System.Int32 C.Y { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Y') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""Y"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""Y""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Y"") (Syntax: '""Y""') 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) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = W(""X"")') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""X"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""X""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""X"") (Syntax: '""X""') 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) "); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0, 1, 2)') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0, 1, 2)') Right: IObjectCreationOperation (Constructor: C..ctor(System.Int32 X, System.Int32 Y, System.Int32 Z)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0, 1, 2)') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Z) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') 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) Initializer: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] [1] Block[B2] - Block Predecessors: [B1] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Value: IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'Y = W(""Y"")') Left: IPropertyReferenceOperation: System.Int32 C.Y { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Y') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""Y"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""Y""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Y"") (Syntax: '""Y""') 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) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = W(""X"")') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""X"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""X""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""X"") (Syntax: '""X""') 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) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with ... = W(""X"") };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with ... = W(""X"") }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Next (Regular) Block[B3] Leaving: {R2} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void WithExprConversions1() { var src = @" using System; record C(long X) { public static void Main() { var c = new C(0); Console.WriteLine((c with { X = 11 }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: "11").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 32 (0x20) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: conv.i8 IL_0002: newobj ""C..ctor(long)"" IL_0007: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_000c: dup IL_000d: ldc.i4.s 11 IL_000f: conv.i8 IL_0010: callvirt ""void C.X.init"" IL_0015: callvirt ""long C.X.get"" IL_001a: call ""void System.Console.WriteLine(long)"" IL_001f: ret }"); } [Fact] public void WithExprConversions2() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static implicit operator long(S s) { Console.WriteLine(""conversion""); return s._i; } } record C(long X) { public static void Main() { var c = new C(0); var s = new S(11); Console.WriteLine((c with { X = s }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" conversion 11").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 44 (0x2c) .maxstack 3 .locals init (S V_0) //s IL_0000: ldc.i4.0 IL_0001: conv.i8 IL_0002: newobj ""C..ctor(long)"" IL_0007: ldloca.s V_0 IL_0009: ldc.i4.s 11 IL_000b: call ""S..ctor(int)"" IL_0010: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0015: dup IL_0016: ldloc.0 IL_0017: call ""long S.op_Implicit(S)"" IL_001c: callvirt ""void C.X.init"" IL_0021: callvirt ""long C.X.get"" IL_0026: call ""void System.Console.WriteLine(long)"" IL_002b: ret }"); } [Fact] public void WithExprConversions3() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static explicit operator int(S s) { Console.WriteLine(""conversion""); return s._i; } } record C(long X) { public static void Main() { var c = new C(0); var s = new S(11); Console.WriteLine((c with { X = (int)s }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" conversion 11").VerifyDiagnostics(); } [Fact] public void WithExprConversions4() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static explicit operator long(S s) => s._i; } record C(long X) { public static void Main() { var c = new C(0); var s = new S(11); Console.WriteLine((c with { X = s }).X); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (19,41): error CS0266: Cannot implicitly convert type 'S' to 'long'. An explicit conversion exists (are you missing a cast?) // Console.WriteLine((c with { X = s }).X); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "s").WithArguments("S", "long").WithLocation(19, 41) ); } [Fact] public void WithExprConversions5() { var src = @" using System; record C(object X) { public static void Main() { var c = new C(0); Console.WriteLine((c with { X = ""abc"" }).X); } }"; CompileAndVerify(src, expectedOutput: "abc").VerifyDiagnostics(); } [Fact] public void WithExprConversions6() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static implicit operator int(S s) { Console.WriteLine(""conversion""); return s._i; } } record C { private readonly long _x; public long X { get => _x; init { Console.WriteLine(""set""); _x = value; } } public static void Main() { var c = new C(); var s = new S(11); Console.WriteLine((c with { X = s }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" conversion set 11").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 43 (0x2b) .maxstack 3 .locals init (S V_0) //s IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_0 IL_0007: ldc.i4.s 11 IL_0009: call ""S..ctor(int)"" IL_000e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0013: dup IL_0014: ldloc.0 IL_0015: call ""int S.op_Implicit(S)"" IL_001a: conv.i8 IL_001b: callvirt ""void C.X.init"" IL_0020: callvirt ""long C.X.get"" IL_0025: call ""void System.Console.WriteLine(long)"" IL_002a: ret }"); } [Fact] public void WithExprStaticProperty() { var src = @" record C { public static int X { get; set; } public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,22): error CS0176: Member 'C.X' cannot be accessed with an instance reference; qualify it with a type name instead // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_ObjectProhibited, "X").WithArguments("C.X").WithLocation(9, 22) ); } [Fact] public void WithExprMethodAsArgument() { var src = @" record C { public int X() => 0; public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,22): error CS1913: Member 'X' cannot be initialized. It is not a field or property. // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "X").WithArguments("X").WithLocation(9, 22) ); } [Fact] public void WithExprStaticWithMethod() { var src = @" class C { public int X = 0; public static C Clone() => null; public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone". // c = c with { }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(9, 13), // (10,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone". // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(10, 13) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExprStaticWithMethod2() { var src = @" class B { public B Clone() => null; } class C : B { public int X = 0; public static new C Clone() => null; // static public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,13): error CS0266: Cannot implicitly convert type 'B' to 'C'. An explicit conversion exists (are you missing a cast?) // c = c with { }; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "c with { }").WithArguments("B", "C").WithLocation(13, 13), // (14,22): error CS0117: 'B' does not contain a definition for 'X' // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("B", "X").WithLocation(14, 22) ); } [Fact] public void WithExprBadMemberBadType() { var src = @" record C { public int X { get; init; } public static void Main() { var c = new C(); c = c with { X = ""a"" }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int' // c = c with { X = "a" }; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""a""").WithArguments("string", "int").WithLocation(8, 26) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExprCloneReturnDifferent() { var src = @" class B { public int X { get; init; } } class C : B { public B Clone() => new B(); public static void Main() { var c = new C(); var b = c with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithSemanticModel1() { var src = @" record C(int X, string Y) { public static void Main() { var c = new C(0, ""a""); c = c with { X = 2 }; } }"; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees[0]; var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); var withExpr = root.DescendantNodes().OfType<WithExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(withExpr); var c = comp.GlobalNamespace.GetTypeMember("C"); Assert.True(c.IsRecord); Assert.True(c.ISymbol.Equals(typeInfo.Type)); var x = c.GetMembers("X").Single(); var xId = withExpr.DescendantNodes().Single(id => id.ToString() == "X"); var symbolInfo = model.GetSymbolInfo(xId); Assert.True(x.ISymbol.Equals(symbolInfo.Symbol)); comp.VerifyOperationTree(withExpr, @" IWithOperation (OperationKind.With, Type: C) (Syntax: 'c with { X = 2 }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 2 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')"); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0, ""a"")') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0, ""a"")') Right: IObjectCreationOperation (Constructor: C..ctor(System.Int32 X, System.String Y)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0, ""a"")') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: '""a""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""a"") (Syntax: '""a""') 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) Initializer: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] [1] Block[B2] - Block Predecessors: [B1] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c with { X = 2 }') Value: IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with { X = 2 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with { X = 2 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }') Next (Regular) Block[B3] Leaving: {R2} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void NoCloneMethod_01() { var src = @" class C { int X { get; set; } public static void Main() { var c = new C(); c = c with { X = 2 }; } }"; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees[0]; var root = tree.GetRoot(); var withExpr = root.DescendantNodes().OfType<WithExpressionSyntax>().Single(); comp.VerifyOperationTree(withExpr, @" IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { X = 2 }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 2 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')"); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Right: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] [1] Block[B2] - Block Predecessors: [B1] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c') Value: IInvalidOperation (OperationKind.Invalid, Type: C, IsInvalid, IsImplicit) (Syntax: 'c') Children(1): ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'c = c with { X = 2 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsInvalid) (Syntax: 'c = c with { X = 2 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c') Next (Regular) Block[B3] Leaving: {R2} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void NoCloneMethod_02() { var source = @"#nullable enable class R { public object? P { get; set; } } class Program { static void Main() { R r = new R(); _ = r with { P = 2 }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS8858: The receiver type 'R' is not a valid record type. // _ = r with { P = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "r").WithArguments("R").WithLocation(11, 13)); } [Fact] public void WithBadExprArg() { var src = @" record C(int X, int Y) { public static void Main() { var c = new C(0, 0); c = c with { 5 }; c = c with { { X = 2 } }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,22): error CS0747: Invalid initializer member declarator // c = c with { 5 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "5").WithLocation(8, 22), // (9,22): error CS1513: } expected // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(9, 22), // (9,22): error CS1002: ; expected // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(9, 22), // (9,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.X' // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_ObjectRequired, "X").WithArguments("C.X").WithLocation(9, 24), // (9,30): error CS1002: ; expected // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(9, 30), // (9,33): error CS1597: Semicolon after method or accessor block is not valid // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(9, 33), // (11,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(11, 1) ); var tree = comp.SyntaxTrees[0]; var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); VerifyClone(model); var withExpr1 = root.DescendantNodes().OfType<WithExpressionSyntax>().First(); comp.VerifyOperationTree(withExpr1, @" IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { 5 }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ 5 }') Initializers(1): IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '5') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsInvalid) (Syntax: '5')"); var withExpr2 = root.DescendantNodes().OfType<WithExpressionSyntax>().Skip(1).Single(); comp.VerifyOperationTree(withExpr2, @" IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { ') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ ') Initializers(0)"); } [Fact] public void WithExpr_DefiniteAssignment_01() { var src = @" record B(int X) { static void M(B b) { int y; _ = b with { X = y = 42 }; y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_02() { var src = @" record B(int X, string Y) { static void M(B b) { int z; _ = b with { X = z = 42, Y = z.ToString() }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_03() { var src = @" record B(int X, string Y) { static void M(B b) { int z; _ = b with { Y = z.ToString(), X = z = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,26): error CS0165: Use of unassigned local variable 'z' // _ = b with { Y = z.ToString(), X = z = 42 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(7, 26)); } [Fact] public void WithExpr_DefiniteAssignment_04() { var src = @" record B(int X) { static void M() { B b; _ = (b = new B(42)) with { X = b.X }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_05() { var src = @" record B(int X) { static void M() { B b; _ = new B(b.X) with { X = (b = new B(42)).X }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,19): error CS0165: Use of unassigned local variable 'b' // _ = new B(b.X) with { X = new B(42).X }; Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(7, 19)); } [Fact] public void WithExpr_DefiniteAssignment_06() { var src = @" record B(int X) { static void M(B b) { int y; _ = b with { X = M(out y) }; y.ToString(); } static int M(out int y) { y = 42; return 43; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_07() { var src = @" record B(int X) { static void M(B b) { _ = b with { X = M(out int y) }; y.ToString(); } static int M(out int y) { y = 42; return 43; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_01() { var src = @" #nullable enable record B(int X) { static void M(B b) { string? s = null; _ = b with { X = M(out s) }; s.ToString(); } static int M(out string s) { s = ""a""; return 42; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_02() { var src = @" #nullable enable record B(string X) { static void M(B b, string? s) { b.X.ToString(); _ = b with { X = s }; // 1 b.X.ToString(); // 2 } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): warning CS8601: Possible null reference assignment. // _ = b with { X = s }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(8, 26)); } [Fact] public void WithExpr_NullableAnalysis_03() { var src = @" #nullable enable record B(string? X) { static void M1(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 1 _ = b with { X = s }; if (flag) { b.X.ToString(); } // 2 } static void M2(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 3 b = b with { X = s }; if (flag) { b.X.ToString(); } } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(7, 21), // (9,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(9, 21), // (14,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(14, 21)); } [Fact] public void WithExpr_NullableAnalysis_04() { var src = @" #nullable enable record B(int X) { static void M1(B? b) { var b1 = b with { X = 42 }; // 1 _ = b.ToString(); _ = b1.ToString(); } static void M2(B? b) { (b with { X = 42 }).ToString(); // 2 } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,18): warning CS8602: Dereference of a possibly null reference. // var b1 = b with { X = 42 }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(7, 18), // (14,10): warning CS8602: Dereference of a possibly null reference. // (b with { X = 42 }).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(14, 10)); } [Fact, WorkItem(44763, "https://github.com/dotnet/roslyn/issues/44763")] public void WithExpr_NullableAnalysis_05() { var src = @" #nullable enable record B(string? X, string? Y) { static void M1(bool flag) { B b = new B(""hello"", null); if (flag) { b.X.ToString(); // shouldn't warn b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); // shouldn't warn b.Y.ToString(); } }"; // records should propagate the nullability of the // constructor arguments to the corresponding properties. // https://github.com/dotnet/roslyn/issues/44763 var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(11, 13), // (15,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(15, 9)); } [Fact] public void WithExpr_NullableAnalysis_06() { var src = @" #nullable enable record B { public string? X { get; init; } public string? Y { get; init; } static void M1(bool flag) { B b = new B { X = ""hello"", Y = null }; if (flag) { b.X.ToString(); b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); b.Y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(14, 13) ); } [Fact, WorkItem(44691, "https://github.com/dotnet/roslyn/issues/44691")] public void WithExpr_NullableAnalysis_07() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B([AllowNull] string X) // 1 { static void M1(B b) { b.X.ToString(); b = b with { X = null }; // 2 b.X.ToString(); // 3 b = new B((string?)null); b.X.ToString(); } }"; var comp = CreateCompilation(new[] { src, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,10): warning CS8601: Possible null reference assignment. // record B([AllowNull] string X) // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "[AllowNull] string X").WithLocation(5, 10), // (10,26): warning CS8625: Cannot convert null literal to non-nullable reference type. // b = b with { X = null }; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 26), // (11,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(11, 9)); } [Fact, WorkItem(44691, "https://github.com/dotnet/roslyn/issues/44691")] public void WithExpr_NullableAnalysis_08() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B([property: AllowNull][AllowNull] string X) { static void M1(B b) { b.X.ToString(); b = b with { X = null }; b.X.ToString(); // 1 b = new B((string?)null); b.X.ToString(); } }"; var comp = CreateCompilation(new[] { src, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(11, 9)); } [Fact] public void WithExpr_NullableAnalysis_09() { var src = @" #nullable enable record B(string? X, string? Y) { static void M1(B b1) { B b2 = b1 with { X = ""hello"" }; B b3 = b1 with { Y = ""world"" }; B b4 = b2 with { Y = ""world"" }; b1.X.ToString(); // 1 b1.Y.ToString(); // 2 b2.X.ToString(); b2.Y.ToString(); // 3 b3.X.ToString(); // 4 b3.Y.ToString(); b4.X.ToString(); b4.Y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // b1.X.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1.X").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // b1.Y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1.Y").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // b2.Y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b2.Y").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // b3.X.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b3.X").WithLocation(15, 9)); } [Fact] public void WithExpr_NullableAnalysis_10() { var src = @" #nullable enable record B(string? X, string? Y) { static void M1(B b1) { string? local = ""hello""; _ = b1 with { X = local = null, Y = local.ToString() // 1 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,17): warning CS8602: Dereference of a possibly null reference. // Y = local.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "local").WithLocation(11, 17)); } [Fact] public void WithExpr_NullableAnalysis_11() { var src = @" #nullable enable record B(string X, string Y) { static string M0(out string? s) { s = null; return ""hello""; } static void M1(B b1) { string? local = ""world""; _ = b1 with { X = M0(out local), Y = local // 1 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,17): warning CS8601: Possible null reference assignment. // Y = local // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "local").WithLocation(13, 17)); } [Fact] public void WithExpr_NullableAnalysis_VariantClone() { var src = @" #nullable enable record A { public string? Y { get; init; } public string? Z { get; init; } } record B(string? X) : A { public new string Z { get; init; } = ""zed""; static void M1(B b1) { b1.Z.ToString(); (b1 with { Y = ""hello"" }).Y.ToString(); (b1 with { Y = ""hello"" }).Z.ToString(); } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_NullableClone() { var src = @" #nullable enable record B(string? X) { public B? Clone() => new B(X); static void M1(B b1) { _ = b1 with { X = null }; // 1 (b1 with { X = null }).ToString(); // 2 } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,21): warning CS8602: Dereference of a possibly null reference. // _ = b1 with { X = null }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(10, 21), // (11,18): warning CS8602: Dereference of a possibly null reference. // (b1 with { X = null }).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(11, 18)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_MaybeNullClone() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B(string? X) { [return: MaybeNull] public B Clone() => new B(X); static void M1(B b1) { _ = b1 with { }; _ = b1 with { X = null }; // 1 (b1 with { X = null }).ToString(); // 2 } } "; var comp = CreateCompilation(new[] { src, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (13,21): warning CS8602: Dereference of a possibly null reference. // _ = b1 with { X = null }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(13, 21), // (14,18): warning CS8602: Dereference of a possibly null reference. // (b1 with { X = null }).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(14, 18)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_NotNullClone() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B(string? X) { [return: NotNull] public B? Clone() => new B(X); static void M1(B b1) { _ = b1 with { }; _ = b1 with { X = null }; (b1 with { X = null }).ToString(); } } "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_NullableClone_NoInitializers() { var src = @" #nullable enable record B(string? X) { public B? Clone() => new B(X); static void M1(B b1) { _ = b1 with { }; (b1 with { }).ToString(); // 1 } } "; var comp = CreateCompilation(src); // Note: we expect to give a warning on `// 1`, but do not currently // due to limitations of object initializer analysis. // Tracking in https://github.com/dotnet/roslyn/issues/44759 comp.VerifyDiagnostics(); } [Fact] public void WithExprNominalRecord() { var src = @" using System; record C { public int X { get; set; } public string Y { get; init; } public long Z; public event Action E; public C() { } public C(C other) { X = other.X; Y = other.Y; Z = other.Z; E = other.E; } public static void Main() { var c = new C() { X = 1, Y = ""2"", Z = 3, E = () => { } }; var c2 = c with {}; Console.WriteLine(c.Equals(c2)); Console.WriteLine(ReferenceEquals(c, c2)); Console.WriteLine(c2.X); Console.WriteLine(c2.Y); Console.WriteLine(c2.Z); Console.WriteLine(ReferenceEquals(c.E, c2.E)); var c3 = c with { Y = ""3"", X = 2 }; Console.WriteLine(c.Y); Console.WriteLine(c3.Y); Console.WriteLine(c.X); Console.WriteLine(c3.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" True False 1 2 3 True 2 3 1 2").VerifyDiagnostics(); } [Fact] public void WithExprNominalRecord2() { var comp1 = CreateCompilation(@" public record C { public int X { get; set; } public string Y { get; init; } public long Z; public C() { } public C(C other) { X = other.X; Y = other.Y; Z = other.Z; } }"); var verifier = CompileAndVerify(@" class D { public C M(C c) => c with { X = 5, Y = ""a"", Z = 2, }; }", references: new[] { comp1.EmitToImageReference() }).VerifyDiagnostics(); verifier.VerifyIL("D.M", @" { // Code size 33 (0x21) .maxstack 3 IL_0000: ldarg.1 IL_0001: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0006: dup IL_0007: ldc.i4.5 IL_0008: callvirt ""void C.X.set"" IL_000d: dup IL_000e: ldstr ""a"" IL_0013: callvirt ""void C.Y.init"" IL_0018: dup IL_0019: ldc.i4.2 IL_001a: conv.i8 IL_001b: stfld ""long C.Z"" IL_0020: ret }"); } [Fact] public void WithExprAssignToRef1() { var src = @" using System; record C(int Y) { private readonly int[] _a = new[] { 0 }; public ref int X => ref _a[0]; public static void Main() { var c = new C(0) { X = 5 }; Console.WriteLine(c.X); c = c with { X = 1 }; Console.WriteLine(c.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 5 1").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 51 (0x33) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: newobj ""C..ctor(int)"" IL_0006: dup IL_0007: callvirt ""ref int C.X.get"" IL_000c: ldc.i4.5 IL_000d: stind.i4 IL_000e: dup IL_000f: callvirt ""ref int C.X.get"" IL_0014: ldind.i4 IL_0015: call ""void System.Console.WriteLine(int)"" IL_001a: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_001f: dup IL_0020: callvirt ""ref int C.X.get"" IL_0025: ldc.i4.1 IL_0026: stind.i4 IL_0027: callvirt ""ref int C.X.get"" IL_002c: ldind.i4 IL_002d: call ""void System.Console.WriteLine(int)"" IL_0032: ret }"); } [Fact] public void WithExprAssignToRef2() { var src = @" using System; record C(int Y) { private readonly int[] _a = new[] { 0 }; public ref int X { get => ref _a[0]; set { } } public static void Main() { var a = new[] { 0 }; var c = new C(0) { X = ref a[0] }; Console.WriteLine(c.X); c = c with { X = ref a[0] }; Console.WriteLine(c.X); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,9): error CS8147: Properties which return by reference cannot have set accessors // set { } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("C.X.set").WithLocation(9, 9), // (15,32): error CS1525: Invalid expression term 'ref' // var c = new C(0) { X = ref a[0] }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref a[0]").WithArguments("ref").WithLocation(15, 32), // (15,32): error CS1073: Unexpected token 'ref' // var c = new C(0) { X = ref a[0] }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(15, 32), // (17,26): error CS1073: Unexpected token 'ref' // c = c with { X = ref a[0] }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(17, 26) ); } [Fact] public void WithExpressionSameLHS() { var comp = CreateCompilation(@" record C(int X) { public static void Main() { var c = new C(0); c = c with { X = 1, X = 2}; } }"); comp.VerifyDiagnostics( // (7,29): error CS1912: Duplicate initialization of member 'X' // c = c with { X = 1, X = 2}; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(7, 29) ); } [Fact] public void WithExpr_ValEscape() { var text = @" using System; record R { public S1 Property { set { throw null; } } } class Program { static void Main() { var r = new R(); Span<int> local = stackalloc int[1]; _ = r with { Property = MayWrap(ref local) }; _ = new R() { Property = MayWrap(ref local) }; } static S1 MayWrap(ref Span<int> arg) { return default; } } ref struct S1 { public ref int this[int i] => throw null; } "; CreateCompilationWithMscorlibAndSpan(text).VerifyDiagnostics(); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Fact] public void Inheritance_01() { var source = @"record A { internal A() { } public object P1 { get; set; } internal object P2 { get; set; } protected internal object P3 { get; set; } protected object P4 { get; set; } private protected object P5 { get; set; } private object P6 { get; set; } } record B(object P1, object P2, object P3, object P4, object P5, object P6) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28), // (11,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(11, 39), // (11,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(11, 50), // (11,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(11, 61) ); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P6 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Fact] public void Inheritance_02() { var source = @"record A { internal A() { } private protected object P1 { get; set; } private object P2 { get; set; } private record B(object P1, object P2) : A { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,29): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // private record B(object P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(6, 29), // (6,40): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // private record B(object P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(6, 40) ); var actualMembers = GetProperties(comp, "A.B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type A.B.EqualityContract { get; }" }, actualMembers); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Theory] [InlineData(false)] [InlineData(true)] public void Inheritance_03(bool useCompilationReference) { var sourceA = @"public record A { public A() { } internal object P { get; set; } } public record B(object Q) : A { public B() : this(null) { } } record C1(object P, object Q) : B { }"; var comp = CreateCompilation(sourceA); AssertEx.Equal(new[] { "System.Type C1.EqualityContract { get; }" }, GetProperties(comp, "C1").ToTestDisplayStrings()); var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference(); var sourceB = @"record C2(object P, object Q) : B { }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,28): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record C2(object P, object Q) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 28) ); AssertEx.Equal(new[] { "System.Type C2.EqualityContract { get; }", "System.Object C2.P { get; init; }" }, GetProperties(comp, "C2").ToTestDisplayStrings()); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Fact] public void Inheritance_04() { var source = @"record A { internal A() { } public object P1 { get { return null; } set { } } public object P2 { get; init; } public object P3 { get; } public object P4 { set { } } public virtual object P5 { get; set; } public static object P6 { get; set; } public ref object P7 => throw null; } record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(12, 17), // (12,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(12, 28), // (12,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(12, 39), // (12,50): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'object' to match positional parameter 'P4'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "object", "P4").WithLocation(12, 50), // (12,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(12, 50), // (12,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(12, 61), // (12,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(12, 72), // (12,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(12, 72), // (12,83): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(12, 83)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_05() { var source = @"record A { internal A() { } public object P1 { get; set; } public int P2 { get; set; } } record B(int P1, object P2) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'int' to match positional parameter 'P1'. // record B(int P1, object P2) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "int", "P1").WithLocation(7, 14), // (7,14): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(int P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(7, 14), // (7,25): error CS8866: Record member 'A.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'. // record B(int P1, object P2) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("A.P2", "object", "P2").WithLocation(7, 25), // (7,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(int P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(7, 25)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_06() { var source = @"record A { internal int X { get; set; } internal int Y { set { } } internal int Z; } record B(int X, int Y, int Z) : A { } class Program { static void Main() { var b = new B(1, 2, 3); b.X = 4; b.Y = 5; b.Z = 6; ((A)b).X = 7; ((A)b).Y = 8; ((A)b).Z = 9; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14), // (7,21): error CS8866: Record member 'A.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'. // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("A.Y", "int", "Y").WithLocation(7, 21), // (7,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 21), // (7,24): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int Z").WithArguments("positional fields in records", "10.0").WithLocation(7, 24), // (7,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(7, 28)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_07() { var source = @"abstract record A { public abstract int X { get; } public virtual int Y { get; } } abstract record B1(int X, int Y) : A { } record B2(int X, int Y) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,24): error CS0546: 'B1.X.init': cannot override because 'A.X' does not have an overridable set accessor // abstract record B1(int X, int Y) : A Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("B1.X.init", "A.X").WithLocation(6, 24), // (6,31): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record B1(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(6, 31), // (9,15): error CS0546: 'B2.X.init': cannot override because 'A.X' does not have an overridable set accessor // record B2(int X, int Y) : A Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("B2.X.init", "A.X").WithLocation(9, 15), // (9,22): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B2(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(9, 22)); AssertEx.Equal(new[] { "System.Type B1.EqualityContract { get; }", "System.Int32 B1.X { get; init; }" }, GetProperties(comp, "B1").ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.Type B2.EqualityContract { get; }", "System.Int32 B2.X { get; init; }" }, GetProperties(comp, "B2").ToTestDisplayStrings()); var b1Ctor = comp.GetTypeByMetadataName("B1")!.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal("B1..ctor(System.Int32 X, System.Int32 Y)", b1Ctor.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, b1Ctor.DeclaredAccessibility); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_08() { var source = @"abstract record A { public abstract int X { get; } public virtual int Y { get; } public virtual int Z { get; } } abstract record B : A { public override abstract int Y { get; } } record C(int X, int Y, int Z) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,14): error CS0546: 'C.X.init': cannot override because 'A.X' does not have an overridable set accessor // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("C.X.init", "A.X").WithLocation(11, 14), // (11,21): error CS0546: 'C.Y.init': cannot override because 'B.Y' does not have an overridable set accessor // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.ERR_NoSetToOverride, "Y").WithArguments("C.Y.init", "B.Y").WithLocation(11, 21), // (11,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(11, 28)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; init; }", "System.Int32 C.Y { get; init; }" }, actualMembers); } [Fact, WorkItem(48947, "https://github.com/dotnet/roslyn/issues/48947")] public void Inheritance_09() { var source = @"abstract record C(int X, int Y) { public abstract int X { get; } public virtual int Y { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,23): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // abstract record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(1, 23), // (1,30): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(1, 30) ); NamedTypeSymbol c = comp.GetMember<NamedTypeSymbol>("C"); var actualMembers = c.GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; }", "System.Int32 C.X.get", "System.Int32 C.<Y>k__BackingField", "System.Int32 C.Y { get; }", "System.Int32 C.Y.get", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); var expectedMemberNames = new[] { ".ctor", "get_EqualityContract", "EqualityContract", "X", "get_X", "<Y>k__BackingField", "Y", "get_Y", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, c.GetPublicSymbol().MemberNames); var expectedCtors = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)", }; AssertEx.Equal(expectedCtors, c.GetPublicSymbol().Constructors.ToTestDisplayStrings()); } [Fact] public void Inheritance_10() { var source = @"using System; interface IA { int X { get; } } interface IB { int Y { get; } } record C(int X, int Y) : IA, IB { } class Program { static void Main() { var c = new C(1, 2); Console.WriteLine(""{0}, {1}"", c.X, c.Y); Console.WriteLine(""{0}, {1}"", ((IA)c).X, ((IB)c).Y); } }"; CompileAndVerify(source, expectedOutput: @"1, 2 1, 2").VerifyDiagnostics(); } [Fact] public void Inheritance_11() { var source = @"interface IA { int X { get; } } interface IB { object Y { get; set; } } record C(object X, object Y) : IA, IB { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,32): error CS0738: 'C' does not implement interface member 'IA.X'. 'C.X' cannot implement 'IA.X' because it does not have the matching return type of 'int'. // record C(object X, object Y) : IA, IB Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "IA").WithArguments("C", "IA.X", "C.X", "int").WithLocation(9, 32), // (9,36): error CS8854: 'C' does not implement interface member 'IB.Y.set'. 'C.Y.init' cannot implement 'IB.Y.set'. // record C(object X, object Y) : IA, IB Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "IB").WithArguments("C", "IB.Y.set", "C.Y.init").WithLocation(9, 36) ); } [Fact] public void Inheritance_12() { var source = @"record A { public object X { get; } public object Y { get; } } record B(object X, object Y) : A { public object X { get; } public object Y { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(6, 17), // (6,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(6, 27), // (8,19): warning CS0108: 'B.X' hides inherited member 'A.X'. Use the new keyword if hiding was intended. // public object X { get; } Diagnostic(ErrorCode.WRN_NewRequired, "X").WithArguments("B.X", "A.X").WithLocation(8, 19), // (9,19): warning CS0108: 'B.Y' hides inherited member 'A.Y'. Use the new keyword if hiding was intended. // public object Y { get; } Diagnostic(ErrorCode.WRN_NewRequired, "Y").WithArguments("B.Y", "A.Y").WithLocation(9, 19)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.X { get; }", "System.Object B.Y { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_13() { var source = @"record A(object X, object Y) { internal A() : this(null, null) { } } record B(object X, object Y) : A { public object X { get; } public object Y { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 17), // (5,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 27), // (7,19): warning CS0108: 'B.X' hides inherited member 'A.X'. Use the new keyword if hiding was intended. // public object X { get; } Diagnostic(ErrorCode.WRN_NewRequired, "X").WithArguments("B.X", "A.X").WithLocation(7, 19), // (8,19): warning CS0108: 'B.Y' hides inherited member 'A.Y'. Use the new keyword if hiding was intended. // public object Y { get; } Diagnostic(ErrorCode.WRN_NewRequired, "Y").WithArguments("B.Y", "A.Y").WithLocation(8, 19)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.X { get; }", "System.Object B.Y { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_14() { var source = @"record A { public object P1 { get; } public object P2 { get; } public object P3 { get; } public object P4 { get; } } record B : A { public new int P1 { get; } public new int P2 { get; } } record C(object P1, int P2, object P3, int P4) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,17): error CS8866: Record member 'B.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("B.P1", "object", "P1").WithLocation(13, 17), // (13,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(13, 17), // (13,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(13, 25), // (13,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(13, 36), // (13,44): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'int' to match positional parameter 'P4'. // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "int", "P4").WithLocation(13, 44), // (13,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(13, 44)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_15() { var source = @"record C(int P1, object P2) { public object P1 { get; set; } public int P2 { get; set; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,14): error CS8866: Record member 'C.P1' must be a readable instance property or field of type 'int' to match positional parameter 'P1'. // record C(int P1, object P2) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("C.P1", "int", "P1").WithLocation(1, 14), // (1,14): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(int P1, object P2) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 14), // (1,25): error CS8866: Record member 'C.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'. // record C(int P1, object P2) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("C.P2", "object", "P2").WithLocation(1, 25), // (1,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(int P1, object P2) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 25)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P1 { get; set; }", "System.Int32 C.P2 { get; set; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_16() { var source = @"record A { public int P1 { get; } public int P2 { get; } public int P3 { get; } public int P4 { get; } } record B(object P1, int P2, object P3, int P4) : A { public new object P1 { get; } public new object P2 { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(8, 17), // (8,25): error CS8866: Record member 'B.P2' must be a readable instance property or field of type 'int' to match positional parameter 'P2'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("B.P2", "int", "P2").WithLocation(8, 25), // (8,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(8, 25), // (8,36): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(8, 36), // (8,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(8, 36), // (8,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(8, 44)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P1 { get; }", "System.Object B.P2 { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_17() { var source = @"record A { public object P1 { get; } public object P2 { get; } public object P3 { get; } public object P4 { get; } } record B(object P1, int P2, object P3, int P4) : A { public new int P1 { get; } public new int P2 { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,17): error CS8866: Record member 'B.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("B.P1", "object", "P1").WithLocation(8, 17), // (8,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(8, 17), // (8,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(8, 25), // (8,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(8, 36), // (8,44): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'int' to match positional parameter 'P4'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "int", "P4").WithLocation(8, 44), // (8,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(8, 44)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Int32 B.P1 { get; }", "System.Int32 B.P2 { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_18() { var source = @"record C(object P1, object P2, object P3, object P4, object P5) { public object P1 { get { return null; } set { } } public object P2 { get; } public object P3 { set { } } public static object P4 { get; set; } public ref object P5 => throw null; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (1,39): error CS8866: Record member 'C.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("C.P3", "object", "P3").WithLocation(1, 39), // (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39), // (1,50): error CS8866: Record member 'C.P4' must be a readable instance property or field of type 'object' to match positional parameter 'P4'. // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("C.P4", "object", "P4").WithLocation(1, 50), // (1,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(1, 50), // (1,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(1, 61)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P1 { get; set; }", "System.Object C.P2 { get; }", "System.Object C.P3 { set; }", "System.Object C.P4 { get; set; }", "ref System.Object C.P5 { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_19() { var source = @"#pragma warning disable 8618 #nullable enable record A { internal A() { } public object P1 { get; } public dynamic[] P2 { get; } public object? P3 { get; } public object[] P4 { get; } public (int X, int Y) P5 { get; } public (int, int)[] P6 { get; } public nint P7 { get; } public System.UIntPtr[] P8 { get; } } record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,18): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(15, 18), // (15,31): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(15, 31), // (15,42): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(15, 42), // (15,56): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(15, 56), // (15,71): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(15, 71), // (15,92): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(15, 92), // (15,110): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(15, 110), // (15,122): warning CS8907: Parameter 'P8' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P8").WithArguments("P8").WithLocation(15, 122) ); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_20() { var source = @"#pragma warning disable 8618 #nullable enable record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) { public object P1 { get; } public dynamic[] P2 { get; } public object? P3 { get; } public object[] P4 { get; } public (int X, int Y) P5 { get; } public (int, int)[] P6 { get; } public nint P7 { get; } public System.UIntPtr[] P8 { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,18): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(3, 18), // (3,31): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(3, 31), // (3,42): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(3, 42), // (3,56): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(3, 56), // (3,71): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(3, 71), // (3,92): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(3, 92), // (3,110): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(3, 110), // (3,122): warning CS8907: Parameter 'P8' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P8").WithArguments("P8").WithLocation(3, 122) ); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P1 { get; }", "dynamic[] C.P2 { get; }", "System.Object? C.P3 { get; }", "System.Object[] C.P4 { get; }", "(System.Int32 X, System.Int32 Y) C.P5 { get; }", "(System.Int32, System.Int32)[] C.P6 { get; }", "nint C.P7 { get; }", "System.UIntPtr[] C.P8 { get; }" }; AssertEx.Equal(expectedMembers, actualMembers); } [Theory] [InlineData(false)] [InlineData(true)] public void Inheritance_21(bool useCompilationReference) { var sourceA = @"public record A { public object P1 { get; } internal object P2 { get; } } public record B : A { internal new object P1 { get; } public new object P2 { get; } }"; var comp = CreateCompilation(sourceA); var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference(); var sourceB = @"record C(object P1, object P2) : B { } class Program { static void Main() { var c = new C(1, 2); System.Console.WriteLine(""({0}, {1})"", c.P1, c.P2); } }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); var verifier = CompileAndVerify(comp, expectedOutput: "(, )").VerifyDiagnostics( // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28) ); verifier.VerifyIL("C..ctor(object, object)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""B..ctor()"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(C)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ret }"); verifier.VerifyIL("Program.Main", @"{ // Code size 41 (0x29) .maxstack 3 .locals init (C V_0) //c IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: ldc.i4.2 IL_0007: box ""int"" IL_000c: newobj ""C..ctor(object, object)"" IL_0011: stloc.0 IL_0012: ldstr ""({0}, {1})"" IL_0017: ldloc.0 IL_0018: callvirt ""object A.P1.get"" IL_001d: ldloc.0 IL_001e: callvirt ""object B.P2.get"" IL_0023: call ""void System.Console.WriteLine(string, object, object)"" IL_0028: ret }"); } [Fact] public void Inheritance_22() { var source = @"record A { public ref object P1 => throw null; public object P2 => throw null; } record B : A { public new object P1 => throw null; public new ref object P2 => throw null; } record C(object P1, object P2) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28) ); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_23() { var source = @"record A { public static object P1 { get; } public object P2 { get; } } record B : A { public new object P1 { get; } public new static object P2 { get; } } record C(object P1, object P2) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): error CS8866: Record member 'B.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'. // record C(object P1, object P2) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("B.P2", "object", "P2").WithLocation(11, 28), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_24() { var source = @"record A { public object get_P() => null; public object set_Q() => null; } record B(object P, object Q) : A { } record C(object P) { public object get_P() => null; public object set_Q() => null; }"; var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? source : new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics( // (9,17): error CS0082: Type 'C' already reserves a member called 'get_P' with the same parameter types // record C(object P) Diagnostic(ErrorCode.ERR_MemberReserved, "P").WithArguments("get_P", "C").WithLocation(9, 17)); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); var expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses ? "B B." + WellKnownMemberNames.CloneMethodName + "()" : "A B." + WellKnownMemberNames.CloneMethodName + "()"; var expectedMembers = new[] { "B..ctor(System.Object P, System.Object Q)", "System.Type B.EqualityContract.get", "System.Type B.EqualityContract { get; }", "System.Object B.<P>k__BackingField", "System.Object B.P.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.P.init", "System.Object B.P { get; init; }", "System.Object B.<Q>k__BackingField", "System.Object B.Q.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Q.init", "System.Object B.Q { get; init; }", "System.String B.ToString()", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", expectedClone, "B..ctor(B original)", "void B.Deconstruct(out System.Object P, out System.Object Q)" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings()); expectedMembers = new[] { "C..ctor(System.Object P)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.Object C.<P>k__BackingField", "System.Object C.P.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.P.init", "System.Object C.P { get; init; }", "System.Object C.get_P()", "System.Object C.set_Q()", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Object P)" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings()); } [Fact] public void Inheritance_25() { var sourceA = @"public record A { public class P1 { } internal object P2 = 2; public int P3(object o) => 3; internal int P4<T>(T t) => 4; }"; var sourceB = @"record B(object P1, object P2, object P3, object P4) : A { }"; var comp = CreateCompilation(new[] { sourceA, sourceB, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "object", "P1").WithLocation(1, 17), // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,21): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object P2").WithArguments("positional fields in records", "10.0").WithLocation(1, 21), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (1,39): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(1, 39), // (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P4 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); comp = CreateCompilation(sourceA); var refA = comp.EmitToImageReference(); comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "object", "P1").WithLocation(1, 17), // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,39): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(1, 39), // (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39)); actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P2 { get; init; }", "System.Object B.P4 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_26() { var sourceA = @"public record A { internal const int P = 4; }"; var sourceB = @"record B(object P) : A { }"; var comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (1,17): error CS8866: Record member 'A.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'. // record B(object P) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("A.P", "object", "P").WithLocation(1, 17), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B(object P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); comp = CreateCompilation(sourceA); var refA = comp.EmitToImageReference(); comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P { get; init; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [Fact] public void Inheritance_27() { var source = @"record A { public object P { get; } public object Q { get; set; } } record B(object get_P, object set_Q) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.get_P { get; init; }", "System.Object B.set_Q { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_28() { var source = @"interface I { object P { get; } } record A : I { object I.P => null; } record B(object P) : A { } record C(object P) : I { object I.P => null; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P { get; init; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P { get; init; }", "System.Object C.I.P { get; }" }, GetProperties(comp, "C").ToTestDisplayStrings()); } [Fact] public void Inheritance_29() { var sourceA = @"Public Class A Public Property P(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Property Q(x As Object, y As Object) As Object Get Return Nothing End Get Set End Set End Property End Class "; var compA = CreateVisualBasicCompilation(sourceA); compA.VerifyDiagnostics(); var refA = compA.EmitToImageReference(); var sourceB = @"record B(object P, object Q) : A { object P { get; } }"; var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'B.Equals(A?)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(1, 8), // (1,8): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,8): error CS8867: No accessible copy constructor found in base type 'A'. // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(1, 8), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B(object P, object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,32): error CS8864: Records may only inherit from object or another record // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(1, 32) ); var actualMembers = GetProperties(compB, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.Q { get; init; }", "System.Object B.P { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_30() { var sourceA = @"Public Class A Public ReadOnly Overloads Property P() As Object Get Return Nothing End Get End Property Public ReadOnly Overloads Property P(o As Object) As Object Get Return Nothing End Get End Property Public Overloads Property Q(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Overloads Property Q() As Object Get Return Nothing End Get Set End Set End Property End Class "; var compA = CreateVisualBasicCompilation(sourceA); compA.VerifyDiagnostics(); var refA = compA.EmitToImageReference(); var sourceB = @"record B(object P, object Q) : A { }"; var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'B.Equals(A?)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(1, 8), // (1,8): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,8): error CS8867: No accessible copy constructor found in base type 'A'. // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(1, 8), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B(object P, object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record B(object P, object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27), // (1,32): error CS8864: Records may only inherit from object or another record // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(1, 32) ); var actualMembers = GetProperties(compB, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_31() { var sourceA = @"Public Class A Public ReadOnly Property P() As Object Get Return Nothing End Get End Property Public Property Q(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Property R(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Sub New(a as A) End Sub End Class Public Class B Inherits A Public ReadOnly Overloads Property P(o As Object) As Object Get Return Nothing End Get End Property Public Overloads Property Q() As Object Get Return Nothing End Get Set End Set End Property Public Overloads Property R(x As Object, y As Object) As Object Get Return Nothing End Get Set End Set End Property Public Sub New(b as B) MyBase.New(b) End Sub End Class "; var compA = CreateVisualBasicCompilation(sourceA); compA.VerifyDiagnostics(); var refA = compA.EmitToImageReference(); var sourceB = @"record C(object P, object Q, object R) : B { }"; var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (1,8): error CS0115: 'C.EqualityContract': no suitable method found to override // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'C.Equals(B?)': no suitable method found to override // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.Equals(B?)").WithLocation(1, 8), // (1,8): error CS0115: 'C.PrintMembers(StringBuilder)': no suitable method found to override // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'b' of 'B.B(B)' // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("b", "B.B(B)").WithLocation(1, 8), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27), // (1,42): error CS8864: Records may only inherit from object or another record // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_BadRecordBase, "B").WithLocation(1, 42) ); var actualMembers = GetProperties(compB, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.R { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_32() { var source = @"record A { public virtual object P1 { get; } public virtual object P2 { get; set; } public virtual object P3 { get; protected init; } public virtual object P4 { protected get; init; } public virtual object P5 { init { } } public virtual object P6 { set { } } public static object P7 { get; set; } } record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28), // (11,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(11, 39), // (11,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(11, 50), // (11,61): error CS8866: Record member 'A.P5' must be a readable instance property or field of type 'object' to match positional parameter 'P5'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P5").WithArguments("A.P5", "object", "P5").WithLocation(11, 61), // (11,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(11, 61), // (11,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(11, 72), // (11,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(11, 72), // (11,83): error CS8866: Record member 'A.P7' must be a readable instance property or field of type 'object' to match positional parameter 'P7'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P7").WithArguments("A.P7", "object", "P7").WithLocation(11, 83), // (11,83): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(11, 83)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_33() { var source = @"abstract record A { public abstract object P1 { get; } public abstract object P2 { get; set; } public abstract object P3 { get; protected init; } public abstract object P4 { protected get; init; } public abstract object P5 { init; } public abstract object P6 { set; } } record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,8): error CS0534: 'B' does not implement inherited abstract member 'A.P6.set' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P6.set").WithLocation(10, 8), // (10,8): error CS0534: 'B' does not implement inherited abstract member 'A.P5.init' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P5.init").WithLocation(10, 8), // (10,17): error CS0546: 'B.P1.init': cannot override because 'A.P1' does not have an overridable set accessor // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_NoSetToOverride, "P1").WithArguments("B.P1.init", "A.P1").WithLocation(10, 17), // (10,28): error CS8853: 'B.P2' must match by init-only of overridden member 'A.P2' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "P2").WithArguments("B.P2", "A.P2").WithLocation(10, 28), // (10,39): error CS0507: 'B.P3.init': cannot change access modifiers when overriding 'protected' inherited member 'A.P3.init' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "P3").WithArguments("B.P3.init", "protected", "A.P3.init").WithLocation(10, 39), // (10,50): error CS0507: 'B.P4.get': cannot change access modifiers when overriding 'protected' inherited member 'A.P4.get' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "P4").WithArguments("B.P4.get", "protected", "A.P4.get").WithLocation(10, 50), // (10,61): error CS8866: Record member 'A.P5' must be a readable instance property or field of type 'object' to match positional parameter 'P5'. // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P5").WithArguments("A.P5", "object", "P5").WithLocation(10, 61), // (10,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(10, 61), // (10,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'. // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(10, 72), // (10,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(10, 72)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P1 { get; init; }", "System.Object B.P2 { get; init; }", "System.Object B.P3 { get; init; }", "System.Object B.P4 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_34() { var source = @"abstract record A { public abstract object P1 { get; init; } public virtual object P2 { get; init; } } record B(string P1, string P2) : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,8): error CS0534: 'B' does not implement inherited abstract member 'A.P1.init' // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P1.init").WithLocation(6, 8), // (6,8): error CS0534: 'B' does not implement inherited abstract member 'A.P1.get' // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P1.get").WithLocation(6, 8), // (6,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'string' to match positional parameter 'P1'. // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "string", "P1").WithLocation(6, 17), // (6,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(string P1, string P2) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(6, 17), // (6,28): error CS8866: Record member 'A.P2' must be a readable instance property or field of type 'string' to match positional parameter 'P2'. // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("A.P2", "string", "P2").WithLocation(6, 28), // (6,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(string P1, string P2) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(6, 28)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_35() { var source = @"using static System.Console; abstract record A(object X, object Y) { public abstract object X { get; } public abstract object Y { get; init; } } record B(object X, object Y) : A(X, Y) { public override object X { get; } = X; } class Program { static void Main() { B b = new B(1, 2); A a = b; WriteLine((b.X, b.Y)); WriteLine((a.X, a.Y)); var (x, y) = b; WriteLine((x, y)); (x, y) = a; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.Y { get; init; }", "System.Object B.X { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"(1, 2) (1, 2) (1, 2) (1, 2)").VerifyDiagnostics( // (2,26): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 26), // (2,36): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(2, 36) ); verifier.VerifyIL("A..ctor(object, object)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A..ctor(A)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("A.GetHashCode()", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type A.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ret }"); verifier.VerifyIL("B..ctor(object, object)", @"{ // Code size 23 (0x17) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.2 IL_0002: stfld ""object B.<Y>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: stfld ""object B.<X>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldarg.1 IL_0010: ldarg.2 IL_0011: call ""A..ctor(object, object)"" IL_0016: ret }"); verifier.VerifyIL("B..ctor(B)", @"{ // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""A..ctor(A)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object B.<Y>k__BackingField"" IL_000e: stfld ""object B.<Y>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object B.<X>k__BackingField"" IL_001a: stfld ""object B.<X>k__BackingField"" IL_001f: ret }"); verifier.VerifyIL("B.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 64 (0x40) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_003e IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: brfalse.s IL_003c IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""object B.<Y>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""object B.<Y>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0023: brfalse.s IL_003c IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_002a: ldarg.0 IL_002b: ldfld ""object B.<X>k__BackingField"" IL_0030: ldarg.1 IL_0031: ldfld ""object B.<X>k__BackingField"" IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_003b: ret IL_003c: ldc.i4.0 IL_003d: ret IL_003e: ldc.i4.1 IL_003f: ret }"); verifier.VerifyIL("B.GetHashCode()", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""object B.<Y>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_001c: add IL_001d: ldc.i4 0xa5555529 IL_0022: mul IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0028: ldarg.0 IL_0029: ldfld ""object B.<X>k__BackingField"" IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0033: add IL_0034: ret }"); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_36() { var source = @"using static System.Console; abstract record A { public abstract object X { get; init; } } abstract record B : A { public abstract object Y { get; init; } } record C(object X, object Y) : B; class Program { static void Main() { C c = new C(1, 2); B b = c; A a = c; WriteLine((c.X, c.Y)); WriteLine((b.X, b.Y)); WriteLine(a.X); var (x, y) = c; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.X { get; init; }", "System.Object C.Y { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"(1, 2) (1, 2) 1 (1, 2)").VerifyDiagnostics(); verifier.VerifyIL("A..ctor()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A..ctor(A)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("A.GetHashCode()", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type A.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ret }"); verifier.VerifyIL("B..ctor()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""A..ctor()"" IL_0006: ret }"); verifier.VerifyIL("B..ctor(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""A..ctor(A)"" IL_0007: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); verifier.VerifyIL("B.GetHashCode()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(object, object)", @"{ // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""object C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""object C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: call ""B..ctor()"" IL_0014: ret }"); verifier.VerifyIL("C..ctor(C)", @"{ // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<X>k__BackingField"" IL_000e: stfld ""object C.<X>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<Y>k__BackingField"" IL_001a: stfld ""object C.<Y>k__BackingField"" IL_001f: ret }"); verifier.VerifyIL("C.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object B.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 64 (0x40) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_003e IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_003c IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""object C.<X>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""object C.<X>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0023: brfalse.s IL_003c IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_002a: ldarg.0 IL_002b: ldfld ""object C.<Y>k__BackingField"" IL_0030: ldarg.1 IL_0031: ldfld ""object C.<Y>k__BackingField"" IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_003b: ret IL_003c: ldc.i4.0 IL_003d: ret IL_003e: ldc.i4.1 IL_003f: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int B.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""object C.<X>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_001c: add IL_001d: ldc.i4 0xa5555529 IL_0022: mul IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0028: ldarg.0 IL_0029: ldfld ""object C.<Y>k__BackingField"" IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0033: add IL_0034: ret }"); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_37() { var source = @"using static System.Console; abstract record A(object X, object Y) { public abstract object X { get; init; } public virtual object Y { get; init; } } abstract record B(object X, object Y) : A(X, Y) { public override abstract object X { get; init; } public override abstract object Y { get; init; } } record C(object X, object Y) : B(X, Y); class Program { static void Main() { C c = new C(1, 2); B b = c; A a = c; WriteLine((c.X, c.Y)); WriteLine((b.X, b.Y)); WriteLine((a.X, a.Y)); var (x, y) = c; WriteLine((x, y)); (x, y) = b; WriteLine((x, y)); (x, y) = a; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.X { get; init; }", "System.Object C.Y { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"(1, 2) (1, 2) (1, 2) (1, 2) (1, 2) (1, 2)").VerifyDiagnostics( // (2,26): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 26), // (2,36): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(2, 36) ); verifier.VerifyIL("A..ctor(object, object)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A..ctor(A)", @"{ // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""object A.<Y>k__BackingField"" IL_000d: stfld ""object A.<Y>k__BackingField"" IL_0012: ret }"); verifier.VerifyIL("A.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""object A.<Y>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""object A.<Y>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("A.GetHashCode()", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type A.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ldc.i4 0xa5555529 IL_0015: mul IL_0016: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""object A.<Y>k__BackingField"" IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0026: add IL_0027: ret }"); verifier.VerifyIL("B..ctor(object, object)", @"{ // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""A..ctor(object, object)"" IL_0008: ret }"); verifier.VerifyIL("B..ctor(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""A..ctor(A)"" IL_0007: ret }"); verifier.VerifyIL("B.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); verifier.VerifyIL("B.GetHashCode()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(object, object)", @"{ // Code size 23 (0x17) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""object C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""object C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldarg.1 IL_0010: ldarg.2 IL_0011: call ""B..ctor(object, object)"" IL_0016: ret }"); verifier.VerifyIL("C..ctor(C)", @"{ // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<X>k__BackingField"" IL_000e: stfld ""object C.<X>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<Y>k__BackingField"" IL_001a: stfld ""object C.<Y>k__BackingField"" IL_001f: ret }"); verifier.VerifyIL("C.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 64 (0x40) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_003e IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_003c IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""object C.<X>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""object C.<X>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0023: brfalse.s IL_003c IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_002a: ldarg.0 IL_002b: ldfld ""object C.<Y>k__BackingField"" IL_0030: ldarg.1 IL_0031: ldfld ""object C.<Y>k__BackingField"" IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_003b: ret IL_003c: ldc.i4.0 IL_003d: ret IL_003e: ldc.i4.1 IL_003f: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int B.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""object C.<X>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_001c: add IL_001d: ldc.i4 0xa5555529 IL_0022: mul IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0028: ldarg.0 IL_0029: ldfld ""object C.<Y>k__BackingField"" IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0033: add IL_0034: ret }"); } // Member in intermediate base that hides abstract property. Not supported. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_38() { var source = @"using static System.Console; abstract record A { public abstract object X { get; init; } public abstract object Y { get; init; } } abstract record B : A { public new void X() { } public new struct Y { } } record C(object X, object Y) : B; class Program { static void Main() { C c = new C(1, 2); A a = c; WriteLine((a.X, a.Y)); var (x, y) = c; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (9,21): error CS0533: 'B.X()' hides inherited abstract member 'A.X' // public new void X() { } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "X").WithArguments("B.X()", "A.X").WithLocation(9, 21), // (10,23): error CS0533: 'B.Y' hides inherited abstract member 'A.Y' // public new struct Y { } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Y").WithArguments("B.Y", "A.Y").WithLocation(10, 23), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.Y.get' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.Y.get").WithLocation(12, 8), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.X.get' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.X.get").WithLocation(12, 8), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.X.init' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.X.init").WithLocation(12, 8), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.Y.init' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.Y.init").WithLocation(12, 8), // (12,17): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'object' to match positional parameter 'X'. // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "object", "X").WithLocation(12, 17), // (12,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(object X, object Y) : B; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(12, 17), // (12,27): error CS8866: Record member 'B.Y' must be a readable instance property or field of type 'object' to match positional parameter 'Y'. // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("B.Y", "object", "Y").WithLocation(12, 27), // (12,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(object X, object Y) : B; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(12, 27)); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", }, GetProperties(comp, "C").ToTestDisplayStrings()); } // Member in intermediate base that hides abstract property. Not supported. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_39() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .property instance object P() { .get instance object A::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object) } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .method public abstract virtual instance object get_P() { } .method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } .class public abstract B extends A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void A::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class B A_1) { ldnull throw } .method public hidebysig specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .method public hidebysig instance object P() { ldnull ret } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"record CA(object P) : A; record CB(object P) : B; "; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,8): error CS0534: 'CB' does not implement inherited abstract member 'A.P.get' // record CB(object P) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "CB").WithArguments("CB", "A.P.get").WithLocation(2, 8), // (2,8): error CS0534: 'CB' does not implement inherited abstract member 'A.P.init' // record CB(object P) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "CB").WithArguments("CB", "A.P.init").WithLocation(2, 8), // (2,18): error CS8866: Record member 'B.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'. // record CB(object P) : B; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("B.P", "object", "P").WithLocation(2, 18), // (2,18): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record CB(object P) : B; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 18)); AssertEx.Equal(new[] { "System.Type CA.EqualityContract { get; }", "System.Object CA.P { get; init; }" }, GetProperties(comp, "CA").ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.Type CB.EqualityContract { get; }" }, GetProperties(comp, "CB").ToTestDisplayStrings()); } // Accessor names that do not match the property name. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_40() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::GetProperty1() } .property instance object P() { .get instance object A::GetProperty2() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::SetProperty2(object) } .method family virtual instance class [mscorlib]System.Type GetProperty1() { ldnull ret } .method public abstract virtual instance object GetProperty2() { } .method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) SetProperty2(object 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using static System.Console; record B(object P) : A { static void Main() { B b = new B(3); WriteLine(b.P); WriteLine(((A)b).P); b = new B(1) { P = 2 }; WriteLine(b.P); WriteLine(b.EqualityContract.Name); } }"; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"3 3 2 B").VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B"); Assert.Equal(2, actualMembers.Length); VerifyProperty(actualMembers[0], "System.Type B.EqualityContract { get; }", "GetProperty1", null); VerifyProperty(actualMembers[1], "System.Object B.P { get; init; }", "GetProperty2", "SetProperty2"); } // Accessor names that do not match the property name and are not valid C# names. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_41() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::'EqualityContract<>get'() } .property instance object P() { .get instance object A::'P<>get'() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::'P<>set'(object) } .method family virtual instance class [mscorlib]System.Type 'EqualityContract<>get'() { ldnull ret } .method public abstract virtual instance object 'P<>get'() { } .method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) 'P<>set'(object 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using static System.Console; record B(object P) : A { static void Main() { B b = new B(3); WriteLine(b.P); WriteLine(((A)b).P); b = new B(1) { P = 2 }; WriteLine(b.P); WriteLine(b.EqualityContract.Name); } }"; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"3 3 2 B").VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B"); Assert.Equal(2, actualMembers.Length); VerifyProperty(actualMembers[0], "System.Type B.EqualityContract { get; }", "EqualityContract<>get", null); VerifyProperty(actualMembers[1], "System.Object B.P { get; init; }", "P<>get", "P<>set"); } private static void VerifyProperty(Symbol symbol, string propertyDescription, string? getterName, string? setterName) { var property = (PropertySymbol)symbol; Assert.Equal(propertyDescription, symbol.ToTestDisplayString()); VerifyAccessor(property.GetMethod, getterName); VerifyAccessor(property.SetMethod, setterName); } private static void VerifyAccessor(MethodSymbol? accessor, string? name) { Assert.Equal(name, accessor?.Name); if (accessor is object) { Assert.True(accessor.HasSpecialName); foreach (var parameter in accessor.Parameters) { Assert.Same(accessor, parameter.ContainingSymbol); } } } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_42() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type modopt(int32) EqualityContract() { .get instance class [mscorlib]System.Type modopt(int32) A::get_EqualityContract() } .property instance object modopt(uint16) P() { .get instance object modopt(uint16) A::get_P() .set instance void modopt(uint8) modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object modopt(uint16)) } .method family virtual instance class [mscorlib]System.Type modopt(int32) get_EqualityContract() { ldnull ret } .method public abstract virtual instance object modopt(uint16) get_P() { } .method public abstract virtual instance void modopt(uint8) modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object modopt(uint16) 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using static System.Console; record B(object P) : A { static void Main() { B b = new B(3); WriteLine(b.P); WriteLine(((A)b).P); b = new B(1) { P = 2 }; WriteLine(b.P); WriteLine(b.EqualityContract.Name); } }"; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"3 3 2 B").VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B"); Assert.Equal(2, actualMembers.Length); var property = (PropertySymbol)actualMembers[0]; Assert.Equal("System.Type modopt(System.Int32) B.EqualityContract { get; }", property.ToTestDisplayString()); verifyReturnType(property.GetMethod, CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_Int32))); property = (PropertySymbol)actualMembers[1]; Assert.Equal("System.Object modopt(System.UInt16) B.P { get; init; }", property.ToTestDisplayString()); verifyReturnType(property.GetMethod, CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_UInt16))); verifyReturnType(property.SetMethod, CSharpCustomModifier.CreateRequired(comp.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsExternalInit)), CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_Byte))); verifyParameterType(property.SetMethod, CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_UInt16))); static void verifyReturnType(MethodSymbol method, params CustomModifier[] expectedModifiers) { var returnType = method.ReturnTypeWithAnnotations; Assert.True(method.OverriddenMethod.ReturnTypeWithAnnotations.Equals(returnType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); AssertEx.Equal(expectedModifiers, returnType.CustomModifiers); } static void verifyParameterType(MethodSymbol method, params CustomModifier[] expectedModifiers) { var parameterType = method.Parameters[0].TypeWithAnnotations; Assert.True(method.OverriddenMethod.Parameters[0].TypeWithAnnotations.Equals(parameterType, TypeCompareKind.ConsiderEverything)); AssertEx.Equal(expectedModifiers, parameterType.CustomModifiers); } } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_43() { var source = @"#nullable enable record A { protected virtual System.Type? EqualityContract => null; } record B : A { static void Main() { var b = new B(); _ = b.EqualityContract.ToString(); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); Assert.Equal("System.Type! B.EqualityContract { get; }", GetProperties(comp, "B").Single().ToTestDisplayString(includeNonNullable: true)); } // No EqualityContract property on base. [Fact] public void Inheritance_44() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { ldnull throw } .property instance object P() { .get instance object A::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object) } .method public instance object get_P() { ldnull ret } .method public instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object 'value') { ret } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"record B : A; "; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B : A; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [Theory, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [InlineData(false)] [InlineData(true)] public void CopyCtor(bool useCompilationReference) { var sourceA = @"public record B(object N1, object N2) { }"; var compA = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? sourceA : new[] { sourceA, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); var verifierA = CompileAndVerify(compA, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifierA.VerifyIL("B..ctor(B)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""object B.<N1>k__BackingField"" IL_000d: stfld ""object B.<N1>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""object B.<N2>k__BackingField"" IL_0019: stfld ""object B.<N2>k__BackingField"" IL_001e: ret }"); var refA = useCompilationReference ? compA.ToMetadataReference() : compA.EmitToImageReference(); var sourceB = @"record C(object P1, object P2) : B(3, 4) { static void Main() { var c1 = new C(1, 2); System.Console.Write((c1.P1, c1.P2, c1.N1, c1.N2)); System.Console.Write("" ""); var c2 = new C(c1); System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2)); System.Console.Write("" ""); var c3 = c1 with { P1 = 10, N1 = 30 }; System.Console.Write((c3.P1, c3.P2, c3.N1, c3.N2)); } }"; var compB = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? sourceB : new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, targetFramework: TargetFramework.StandardLatest); var verifierB = CompileAndVerify(compB, expectedOutput: "(1, 2, 3, 4) (1, 2, 3, 4) (10, 2, 30, 4)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); // call base copy constructor B..ctor(B) verifierB.VerifyIL("C..ctor(C)", @" { // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ret }"); verifierA.VerifyIL($"B.{WellKnownMemberNames.CloneMethodName}()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""B..ctor(B)"" IL_0006: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithOtherOverload() { var source = @"public record B(object N1, object N2) { public B(C c) : this(30, 40) => throw null; } public record C(object P1, object P2) : B(3, 4) { static void Main() { var c1 = new C(1, 2); System.Console.Write((c1.P1, c1.P2, c1.N1, c1.N2)); System.Console.Write("" ""); var c2 = c1 with { P1 = 10, P2 = 20, N1 = 30, N2 = 40 }; System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 3, 4) (10, 20, 30, 40)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); // call base copy constructor B..ctor(B) verifier.VerifyIL("C..ctor(C)", @" { // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithObsoleteCopyConstructor() { var source = @"public record B(object N1, object N2) { [System.Obsolete(""Obsolete"", true)] public B(B b) { } } public record C(object P1, object P2) : B(3, 4) { } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithParamsCopyConstructor() { var source = @"public record B(object N1, object N2) { public B(B b, params int[] i) : this(30, 40) { } } public record C(object P1, object P2) : B(3, 4) { } "; var comp = CreateCompilation(source); var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().Where(m => m.Name == ".ctor").ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Object N1, System.Object N2)", "B..ctor(B b, params System.Int32[] i)", "B..ctor(B original)" }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithInitializers() { var source = @"public record C(object N1, object N2) { private int field = 42; public int Property = 43; }"; var comp = CreateCompilation(source); var verifier = CompileAndVerify(comp, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics( // (3,17): warning CS0414: The field 'C.field' is assigned but its value is never used // private int field = 42; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C.field").WithLocation(3, 17) ); verifier.VerifyIL("C..ctor(C)", @" { // Code size 55 (0x37) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""object C.<N1>k__BackingField"" IL_000d: stfld ""object C.<N1>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""object C.<N2>k__BackingField"" IL_0019: stfld ""object C.<N2>k__BackingField"" IL_001e: ldarg.0 IL_001f: ldarg.1 IL_0020: ldfld ""int C.field"" IL_0025: stfld ""int C.field"" IL_002a: ldarg.0 IL_002b: ldarg.1 IL_002c: ldfld ""int C.Property"" IL_0031: stfld ""int C.Property"" IL_0036: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_NotInRecordType() { var source = @"public class C { public object Property { get; set; } public int field = 42; public C(C c) { } } public class D : C { public int field2 = 43; public D(D d) : base(d) { } } "; var comp = CreateCompilation(source); var verifier = CompileAndVerify(comp).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: stfld ""int C.field"" IL_0008: ldarg.0 IL_0009: call ""object..ctor()"" IL_000e: ret }"); verifier.VerifyIL("D..ctor(D)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 43 IL_0003: stfld ""int D.field2"" IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: call ""C..ctor(C)"" IL_000f: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor() { var source = @"public record B(object N1, object N2) { } public record C(object P1, object P2) : B(0, 1) { public C(C c) // 1, 2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,12): error CS1729: 'B' does not contain a constructor that takes 0 arguments // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(6, 12), // (6,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(6, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject() { var source = @"public record C(int I) { public int I { get; set; } = 42; public C(C c) { } public static void Main() { var c = new C(1); c.I = 2; var c2 = new C(c); System.Console.Write((c.I, c2.I)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(2, 0)").VerifyDiagnostics( // (1,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // public record C(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(1, 21) ); verifier.VerifyIL("C..ctor(C)", @" { // Code size 9 (0x9) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: nop IL_0008: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject_WithFieldInitializer() { var source = @"public record C(int I) { public int I { get; set; } = 42; public int field = 43; public C(C c) { System.Console.Write("" RAN ""); } public static void Main() { var c = new C(1); c.I = 2; c.field = 100; System.Console.Write((c.I, c.field)); var c2 = new C(c); System.Console.Write((c2.I, c2.field)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(2, 100) RAN (0, 0)").VerifyDiagnostics( // (1,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // public record C(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(1, 21) ); verifier.VerifyIL("C..ctor(C)", @" { // Code size 20 (0x14) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: nop IL_0008: ldstr "" RAN "" IL_000d: call ""void System.Console.Write(string)"" IL_0012: nop IL_0013: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_DerivesFromObject_GivesParameterToBase() { var source = @" public record C(object I) { public C(C c) : base(1) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS1729: 'object' does not contain a constructor that takes 1 arguments // public C(C c) : base(1) { } Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("object", "1").WithLocation(4, 21), // (4,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : base(1) { } Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(4, 21) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_DerivesFromObject_WithSomeOtherConstructor() { var source = @" public record C(object I) { public C(int i) : this((object)null) { } public static void Main() { var c = new C((object)null); var c2 = new C(1); var c3 = new C(c); System.Console.Write(""RAN""); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "RAN", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int)", @" { // Code size 10 (0xa) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldnull IL_0002: call ""C..ctor(object)"" IL_0007: nop IL_0008: nop IL_0009: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject_UsesThis() { var source = @"public record C(int I) { public C(C c) : this(c.I) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : this(c.I) Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(3, 21) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefined_DerivesFromObject_UsesBase() { var source = @"public record C(int I) { public C(C c) : base() { System.Console.Write(""RAN ""); } public static void Main() { var c = new C(1); System.Console.Write(c.I); System.Console.Write("" ""); var c2 = c with { I = 2 }; System.Console.Write(c2.I); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "1 RAN 2", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 20 (0x14) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: nop IL_0008: ldstr ""RAN "" IL_000d: call ""void System.Console.Write(string)"" IL_0012: nop IL_0013: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_NoPositionalMembers() { var source = @"public record B(object N1, object N2) { } public record C(object P1) : B(0, 1) { public C(C c) // 1, 2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,12): error CS1729: 'B' does not contain a constructor that takes 0 arguments // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(6, 12), // (6,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(6, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_UsesThis() { var source = @"public record B(object N1, object N2) { } public record C(object P1, object P2) : B(0, 1) { public C(C c) : this(1, 2) // 1 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : this(1, 2) // 1 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(6, 21) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_UsesBase() { var source = @"public record B(int i) { } public record C(int j) : B(0) { public C(C c) : base(1) // 1 { } } #nullable enable public record D(int j) : B(0) { public D(D? d) : base(1) // 2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : base(1) // 1 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(6, 21), // (13,22): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public D(D? d) : base(1) // 2 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(13, 22) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefined_WithFieldInitializers() { var source = @"public record C(int I) { } public record D(int J) : C(1) { public int field = 42; public D(D d) : base(d) { System.Console.Write(""RAN ""); } public static void Main() { var d = new D(2); System.Console.Write((d.I, d.J, d.field)); System.Console.Write("" ""); var d2 = d with { I = 10, J = 20 }; System.Console.Write((d2.I, d2.J, d.field)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 42) RAN (10, 20, 42)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("D..ctor(D)", @" { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C..ctor(C)"" IL_0007: nop IL_0008: nop IL_0009: ldstr ""RAN "" IL_000e: call ""void System.Console.Write(string)"" IL_0013: nop IL_0014: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_Synthesized_WithFieldInitializers() { var source = @"public record C(int I) { } public record D(int J) : C(1) { public int field = 42; public static void Main() { var d = new D(2); System.Console.Write((d.I, d.J, d.field)); System.Console.Write("" ""); var d2 = d with { I = 10, J = 20 }; System.Console.Write((d2.I, d2.J, d.field)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 42) (10, 20, 42)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("D..ctor(D)", @" { // Code size 33 (0x21) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C..ctor(C)"" IL_0007: nop IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: ldfld ""int D.<J>k__BackingField"" IL_000f: stfld ""int D.<J>k__BackingField"" IL_0014: ldarg.0 IL_0015: ldarg.1 IL_0016: ldfld ""int D.field"" IL_001b: stfld ""int D.field"" IL_0020: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButPrivate() { var source = @"public record B(object N1, object N2) { private B(B b) { } } public record C(object P1, object P2) : B(0, 1) { private C(C c) : base(2, 3) { } // 1 } public record D(object P1, object P2) : B(0, 1) { private D(D d) : base(d) { } // 2 } public record E(object P1, object P2) : B(0, 1); // 3 "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,13): error CS8878: A copy constructor 'B.B(B)' must be public or protected because the record is not sealed. // private B(B b) { } Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "B").WithArguments("B.B(B)").WithLocation(3, 13), // (7,13): error CS8878: A copy constructor 'C.C(C)' must be public or protected because the record is not sealed. // private C(C c) : base(2, 3) { } // 1 Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "C").WithArguments("C.C(C)").WithLocation(7, 13), // (7,22): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // private C(C c) : base(2, 3) { } // 1 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(7, 22), // (11,13): error CS8878: A copy constructor 'D.D(D)' must be public or protected because the record is not sealed. // private D(D d) : base(d) { } // 2 Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "D").WithArguments("D.D(D)").WithLocation(11, 13), // (11,22): error CS0122: 'B.B(B)' is inaccessible due to its protection level // private D(D d) : base(d) { } // 2 Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("B.B(B)").WithLocation(11, 22), // (13,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record E(object P1, object P2) : B(0, 1); // 3 Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "E").WithArguments("B").WithLocation(13, 15) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_InaccessibleToCaller() { var sourceA = @"public record B(object N1, object N2) { internal B(B b) { } }"; var compA = CreateCompilation(sourceA); compA.VerifyDiagnostics( // (3,14): error CS8878: A copy constructor 'B.B(B)' must be public or protected because the record is not sealed. // internal B(B b) { } Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "B").WithArguments("B.B(B)").WithLocation(3, 14) ); var refA = compA.ToMetadataReference(); var sourceB = @" record C(object P1, object P2) : B(3, 4); // 1 "; var compB = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (2,8): error CS8867: No accessible copy constructor found in base type 'B'. // record C(object P1, object P2) : B(3, 4); // 1 Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 8) ); var sourceC = @" record C(object P1, object P2) : B(3, 4) { protected C(C c) : base(c) { } // 1, 2 } "; var compC = CreateCompilation(sourceC, references: new[] { refA }, parseOptions: TestOptions.Regular9); compC.VerifyDiagnostics( // (4,24): error CS0122: 'B.B(B)' is inaccessible due to its protection level // protected C(C c) : base(c) { } // 1, 2 Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("B.B(B)").WithLocation(4, 24) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_InaccessibleToCallerFromPE_WithIVT() { var sourceA = @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""AssemblyB"")] internal record B(object N1, object N2) { public B(B b) { } }"; var compA = CreateCompilation(new[] { sourceA, IsExternalInitTypeDefinition }, assemblyName: "AssemblyA", parseOptions: TestOptions.Regular9); var refA = compA.EmitToImageReference(); var sourceB = @" record C(int j) : B(3, 4); "; var compB = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB"); compB.VerifyDiagnostics(); var sourceC = @" record C(int j) : B(3, 4) { protected C(C c) : base(c) { } } "; var compC = CreateCompilation(sourceC, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB"); compC.VerifyDiagnostics(); var compB2 = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB2"); compB2.VerifyEmitDiagnostics( // (2,8): error CS0115: 'C.ToString()': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'C.GetHashCode()': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'C.EqualityContract': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'C.Equals(object?)': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'C.PrintMembers(StringBuilder)': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,19): error CS0122: 'B' is inaccessible due to its protection level // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_BadAccess, "B").WithArguments("B").WithLocation(2, 19), // (2,20): error CS0122: 'B.B(object, object)' is inaccessible due to its protection level // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_BadAccess, "(3, 4)").WithArguments("B.B(object, object)").WithLocation(2, 20) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [WorkItem(45012, "https://github.com/dotnet/roslyn/issues/45012")] public void CopyCtor_UserDefinedButPrivate_InSealedType() { var source = @"public record B(int i) { } public sealed record C(int j) : B(0) { private C(C c) : base(c) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var copyCtor = comp.GetMembers("C..ctor")[1]; Assert.Equal("C..ctor(C c)", copyCtor.ToTestDisplayString()); Assert.True(copyCtor.DeclaredAccessibility == Accessibility.Private); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [WorkItem(45012, "https://github.com/dotnet/roslyn/issues/45012")] public void CopyCtor_UserDefinedButInternal() { var source = @"public record B(object N1, object N2) { } public sealed record Sealed(object P1, object P2) : B(0, 1) { internal Sealed(Sealed s) : base(s) { } } public record Unsealed(object P1, object P2) : B(0, 1) { internal Unsealed(Unsealed s) : base(s) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,14): error CS8878: A copy constructor 'Unsealed.Unsealed(Unsealed)' must be public or protected because the record is not sealed. // internal Unsealed(Unsealed s) : base(s) Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "Unsealed").WithArguments("Unsealed.Unsealed(Unsealed)").WithLocation(12, 14) ); var sealedCopyCtor = comp.GetMembers("Sealed..ctor")[1]; Assert.Equal("Sealed..ctor(Sealed s)", sealedCopyCtor.ToTestDisplayString()); Assert.True(sealedCopyCtor.DeclaredAccessibility == Accessibility.Internal); var unsealedCopyCtor = comp.GetMembers("Unsealed..ctor")[1]; Assert.Equal("Unsealed..ctor(Unsealed s)", unsealedCopyCtor.ToTestDisplayString()); Assert.True(unsealedCopyCtor.DeclaredAccessibility == Accessibility.Internal); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_BaseHasRefKind() { var source = @"public record B(int i) { public B(ref B b) => throw null; // 1, not recognized as copy constructor } public record C(int j) : B(1) { protected C(C c) : base(c) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public B(ref B b) => throw null; // 1, not recognized as copy constructor Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "B").WithLocation(3, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_BaseHasRefKind_WithThisInitializer() { var source = @"public record B(int i) { public B(ref B b) : this(0) => throw null; // 1, not recognized as copy constructor } public record C(int j) : B(1) { protected C(C c) : base(c) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().Where(m => m.Name == ".ctor").ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Int32 i)", "B..ctor(ref B b)", "B..ctor(B original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithPrivateField() { var source = @"public record B(object N1, object N2) { private int field1 = 100; public int GetField1() => field1; } public record C(object P1, object P2) : B(3, 4) { private int field2 = 200; public int GetField2() => field2; static void Main() { var c1 = new C(1, 2); var c2 = new C(c1); System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2, c2.GetField1(), c2.GetField2())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 3, 4, 100, 200)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 44 (0x2c) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ldarg.0 IL_0020: ldarg.1 IL_0021: ldfld ""int C.field2"" IL_0026: stfld ""int C.field2"" IL_002b: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_MissingInMetadata() { // IL for `public record B { }` var ilSource = @" .class public auto ansi beforefieldinit B extends [mscorlib]System.Object { .method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { IL_0000: ldnull IL_0001: throw } // Removed copy constructor //.method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15) ); var source2 = @" public record C : B { public C(C c) { } }"; var comp2 = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics( // (4,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) { } Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(4, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_InaccessibleInMetadata() { // IL for `public record B { }` var ilSource = @" .class public auto ansi beforefieldinit B extends [mscorlib]System.Object { .method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { IL_0000: ldnull IL_0001: throw } // Inaccessible copy constructor .method private hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15) ); } [Fact, WorkItem(45077, "https://github.com/dotnet/roslyn/issues/45077")] public void CopyCtor_AmbiguitiesInMetadata() { // IL for a minimal `public record B { }` with injected copy constructors var ilSource_template = @" .class public auto ansi beforefieldinit B extends [mscorlib]System.Object { INJECT .method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldarg.0 IL_0001: newobj instance void B::.ctor(class B) IL_0006: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C : B { public static void Main() { var c = new C(); _ = c with { }; } }"; // We're going to inject various copy constructors into record B (at INJECT marker), and check which one is used // by derived record C // The RAN and THROW markers are shorthands for method bodies that print "RAN" and throw, respectively. // .ctor(B) vs. .ctor(modopt B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW "); // .ctor(modopt B) alone verify(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed RAN "); // .ctor(B) vs. .ctor(modreq B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int64) '' ) cil managed THROW "); // .ctor(modopt B) vs. .ctor(modreq B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int64) '' ) cil managed THROW "); // .ctor(B) vs. .ctor(modopt1 B) and .ctor(modopt2 B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed THROW "); // .ctor(B) vs. .ctor(modopt1 B) and .ctor(modreq B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW .method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int32) '' ) cil managed THROW "); // .ctor(modeopt1 B) vs. .ctor(modopt2 B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed THROW ", isError: true); // private .ctor(B) vs. .ctor(modopt1 B) and .ctor(modopt B) verifyBoth(@" .method private hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed THROW ", isError: true); void verifyBoth(string inject1, string inject2, bool isError = false) { verify(inject1 + inject2, isError); verify(inject2 + inject1, isError); } void verify(string inject, bool isError = false) { var ranBody = @" { IL_0000: ldstr ""RAN"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } "; var throwBody = @" { IL_0000: ldnull IL_0001: throw } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource_template.Replace("INJECT", inject).Replace("RAN", ranBody).Replace("THROW", throwBody), parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var expectedDiagnostics = isError ? new[] { // (2,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record C : B Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15) } : new DiagnosticDescription[] { }; comp.VerifyDiagnostics(expectedDiagnostics); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics(); } } } [Fact, WorkItem(45077, "https://github.com/dotnet/roslyn/issues/45077")] public void CopyCtor_AmbiguitiesInMetadata_GenericType() { // IL for a minimal `public record B<T> { }` with modopt in nested position of parameter type var ilSource = @" .class public auto ansi beforefieldinit B`1<T> extends [mscorlib]System.Object implements class [mscorlib]System.IEquatable`1<class B`1<!T>> { .method family hidebysig specialname rtspecialname instance void .ctor ( class B`1<!T modopt(int64)> '' ) cil managed { IL_0000: ldstr ""RAN"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig specialname newslot virtual instance class B`1<!T> '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldarg.0 IL_0001: newobj instance void class B`1<!T>::.ctor(class B`1<!0>) IL_0006: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method public newslot virtual instance bool Equals ( class B`1<!T> '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B`1::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C<T> : B<T> { } public class Program { public static void Main() { var c = new C<string>(); _ = c with { }; } }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void CopyCtor_Accessibility_01(string accessibility) { var source = $@" record A(int X) {{ { accessibility } A(A a) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,6): error CS8878: A copy constructor 'A.A(A)' must be public or protected because the record is not sealed. // A(A a) Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "A").WithArguments("A.A(A)").WithLocation(4, 6 + accessibility.Length) ); } [Theory] [InlineData("public")] [InlineData("protected")] public void CopyCtor_Accessibility_02(string accessibility) { var source = $@" record A(int X) {{ { accessibility } A(A a) => System.Console.Write(""RAN""); public static void Main() {{ var a = new A(123); _ = a with {{}}; }} }} "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] [InlineData("public")] public void CopyCtor_Accessibility_03(string accessibility) { var source = $@" sealed record A(int X) {{ { accessibility } A(A a) => System.Console.Write(""RAN""); public static void Main() {{ var a = new A(123); _ = a with {{}}; }} }} "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics(); var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Theory] [InlineData("private protected")] [InlineData("internal protected")] [InlineData("protected")] public void CopyCtor_Accessibility_04(string accessibility) { var source = $@" sealed record A(int X) {{ { accessibility } A(A a) => System.Console.Write(""RAN""); public static void Main() {{ var a = new A(123); _ = a with {{}}; }} }} "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics( // (4,15): warning CS0628: 'A.A(A)': new protected member declared in sealed type // protected A(A a) Diagnostic(ErrorCode.WRN_ProtectedInSealed, "A").WithArguments("A.A(A)").WithLocation(4, 6 + accessibility.Length) ); var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Fact] public void CopyCtor_Signature_01() { var source = @" record A(int X) { public A(in A a) : this(-15) => System.Console.Write(""RAN""); public static void Main() { var a = new A(123); System.Console.Write((a with { }).X); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "123").VerifyDiagnostics(); } [Fact] public void Deconstruct_Simple() { var source = @"using System; record B(int X, int Y) { public static void Main() { M(new B(1, 2)); } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); var deconstruct = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("B.Deconstruct"); Assert.Equal(2, deconstruct.ParameterCount); Assert.Equal(RefKind.Out, deconstruct.Parameters[0].RefKind); Assert.Equal("X", deconstruct.Parameters[0].Name); Assert.Equal(RefKind.Out, deconstruct.Parameters[1].RefKind); Assert.Equal("Y", deconstruct.Parameters[1].Name); Assert.True(deconstruct.ReturnsVoid); Assert.False(deconstruct.IsVirtual); Assert.False(deconstruct.IsStatic); Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility); } [Fact] public void Deconstruct_PositionalAndNominalProperty() { var source = @"using System; record B(int X) { public int Y { get; init; } public static void Main() { M(new B(1)); } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal( "void B.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Nested() { var source = @"using System; record B(int X, int Y); record C(B B, int Z) { public static void Main() { M(new C(new B(1, 2), 3)); } static void M(C c) { switch (c) { case C(B(int x, int y), int z): Console.Write(x); Console.Write(y); Console.Write(z); break; } } } "; var verifier = CompileAndVerify(source, expectedOutput: "123"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""B C.B.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""int C.Z.get"" IL_000f: stind.i4 IL_0010: ret }"); } [Fact] public void Deconstruct_PropertyCollision() { var source = @"using System; record B(int X, int Y) { public int X => 3; static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "32"); verifier.VerifyDiagnostics( // (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14) ); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_01() { var source = @" record B(int X, int Y) { public int X() => 3; static void M(B b) { switch (b) { case B(int x, int y): break; } } static void Main() { M(new B(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS0102: The type 'B' already contains a definition for 'X' // public int X() => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("B", "X").WithLocation(4, 16) ); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_02() { var source = @" record B { public int X(int y) => y; } record C(int X, int Y) : B { static void M(C c) { switch (c) { case C(int x, int y): break; } } static void Main() { M(new C(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record C(int X, int Y) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "int", "X").WithLocation(7, 14), // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_03() { var source = @" using System; record B { public int X() => 3; } record C(int X, int Y) : B { public new int X { get; } static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "02"); verifier.VerifyDiagnostics( // (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_04() { var source = @" record C(int X, int Y) { public int X(int arg) => 3; static void M(C c) { switch (c) { case C(int x, int y): break; } } static void Main() { M(new C(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS0102: The type 'C' already contains a definition for 'X' // public int X(int arg) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(4, 16) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_FieldCollision() { var source = @" using System; record C(int X) { int X; static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(0)); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,10): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record C(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(4, 10), // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (6,9): warning CS0169: The field 'C.X' is never used // int X; Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("C.X").WithLocation(6, 9) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (6,9): warning CS0169: The field 'C.X' is never used // int X; Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("C.X").WithLocation(6, 9) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_EventCollision() { var source = @" using System; record C(Action X) { event Action X; static void M(C c) { switch (c) { case C(Action x): Console.Write(x); break; } } static void Main() { M(new C(() => { })); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS0102: The type 'C' already contains a definition for 'X' // event Action X; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(6, 18), // (6,18): warning CS0067: The event 'C.X' is never used // event Action X; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "X").WithArguments("C.X").WithLocation(6, 18) ); Assert.Equal( "void C.Deconstruct(out System.Action X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_WriteOnlyPropertyInBase() { var source = @" using System; record B { public int X { set { } } } record C(int X) : B { static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,14): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record C(int X) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "int", "X").WithLocation(9, 14), // (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14)); Assert.Equal( "void C.Deconstruct(out System.Int32 X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_PrivateWriteOnlyPropertyInBase() { var source = @" using System; record B { private int X { set { } } } record C(int X) : B { static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal( "void C.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty() { var source = @" record C { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); Assert.Null(comp.GetMember("C.Deconstruct")); } [Fact] public void Deconstruct_Inheritance_01() { var source = @" using System; record B(int X, int Y) { internal B() : this(0, 1) { } } record C : B { static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } switch (c) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "0101"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; Assert.Null(comp.GetMember("C.Deconstruct")); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Inheritance_02() { var source = @" using System; record B(int X, int Y) { // https://github.com/dotnet/roslyn/issues/44902 internal B() : this(0, 1) { } } record C(int X, int Y, int Z) : B(X, Y) { static void M(C c) { switch (c) { case C(int x, int y, int z): Console.Write(x); Console.Write(y); Console.Write(z); break; } switch (c) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(0, 1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "01201"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y, out System.Int32 Z)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Inheritance_03() { var source = @" using System; record B(int X, int Y) { internal B() : this(0, 1) { } } record C(int X, int Y) : B { static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } switch (c) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(0, 1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "0101"); verifier.VerifyDiagnostics( // (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14), // (9,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(9, 21) ); var comp = verifier.Compilation; Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Inheritance_04() { var source = @" using System; record A<T>(T P) { internal A() : this(default(T)) { } } record B1(int P, object Q) : A<int>(P) { internal B1() : this(0, null) { } } record B2(object P, object Q) : A<object>(P) { internal B2() : this(null, null) { } } record B3<T>(T P, object Q) : A<T>(P) { internal B3() : this(default, 0) { } } class C { static void M0(A<int> arg) { switch (arg) { case A<int>(int x): Console.Write(x); break; } } static void M1(B1 arg) { switch (arg) { case B1(int p, object q): Console.Write(p); Console.Write(q); break; } } static void M2(B2 arg) { switch (arg) { case B2(object p, object q): Console.Write(p); Console.Write(q); break; } } static void M3(B3<int> arg) { switch (arg) { case B3<int>(int p, object q): Console.Write(p); Console.Write(q); break; } } static void Main() { M0(new A<int>(0)); M1(new B1(1, 2)); M2(new B2(3, 4)); M3(new B3<int>(5, 6)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "0123456"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; Assert.Equal( "void A<T>.Deconstruct(out T P)", comp.GetMember("A.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B1.Deconstruct(out System.Int32 P, out System.Object Q)", comp.GetMember("B1.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B2.Deconstruct(out System.Object P, out System.Object Q)", comp.GetMember("B2.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B3<T>.Deconstruct(out T P, out System.Object Q)", comp.GetMember("B3.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Conversion_01() { var source = @" using System; record C(int X, int Y) { public long X { get; init; } public long Y { get; init; } static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(0, 1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,14): error CS8866: Record member 'C.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record C(int X, int Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("C.X", "int", "X").WithLocation(4, 14), // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (4,21): error CS8866: Record member 'C.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'. // record C(int X, int Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("C.Y", "int", "Y").WithLocation(4, 21), // (4,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(4, 21)); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Conversion_02() { var source = @" #nullable enable using System; record C(string? X, string Y) { public string X { get; init; } = null!; public string? Y { get; init; } static void M(C c) { switch (c) { case C(var x, string y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(""a"", ""b"")); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,18): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 18), // (5,28): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 28) ); Assert.Equal( "void C.Deconstruct(out System.String? X, out System.String Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Conversion_03() { var source = @" using System; class Base { } class Derived : Base { } record C(Derived X, Base Y) { public Base X { get; init; } public Derived Y { get; init; } static void M(C c) { switch (c) { case C(Derived x, Base y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(new Derived(), new Base())); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8866: Record member 'C.X' must be a readable instance property or field of type 'Derived' to match positional parameter 'X'. // record C(Derived X, Base Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("C.X", "Derived", "X").WithLocation(7, 18), // (7,18): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(Derived X, Base Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 18), // (7,26): error CS8866: Record member 'C.Y' must be a readable instance property or field of type 'Base' to match positional parameter 'Y'. // record C(Derived X, Base Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("C.Y", "Base", "Y").WithLocation(7, 26), // (7,26): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(Derived X, Base Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 26)); Assert.Equal( "void C.Deconstruct(out Derived X, out Base Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty_WithParameterList() { var source = @" record C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); Assert.Null(comp.GetMember("C.Deconstruct")); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_01() { var source = @"using System; record C() { public void Deconstruct() { } static void M(C c) { switch (c) { case C(): Console.Write(12); break; } } public static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_02() { var source = @"using System; record C() { public void Deconstruct(out int X, out int Y) { X = 1; Y = 2; } static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_03() { var source = @"using System; record C() { private void Deconstruct() { } static void M(C c) { switch (c) { case C(): Console.Write(12); break; } } public static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_04() { var source = @" record C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } public static void Deconstruct() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS0176: Member 'C.Deconstruct()' cannot be accessed with an instance reference; qualify it with a type name instead // case C(): Diagnostic(ErrorCode.ERR_ObjectProhibited, "()", isSuppressed: false).WithArguments("C.Deconstruct()").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_05() { var source = @" record C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } public int Deconstruct() { return 1; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); } [Fact] public void Deconstruct_UserDefined() { var source = @"using System; record B(int X, int Y) { public void Deconstruct(out int X, out int Y) { X = this.X + 1; Y = this.Y + 2; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(0, 0)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_01() { var source = @"using System; record B(int X, int Y) { public void Deconstruct(out int Z) { Z = X + Y; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } switch (b) { case B(int z): Console.Write(z); break; } } public static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "123"); verifier.VerifyDiagnostics(); var expectedSymbols = new[] { "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", "void B.Deconstruct(out System.Int32 Z)", }; Assert.Equal(expectedSymbols, verifier.Compilation.GetMembers("B.Deconstruct").Select(s => s.ToTestDisplayString(includeNonNullable: false))); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_02() { var source = @"using System; record B(int X) { public int Deconstruct(out int a) => throw null; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,16): error CS8874: Record member 'B.Deconstruct(out int)' must return 'void'. // public int Deconstruct(out int a) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Deconstruct").WithArguments("B.Deconstruct(out int)", "void").WithLocation(5, 16), // (11,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'B', with 1 out parameters and a void return type. // case B(int x): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int x)").WithArguments("B", "1").WithLocation(11, 19)); Assert.Equal("System.Int32 B.Deconstruct(out System.Int32 a)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_03() { var source = @"using System; record B(int X) { public void Deconstruct(int X) { } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); var expectedSymbols = new[] { "void B.Deconstruct(out System.Int32 X)", "void B.Deconstruct(System.Int32 X)", }; Assert.Equal(expectedSymbols, verifier.Compilation.GetMembers("B.Deconstruct").Select(s => s.ToTestDisplayString(includeNonNullable: false))); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_04() { var source = @"using System; record B(int X) { public void Deconstruct(ref int X) { } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS0663: 'B' cannot define an overloaded method that differs only on parameter modifiers 'ref' and 'out' // public void Deconstruct(ref int X) Diagnostic(ErrorCode.ERR_OverloadRefKind, "Deconstruct").WithArguments("B", "method", "ref", "out").WithLocation(5, 17) ); Assert.Equal(2, comp.GetMembers("B.Deconstruct").Length); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_05() { var source = @"using System; record A(int X) { public A() : this(0) { } public int Deconstruct(out int a, out int b) => throw null; } record B(int X, int Y) : A(X) { static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); Assert.Equal("void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_06() { var source = @"using System; record A(int X) { public A() : this(0) { } public virtual int Deconstruct(out int a, out int b) => throw null; } record B(int X, int Y) : A(X) { static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); Assert.Equal("void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void Deconstruct_UserDefined_Accessibility_07(string accessibility) { var source = $@" record A(int X) {{ { accessibility } void Deconstruct(out int a) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,11): error CS8873: Record member 'A.Deconstruct(out int)' must be public. // void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 11 + accessibility.Length) ); } [Fact] public void Deconstruct_UserDefined_Static_08() { var source = @" record A(int X) { public static void Deconstruct(out int a) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS8877: Record member 'A.Deconstruct(out int)' may not be static. // public static void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 24) ); } [Fact] public void Deconstruct_Shadowing_01() { var source = @" abstract record A(int X) { public abstract int Deconstruct(out int a, out int b); } abstract record B(int X, int Y) : A(X) { public static void Main() { } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,17): error CS0533: 'B.Deconstruct(out int, out int)' hides inherited abstract member 'A.Deconstruct(out int, out int)' // abstract record B(int X, int Y) : A(X) Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "B").WithArguments("B.Deconstruct(out int, out int)", "A.Deconstruct(out int, out int)").WithLocation(6, 17) ); } [Fact] public void Deconstruct_TypeMismatch_01() { var source = @" record A(int X) { public System.Type X => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record A(int X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 14), // (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14) ); } [Fact] public void Deconstruct_TypeMismatch_02() { var source = @" record A { public System.Type X => throw null; } record B(int X) : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (7,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record B(int X) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(7, 14), // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/45010")] [WorkItem(45010, "https://github.com/dotnet/roslyn/issues/45010")] public void Deconstruct_ObsoleteProperty() { var source = @"using System; record B(int X) { [Obsolete] int X { get; } = X; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal("void B.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/45009")] [WorkItem(45009, "https://github.com/dotnet/roslyn/issues/45009")] public void Deconstruct_RefProperty() { var source = @"using System; record B(int X) { static int _x = 2; ref int X => ref _x; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "2"); verifier.VerifyDiagnostics(); var deconstruct = verifier.Compilation.GetMember("B.Deconstruct"); Assert.Equal("void B.Deconstruct(out System.Int32 X)", deconstruct.ToTestDisplayString(includeNonNullable: false)); Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility); Assert.False(deconstruct.IsAbstract); Assert.False(deconstruct.IsVirtual); Assert.False(deconstruct.IsOverride); Assert.False(deconstruct.IsSealed); Assert.True(deconstruct.IsImplicitlyDeclared); } [Fact] public void Deconstruct_Static() { var source = @" using System; record B(int X, int Y) { static int Y { get; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS8866: Record member 'B.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'. // record B(int X, int Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("B.Y", "int", "Y").WithLocation(4, 21), // (4,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(4, 21)); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Theory] [InlineData(false)] [InlineData(true)] public void Overrides_01(bool usePreview) { var source = @"record A { public sealed override bool Equals(object other) => false; public sealed override int GetHashCode() => 0; public sealed override string ToString() => null; } record B(int X, int Y) : A { }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9); if (usePreview) { comp.VerifyDiagnostics( // (3,33): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public sealed override bool Equals(object other) => false; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 33), // (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed. // public sealed override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32), // (7,8): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // record B(int X, int Y) : A Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(7, 8) ); } else { comp.VerifyDiagnostics( // (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed. // public sealed override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32), // (5,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater. // public sealed override string ToString() => null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(5, 35), // (3,33): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public sealed override bool Equals(object other) => false; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 33), // (7,8): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // record B(int X, int Y) : A Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(7, 8) ); } var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Int32 X, System.Int32 Y)", "System.Type B.EqualityContract.get", "System.Type B.EqualityContract { get; }", "System.Int32 B.<X>k__BackingField", "System.Int32 B.X.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.X.init", "System.Int32 B.X { get; init; }", "System.Int32 B.<Y>k__BackingField", "System.Int32 B.Y.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Y.init", "System.Int32 B.Y { get; init; }", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", "A B." + WellKnownMemberNames.CloneMethodName + "()", "B..ctor(B original)", "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Overrides_02() { var source = @"abstract record A { public abstract override bool Equals(object other); public abstract override int GetHashCode(); public abstract override string ToString(); } record B(int X, int Y) : A { }"; var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? source : new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics( // (3,35): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public abstract override bool Equals(object other); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 35), // (7,8): error CS0534: 'B' does not implement inherited abstract member 'A.Equals(object)' // record B(int X, int Y) : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.Equals(object)").WithLocation(7, 8) ); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); string expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses ? "B B." + WellKnownMemberNames.CloneMethodName + "()" : "A B." + WellKnownMemberNames.CloneMethodName + "()"; var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Int32 X, System.Int32 Y)", "System.Type B.EqualityContract.get", "System.Type B.EqualityContract { get; }", "System.Int32 B.<X>k__BackingField", "System.Int32 B.X.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.X.init", "System.Int32 B.X { get; init; }", "System.Int32 B.<Y>k__BackingField", "System.Int32 B.Y.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Y.init", "System.Int32 B.Y { get; init; }", "System.String B.ToString()", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", expectedClone, "B..ctor(B original)", "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ObjectEquals_01() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public final hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0239: 'B.Equals(object?)': cannot override inherited member 'A.Equals(object)' because it is sealed // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.Equals(object?)", "A.Equals(object)").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_02() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public newslot hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.Equals(object?)' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.Equals(object?)").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_03() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public newslot hidebysig instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.Equals(object?)': cannot override inherited member 'A.Equals(object)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(object?)", "A.Equals(object)").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_04() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public newslot hidebysig virtual instance int32 Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.Equals(object?)': return type must be 'int' to match overridden member 'A.Equals(object)' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.Equals(object?)", "A.Equals(object)", "int").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_05() { var source0 = @"namespace System { public class Object { public virtual int Equals(object other) => default; public virtual int GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'A.Equals(object?)': return type must be 'int' to match overridden member 'object.Equals(object)' // public record A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "A").WithArguments("A.Equals(object?)", "object.Equals(object)", "int").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void ObjectEquals_06() { var source = @"record A { public static new bool Equals(object obj) => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,28): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public static new bool Equals(object obj) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 28) ); } [Fact] public void ObjectGetHashCode_01() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source1 = @" public record B : A { }"; var source2 = @" public record B : A { public override int GetHashCode() => 0; }"; var source3 = @" public record C : B { } "; var source4 = @" public record C : B { public override int GetHashCode() => 0; } "; var comp = CreateCompilationWithIL(new[] { source1, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15) ); comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25) ); comp = CreateCompilationWithIL(new[] { source1 + source3, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15) ); comp = CreateCompilationWithIL(new[] { source1 + source4, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15) ); comp = CreateCompilationWithIL(new[] { source2 + source3, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25) ); comp = CreateCompilationWithIL(new[] { source2 + source4, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_02() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source1 = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source1, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(2, 15) ); var source2 = @" public record B : A { public override int GetHashCode() => throw null; }"; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override // public override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_03() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance bool GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.GetHashCode()': return type must be 'bool' to match overridden member 'A.GetHashCode()' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()", "bool").WithLocation(2, 15) ); var source2 = @" public record B : A { public override int GetHashCode() => throw null; }"; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS0508: 'B.GetHashCode()': return type must be 'bool' to match overridden member 'A.GetHashCode()' // public override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()", "bool").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_04() { var source = @"record A { public override bool GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,26): error CS0508: 'A.GetHashCode()': return type must be 'int' to match overridden member 'object.GetHashCode()' // public override bool GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GetHashCode").WithArguments("A.GetHashCode()", "object.GetHashCode()", "int").WithLocation(3, 26) ); } [Fact] public void ObjectGetHashCode_05() { var source = @"record A { public new int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,20): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public new int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 20) ); } [Fact] public void ObjectGetHashCode_06() { var source = @"record A { public static new int GetHashCode() => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,27): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public static new int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 27), // (6,8): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(6, 8) ); } [Fact] public void ObjectGetHashCode_07() { var source = @"record A { public new int GetHashCode => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,20): error CS0102: The type 'A' already contains a definition for 'GetHashCode' // public new int GetHashCode => throw null; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "GetHashCode").WithArguments("A", "GetHashCode").WithLocation(3, 20) ); } [Fact] public void ObjectGetHashCode_08() { var source = @"record A { public new void GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,21): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public new void GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 21) ); } [Fact] public void ObjectGetHashCode_09() { var source = @"record A { public void GetHashCode(int x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); Assert.Equal("System.Int32 A.GetHashCode()", comp.GetMembers("A.GetHashCode").First().ToTestDisplayString()); } [Fact] public void ObjectGetHashCode_10() { var source = @" record A { public sealed override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed. // public sealed override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32) ); } [Fact] public void ObjectGetHashCode_11() { var source = @" sealed record A { public sealed override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] public void ObjectGetHashCode_12() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public final hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(2, 15) ); var source2 = @" public record B : A { public override int GetHashCode() => throw null; }"; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // public override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantOverrideSealed, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_13() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance class A GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source2 = @" public record B : A { public override A GetHashCode() => default; }"; var comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,23): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override A GetHashCode() => default; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 23) ); } [Fact] public void ObjectGetHashCode_14() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance class A GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source2 = @" public record B : A { public override B GetHashCode() => default; }"; var comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,23): error CS8830: 'B.GetHashCode()': Target runtime doesn't support covariant return types in overrides. Return type must be 'A' to match overridden member 'A.GetHashCode()' // public override B GetHashCode() => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()", "A").WithLocation(3, 23) ); } [Fact] public void ObjectGetHashCode_15() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual Something GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } public class Something { } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { public override Something GetHashCode() => default; } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,31): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public override Something GetHashCode() => default; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 31), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void ObjectGetHashCode_16() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual bool GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { public override bool GetHashCode() => default; } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,26): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public override bool GetHashCode() => default; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 26), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void ObjectGetHashCode_17() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual bool GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'A.GetHashCode()': return type must be 'bool' to match overridden member 'object.GetHashCode()' // public record A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "A").WithArguments("A.GetHashCode()", "object.GetHashCode()", "bool").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void BaseEquals_01() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(2, 15) ); } [Fact] public void BaseEquals_02() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(2, 15) ); } [Fact] public void BaseEquals_03() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance int32 Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.Equals(A?)': return type must be 'int' to match overridden member 'A.Equals(A)' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.Equals(A?)", "A.Equals(A)", "int").WithLocation(2, 15) ); } [Fact] public void BaseEquals_04() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A .class public auto ansi beforefieldinit B extends A { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class B "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8871: 'C.Equals(B?)' does not override expected method from 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "C").WithArguments("C.Equals(B?)", "B").WithLocation(2, 15) ); } [Fact] public void BaseEquals_05() { var source = @" record A { } record B : A { public override bool Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (8,26): error CS0111: Type 'B' already defines a member called 'Equals' with the same parameter types // public override bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "B").WithLocation(8, 26) ); } [Fact] public void RecordEquals_01() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(A x); } record B : A { public virtual bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False ").VerifyDiagnostics( // (5,26): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public abstract bool Equals(A x); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 26), // (9,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25) ); } [Fact] public void RecordEquals_02() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } record B : A { public override bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False ").VerifyDiagnostics( // (9,26): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 26) ); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_03() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } record B : A { public sealed override bool Equals(B other) => Report(""B.Equals(B)""); } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (9,33): error CS8872: 'B.Equals(B)' must allow overriding because the containing record is not sealed. // public sealed override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("B.Equals(B)").WithLocation(9, 33), // (9,33): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public sealed override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 33) ); } [Fact] public void RecordEquals_04() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } sealed record B : A { public sealed override bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False ").VerifyDiagnostics( // (9,33): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public sealed override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 33) ); var copyCtor = comp.GetMember<NamedTypeSymbol>("A").InstanceConstructors.Where(c => c.ParameterCount == 1).Single(); Assert.Equal(Accessibility.Protected, copyCtor.DeclaredAccessibility); Assert.False(copyCtor.IsOverride); Assert.False(copyCtor.IsVirtual); Assert.False(copyCtor.IsAbstract); Assert.False(copyCtor.IsSealed); Assert.True(copyCtor.IsImplicitlyDeclared); copyCtor = comp.GetMember<NamedTypeSymbol>("B").InstanceConstructors.Where(c => c.ParameterCount == 1).Single(); Assert.Equal(Accessibility.Private, copyCtor.DeclaredAccessibility); Assert.False(copyCtor.IsOverride); Assert.False(copyCtor.IsVirtual); Assert.False(copyCtor.IsAbstract); Assert.False(copyCtor.IsSealed); Assert.True(copyCtor.IsImplicitlyDeclared); } [Fact] public void RecordEquals_05() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } abstract record B : A { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (7,17): error CS0533: 'B.Equals(B?)' hides inherited abstract member 'A.Equals(B)' // abstract record B : A Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "B").WithArguments("B.Equals(B?)", "A.Equals(B)").WithLocation(7, 17) ); var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_06(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } " + modifiers + @" record B : A { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (8,8): error CS0534: 'B' does not implement inherited abstract member 'A.Equals(B)' // record B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.Equals(B)").WithLocation(8, 8) ); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_07(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public virtual bool Equals(B x) => Report(""A.Equals(B)""); } " + modifiers + @" record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" A.Equals(B) False True True ").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_08(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(C x); } abstract record B : A { public override bool Equals(C x) => Report(""B.Equals(C)""); } " + modifiers + @" record C : B { } class Program { static void Main() { A a1 = new C(); C c2 = new C(); System.Console.WriteLine(a1.Equals(c2)); System.Console.WriteLine(c2.Equals(a1)); System.Console.WriteLine(c2.Equals((C)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(C) False True True ").VerifyDiagnostics(); var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); clone = comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); clone = comp.GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_09(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public bool Equals(B x) => Report(""A.Equals(B)""); } " + modifiers + @" record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" A.Equals(B) False True True ").VerifyDiagnostics(); } [Theory] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void RecordEquals_10(string accessibility) { var source = $@" record A {{ { accessibility } virtual bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS8873: Record member 'A.Equals(A)' must be public. // { accessibility } virtual bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length), // (4,...): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // { accessibility } virtual bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 19 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("private")] public void RecordEquals_11(string accessibility) { var source = $@" record A {{ { accessibility } virtual bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS0621: 'A.Equals(A)': virtual or abstract members cannot be private // virtual bool Equals(A x) Diagnostic(ErrorCode.ERR_VirtualPrivate, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length), // (4,...): error CS8873: Record member 'A.Equals(A)' must be public. // { accessibility } virtual bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length), // (4,...): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // virtual bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 19 + accessibility.Length) ); } [Fact] public void RecordEquals_12() { var source = @" record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public virtual bool Equals(B other) => Report(""A.Equals(B)""); } class B { } class Program { static void Main() { A a1 = new A(); A a2 = new A(); System.Console.WriteLine(a1.Equals(a2)); System.Console.WriteLine(a1.Equals((object)a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_13() { var source = @" record A { public virtual int Equals(A other) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,24): error CS8874: Record member 'A.Equals(A)' must return 'bool'. // public virtual int Equals(A other) Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual int Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void RecordEquals_14() { var source = @" record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (4,20): error CS0518: Predefined type 'System.Boolean' is not defined or imported // public virtual bool Equals(A other) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(4, 20), // (4,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 25) ); } [Fact] public void RecordEquals_15() { var source = @" record A { public virtual Boolean Equals(A other) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,20): error CS0246: The type or namespace name 'Boolean' could not be found (are you missing a using directive or an assembly reference?) // public virtual Boolean Equals(A other) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Boolean").WithArguments("Boolean").WithLocation(4, 20), // (4,28): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual Boolean Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 28) ); } [Fact] public void RecordEquals_16() { var source = @" abstract record A { } record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_17() { var source = @" abstract record A { } sealed record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.False(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_18() { var source = @" sealed record A { } class Program { static void Main() { A a1 = new A(); A a2 = new A(); System.Console.WriteLine(a1.Equals(a2)); System.Console.WriteLine(a2.Equals(a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.False(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_19() { var source = @" record A { public static bool Equals(A x) => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,8): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 8), // (4,24): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed. // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24), // (7,8): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(7, 8) ); } [Fact] public void RecordEquals_20() { var source = @" sealed record A { public static bool Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static. // sealed record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 15), // (4,24): error CS8877: Record member 'A.Equals(A)' may not be static. // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void EqualityContract_01() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected abstract System.Type EqualityContract { get; } } record B : A { protected override System.Type EqualityContract { get { Report(""B.EqualityContract""); return typeof(B); } } } class Program { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.EqualityContract B.EqualityContract True ").VerifyDiagnostics(); } [Fact] public void EqualityContract_02() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected abstract System.Type EqualityContract { get; } } record B : A { protected sealed override System.Type EqualityContract { get { Report(""B.EqualityContract""); return typeof(B); } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (9,43): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed. // protected sealed override System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(9, 43) ); } [Fact] public void EqualityContract_03() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected abstract System.Type EqualityContract { get; } } sealed record B : A { protected sealed override System.Type EqualityContract { get { Report(""B.EqualityContract""); return typeof(B); } } } class Program { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.EqualityContract B.EqualityContract True ").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("sealed ")] public void EqualityContract_04(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected virtual System.Type EqualityContract { get { Report(""A.EqualityContract""); return typeof(B); } } } " + modifiers + @" record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True True ").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.True(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); var equalityContractGet = equalityContract.GetMethod; Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContractGet!.DeclaredAccessibility); Assert.False(equalityContractGet.IsAbstract); Assert.False(equalityContractGet.IsVirtual); Assert.True(equalityContractGet.IsOverride); Assert.False(equalityContractGet.IsSealed); Assert.True(equalityContractGet.IsImplicitlyDeclared); Assert.Empty(equalityContractGet.DeclaringSyntaxReferences); } [Theory] [InlineData("public")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void EqualityContract_05(string accessibility) { var source = $@" record A {{ { accessibility } virtual System.Type EqualityContract => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS8875: Record member 'A.EqualityContract' must be protected. // { accessibility } virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("private")] public void EqualityContract_06(string accessibility) { var source = $@" record A {{ { accessibility } virtual System.Type EqualityContract => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS0621: 'A.EqualityContract': virtual or abstract members cannot be private // { accessibility } virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_VirtualPrivate, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length), // (4,...): error CS8875: Record member 'A.EqualityContract' must be protected. // { accessibility } virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("abstract ")] [InlineData("sealed ")] public void EqualityContract_07(string modifiers) { var source = @" record A { } " + modifiers + @" record B : A { public void PrintEqualityContract() => System.Console.WriteLine(EqualityContract); } "; if (modifiers != "abstract ") { source += @" class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); b2.PrintEqualityContract(); } }"; } var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: modifiers == "abstract " ? TestOptions.ReleaseDll : TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: modifiers == "abstract " ? null : @" True True True B ").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.True(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); var equalityContractGet = equalityContract.GetMethod; Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContractGet!.DeclaredAccessibility); Assert.False(equalityContractGet.IsAbstract); Assert.False(equalityContractGet.IsVirtual); Assert.True(equalityContractGet.IsOverride); Assert.False(equalityContractGet.IsSealed); Assert.True(equalityContractGet.IsImplicitlyDeclared); Assert.Empty(equalityContractGet.DeclaringSyntaxReferences); verifier.VerifyIL("B.EqualityContract.get", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""B"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret } "); } [Theory] [InlineData("")] [InlineData("abstract ")] [InlineData("sealed ")] public void EqualityContract_08(string modifiers) { var source = modifiers + @" record B { public void PrintEqualityContract() => System.Console.WriteLine(EqualityContract); } "; if (modifiers != "abstract ") { source += @" class Program { static void Main() { B a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); b2.PrintEqualityContract(); } }"; } var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: modifiers == "abstract " ? TestOptions.ReleaseDll : TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: modifiers == "abstract " ? null : @" True True True B ").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(modifiers == "sealed " ? Accessibility.Private : Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.Equal(modifiers != "sealed ", equalityContract.IsVirtual); Assert.False(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); var equalityContractGet = equalityContract.GetMethod; Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(modifiers == "sealed " ? Accessibility.Private : Accessibility.Protected, equalityContractGet!.DeclaredAccessibility); Assert.False(equalityContractGet.IsAbstract); Assert.Equal(modifiers != "sealed ", equalityContractGet.IsVirtual); Assert.False(equalityContractGet.IsOverride); Assert.False(equalityContractGet.IsSealed); Assert.True(equalityContractGet.IsImplicitlyDeclared); Assert.Empty(equalityContractGet.DeclaringSyntaxReferences); verifier.VerifyIL("B.EqualityContract.get", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""B"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret } "); } [Fact] public void EqualityContract_09() { var source = @" record A { protected virtual int EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,27): error CS8874: Record member 'A.EqualityContract' must return 'Type'. // protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("A.EqualityContract", "System.Type").WithLocation(4, 27) ); } [Fact] public void EqualityContract_10() { var source = @" record A { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeTypeMissing(WellKnownType.System_Type); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // record A Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record A { }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // record A Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record A { }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 8) ); } [Fact] public void EqualityContract_11() { var source = @" record A { protected virtual Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,23): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(4, 23) ); } [Fact] public void EqualityContract_12() { var source = @" record A { protected System.Type EqualityContract => throw null; } sealed record B { protected System.Type EqualityContract => throw null; } sealed record C { protected virtual System.Type EqualityContract => throw null; } record D { protected virtual System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,27): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 27), // (10,27): warning CS0628: 'B.EqualityContract': new protected member declared in sealed type // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(10, 27), // (10,27): error CS8879: Record member 'B.EqualityContract' must be private. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(10, 27), // (11,12): warning CS0628: 'B.EqualityContract.get': new protected member declared in sealed type // => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("B.EqualityContract.get").WithLocation(11, 12), // (16,35): warning CS0628: 'C.EqualityContract': new protected member declared in sealed type // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(16, 35), // (16,35): error CS8879: Record member 'C.EqualityContract' must be private. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(16, 35), // (17,12): error CS0549: 'C.EqualityContract.get' is a new virtual member in sealed type 'C' // => throw null; Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "throw null").WithArguments("C.EqualityContract.get", "C").WithLocation(17, 12) ); } [Fact] public void EqualityContract_13() { var source = @" record A {} record B : A { protected System.Type EqualityContract => throw null; } sealed record C : A { protected System.Type EqualityContract => throw null; } sealed record D : A { protected virtual System.Type EqualityContract => throw null; } record E : A { protected virtual System.Type EqualityContract => throw null; } record F : A { protected override System.Type EqualityContract => throw null; } record G : A { protected sealed override System.Type EqualityContract => throw null; } sealed record H : A { protected sealed override System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (7,27): error CS8876: 'B.EqualityContract' does not override expected property from 'A'. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("B.EqualityContract", "A").WithLocation(7, 27), // (7,27): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(7, 27), // (7,27): warning CS0114: 'B.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(7, 27), // (13,27): warning CS0628: 'C.EqualityContract': new protected member declared in sealed type // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(13, 27), // (13,27): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(13, 27), // (13,27): warning CS0114: 'C.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("C.EqualityContract", "A.EqualityContract").WithLocation(13, 27), // (14,12): warning CS0628: 'C.EqualityContract.get': new protected member declared in sealed type // => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("C.EqualityContract.get").WithLocation(14, 12), // (19,35): warning CS0628: 'D.EqualityContract': new protected member declared in sealed type // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("D.EqualityContract").WithLocation(19, 35), // (19,35): error CS8876: 'D.EqualityContract' does not override expected property from 'A'. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("D.EqualityContract", "A").WithLocation(19, 35), // (19,35): warning CS0114: 'D.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("D.EqualityContract", "A.EqualityContract").WithLocation(19, 35), // (20,12): error CS0549: 'D.EqualityContract.get' is a new virtual member in sealed type 'D' // => throw null; Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "throw null").WithArguments("D.EqualityContract.get", "D").WithLocation(20, 12), // (25,35): error CS8876: 'E.EqualityContract' does not override expected property from 'A'. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("E.EqualityContract", "A").WithLocation(25, 35), // (25,35): warning CS0114: 'E.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("E.EqualityContract", "A.EqualityContract").WithLocation(25, 35), // (37,43): error CS8872: 'G.EqualityContract' must allow overriding because the containing record is not sealed. // protected sealed override System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("G.EqualityContract").WithLocation(37, 43) ); } [Fact] public void EqualityContract_14() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { } public record C : A { new protected virtual System.Type EqualityContract => throw null; } public record D : A { new protected virtual int EqualityContract => throw null; } public record E : A { new protected virtual Type EqualityContract => throw null; } public record F : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(2, 15), // (6,39): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // new protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 39), // (11,31): error CS8874: Record member 'D.EqualityContract' must return 'Type'. // new protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 31), // (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // new protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27), // (21,36): error CS0506: 'F.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "EqualityContract").WithArguments("F.EqualityContract", "A.EqualityContract").WithLocation(21, 36) ); } [Fact] public void EqualityContract_15() { var source = @" record A { protected virtual int EqualityContract => throw null; } record B : A { } record C : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,27): error CS8874: Record member 'A.EqualityContract' must return 'Type'. // protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("A.EqualityContract", "System.Type").WithLocation(4, 27), // (8,8): error CS1715: 'B.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract' // record B : A Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "B").WithArguments("B.EqualityContract", "A.EqualityContract", "int").WithLocation(8, 8), // (14,36): error CS1715: 'C.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract' // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "EqualityContract").WithArguments("C.EqualityContract", "A.EqualityContract", "int").WithLocation(14, 36) ); } [Fact] public void EqualityContract_16() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot final virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { } public record C : A { new protected virtual System.Type EqualityContract => throw null; } public record D : A { new protected virtual int EqualityContract => throw null; } public record E : A { new protected virtual Type EqualityContract => throw null; } public record F : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(2, 15), // (6,39): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // new protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 39), // (11,31): error CS8874: Record member 'D.EqualityContract' must return 'Type'. // new protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 31), // (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // new protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27), // (21,36): error CS0506: 'F.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "EqualityContract").WithArguments("F.EqualityContract", "A.EqualityContract").WithLocation(21, 36) ); } [Fact] public void EqualityContract_17() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { } public record C : A { protected virtual System.Type EqualityContract => throw null; } public record D : A { protected virtual int EqualityContract => throw null; } public record E : A { protected virtual Type EqualityContract => throw null; } public record F : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0115: 'B.EqualityContract': no suitable method found to override // public record B : A { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(2, 15), // (6,35): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 35), // (11,27): error CS8874: Record member 'D.EqualityContract' must return 'Type'. // protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 27), // (16,23): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 23), // (21,36): error CS0115: 'F.EqualityContract': no suitable method found to override // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_OverrideNotExpected, "EqualityContract").WithArguments("F.EqualityContract").WithLocation(21, 36) ); } [Fact] public void EqualityContract_18() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A .class public auto ansi beforefieldinit B extends A { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class B "; var source = @" public record C : B { } public record D : B { new protected virtual System.Type EqualityContract => throw null; } public record E : B { new protected virtual int EqualityContract => throw null; } public record F : B { new protected virtual Type EqualityContract => throw null; } public record G : B { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8876: 'C.EqualityContract' does not override expected property from 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "C").WithArguments("C.EqualityContract", "B").WithLocation(2, 15), // (6,39): error CS8876: 'D.EqualityContract' does not override expected property from 'B'. // new protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("D.EqualityContract", "B").WithLocation(6, 39), // (11,31): error CS8874: Record member 'E.EqualityContract' must return 'Type'. // new protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("E.EqualityContract", "System.Type").WithLocation(11, 31), // (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // new protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27), // (21,36): error CS8876: 'G.EqualityContract' does not override expected property from 'B'. // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("G.EqualityContract", "B").WithLocation(21, 36) ); } [Fact] public void EqualityContract_19() { var source = @"sealed record A { protected static System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,34): warning CS0628: 'A.EqualityContract': new protected member declared in sealed type // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34), // (3,34): error CS8879: Record member 'A.EqualityContract' must be private. // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34), // (3,34): error CS8877: Record member 'A.EqualityContract' may not be static. // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34), // (3,54): warning CS0628: 'A.EqualityContract.get': new protected member declared in sealed type // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("A.EqualityContract.get").WithLocation(3, 54) ); } [Fact] public void EqualityContract_20() { var source = @"sealed record A { private static System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,32): error CS8877: Record member 'A.EqualityContract' may not be static. // private static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 32) ); } [Fact] public void EqualityContract_21() { var source = @" sealed record A { static void Main() { A a1 = new A(); A a2 = new A(); System.Console.WriteLine(a1.Equals(a2)); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "True").VerifyDiagnostics(); var equalityContract = comp.GetMembers("A.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type A.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Private, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.False(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); } [Fact] public void EqualityContract_22() { var source = @" record A; sealed record B : A { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "True").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.True(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); } [Fact] public void EqualityContract_23() { var source = @" record A { protected static System.Type EqualityContract => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,34): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed. // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 34), // (7,8): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(7, 8) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_24_SetterOnlyProperty() { var src = @" record R { protected virtual System.Type EqualityContract { set { } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,35): error CS8906: Record equality contract property 'R.EqualityContract' must have a get accessor. // protected virtual System.Type EqualityContract { set { } } Diagnostic(ErrorCode.ERR_EqualityContractRequiresGetter, "EqualityContract").WithArguments("R.EqualityContract").WithLocation(4, 35) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_24_GetterAndSetterProperty() { var src = @" _ = new R() == new R2(); record R { protected virtual System.Type EqualityContract { get { System.Console.Write(""RAN ""); return GetType(); } set { } } } record R2 : R; "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_25_SetterOnlyProperty_DerivedRecord() { var src = @" record Base; record R : Base { protected override System.Type EqualityContract { set { } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,36): error CS8906: Record equality contract property 'R.EqualityContract' must have a get accessor. // protected override System.Type EqualityContract { set { } } Diagnostic(ErrorCode.ERR_EqualityContractRequiresGetter, "EqualityContract").WithArguments("R.EqualityContract").WithLocation(5, 36), // (5,55): error CS0546: 'R.EqualityContract.set': cannot override because 'Base.EqualityContract' does not have an overridable set accessor // protected override System.Type EqualityContract { set { } } Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("R.EqualityContract.set", "Base.EqualityContract").WithLocation(5, 55) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_26_SetterOnlyProperty_InMetadata() { // `record Base;` with modified EqualityContract property, method bodies simplified and nullability removed var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object implements class [mscorlib]System.IEquatable`1<class Base> { .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance bool PrintMembers( class [mscorlib] System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Inequality( class Base r1, class Base r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Equality( class Base r1, class Base r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals( object obj ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance bool Equals( class Base other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance class Base '<Clone>$'() cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class Base original ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname newslot virtual instance void set_EqualityContract ( class [mscorlib]System.Type 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } // Property has a setter but no getter .property instance class [mscorlib]System.Type EqualityContract() { .set instance void Base::set_EqualityContract(class [mscorlib]System.Type) } } "; var src = @" record R : Base; "; var comp = CreateCompilationWithIL(src, il); comp.VerifyEmitDiagnostics( // (2,8): error CS0545: 'R.EqualityContract.get': cannot override because 'Base.EqualityContract' does not have an overridable get accessor // record R : Base; Diagnostic(ErrorCode.ERR_NoGetToOverride, "R").WithArguments("R.EqualityContract.get", "Base.EqualityContract").WithLocation(2, 8) ); var src2 = @" record R : Base { protected override System.Type EqualityContract => typeof(R); } "; var comp2 = CreateCompilationWithIL(src2, il); comp2.VerifyEmitDiagnostics( // (4,56): error CS0545: 'R.EqualityContract.get': cannot override because 'Base.EqualityContract' does not have an overridable get accessor // protected override System.Type EqualityContract => typeof(R); Diagnostic(ErrorCode.ERR_NoGetToOverride, "typeof(R)").WithArguments("R.EqualityContract.get", "Base.EqualityContract").WithLocation(4, 56) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_27_GetterAndSetterProperty_ExplicitlyOverridden() { var src = @" _ = new R() == new R2(); record R { protected virtual System.Type EqualityContract { get { System.Console.Write(""RAN ""); return GetType(); } set { } } } record R2 : R { protected override System.Type EqualityContract { get { System.Console.Write(""RAN2 ""); return GetType(); } } } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN RAN2"); } [Fact] public void EqualityOperators_01() { var source = @" record A(int X) { public virtual bool Equals(ref A other) => throw null; static void Main() { Test(null, null); Test(null, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); Test(new A(4), new B(4, 5)); Test(new B(6, 7), new B(6, 7)); Test(new B(8, 9), new B(8, 10)); var a = new A(11); Test(a, a); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } record B(int X, int Y) : A(X); "; var verifier = CompileAndVerify(source, expectedOutput: @" True True False False False False True True True True False False False False True True False False True True True True False False False False True True True True False False ").VerifyDiagnostics(); var comp = (CSharpCompilation)verifier.Compilation; MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(); Assert.Equal("System.Boolean A.op_Equality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single(); Assert.Equal("System.Boolean A.op_Inequality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); verifier.VerifyIL("bool A.op_Equality(A, A)", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0011 IL_0004: ldarg.0 IL_0005: brfalse.s IL_000f IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: callvirt ""bool A.Equals(A)"" IL_000e: ret IL_000f: ldc.i4.0 IL_0010: ret IL_0011: ldc.i4.1 IL_0012: ret } "); verifier.VerifyIL("bool A.op_Inequality(A, A)", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool A.op_Equality(A, A)"" IL_0007: ldc.i4.0 IL_0008: ceq IL_000a: ret } "); } [Fact] public void EqualityOperators_02() { var source = @" record B; record A(int X) : B { public virtual bool Equals(A other) { System.Console.WriteLine(""Equals(A other)""); return base.Equals(other) && X == other.X; } static void Main() { Test(null, null); Test(null, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); var a = new A(11); Test(a, a); Test(new A(3), new B()); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } static void Test(A a1, B b2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == b2, b2 == a1, a1 != b2, b2 != a1); } } "; var verifier = CompileAndVerify(source, expectedOutput: @" True True False False Equals(A other) Equals(A other) False False True True Equals(A other) Equals(A other) Equals(A other) Equals(A other) True True False False Equals(A other) Equals(A other) Equals(A other) Equals(A other) False False True True True True False False Equals(A other) Equals(A other) False False True True ").VerifyDiagnostics( // (6,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(6, 25) ); var comp = (CSharpCompilation)verifier.Compilation; MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(); Assert.Equal("System.Boolean A.op_Equality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single(); Assert.Equal("System.Boolean A.op_Inequality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); verifier.VerifyIL("bool A.op_Equality(A, A)", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0011 IL_0004: ldarg.0 IL_0005: brfalse.s IL_000f IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: callvirt ""bool A.Equals(A)"" IL_000e: ret IL_000f: ldc.i4.0 IL_0010: ret IL_0011: ldc.i4.1 IL_0012: ret } "); verifier.VerifyIL("bool A.op_Inequality(A, A)", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool A.op_Equality(A, A)"" IL_0007: ldc.i4.0 IL_0008: ceq IL_000a: ret } "); } [Fact] public void EqualityOperators_03() { var source = @" record A { public static bool operator==(A r1, A r2) => throw null; public static bool operator==(A r1, string r2) => throw null; public static bool operator!=(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool operator==(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "==").WithArguments("op_Equality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_04() { var source = @" record A { public static bool operator!=(A r1, A r2) => throw null; public static bool operator!=(string r1, A r2) => throw null; public static bool operator==(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool operator!=(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "!=").WithArguments("op_Inequality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_05() { var source = @" record A { public static bool op_Equality(A r1, A r2) => throw null; public static bool op_Equality(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool op_Equality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Equality").WithArguments("op_Equality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_06() { var source = @" record A { public static bool op_Inequality(A r1, A r2) => throw null; public static bool op_Inequality(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool op_Inequality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Inequality").WithArguments("op_Inequality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_07() { var source = @" record A { public static bool Equals(A other) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,8): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 8), // (4,24): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed. // public static bool Equals(A other) Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_08() { var source = @" record A { public virtual string Equals(A other) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,8): error CS0738: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement 'IEquatable<A>.Equals(A)' because it does not have the matching return type of 'bool'. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)", "bool").WithLocation(2, 8), // (4,27): error CS8874: Record member 'A.Equals(A)' must return 'bool'. // public virtual string Equals(A other) Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 27), // (4,27): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual string Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 27) ); } [Theory] [CombinatorialData] public void EqualityOperators_09(bool useImageReference) { var source1 = @" public record A(int X) { } "; var comp1 = CreateCompilation(source1); var source2 = @" class Program { static void Main() { Test(null, null); Test(null, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } "; CompileAndVerify(source2, references: new[] { useImageReference ? comp1.EmitToImageReference() : comp1.ToMetadataReference() }, expectedOutput: @" True True False False False False True True True True False False False False True True ").VerifyDiagnostics(); } [WorkItem(44692, "https://github.com/dotnet/roslyn/issues/44692")] [Fact] public void DuplicateProperty_01() { var src = @"record C(object Q) { public object P { get; } public object P { get; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0102: The type 'C' already contains a definition for 'P' // public object P { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 19)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.Q { get; init; }", "System.Object C.P { get; }", "System.Object C.P { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [WorkItem(44692, "https://github.com/dotnet/roslyn/issues/44692")] [Fact] public void DuplicateProperty_02() { var src = @"record C(object P, object Q) { public object P { get; } public int P { get; } public int Q { get; } public object Q { get; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,27): error CS8866: Record member 'C.Q' must be a readable instance property or field of type 'object' to match positional parameter 'Q'. // record C(object P, object Q) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Q").WithArguments("C.Q", "object", "Q").WithLocation(1, 27), // (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27), // (4,16): error CS0102: The type 'C' already contains a definition for 'P' // public int P { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 16), // (6,19): error CS0102: The type 'C' already contains a definition for 'Q' // public object Q { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("C", "Q").WithLocation(6, 19)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P { get; }", "System.Int32 C.P { get; }", "System.Int32 C.Q { get; }", "System.Object C.Q { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void DuplicateProperty_03() { var src = @"record A { public object P { get; } public object P { get; } public object Q { get; } public int Q { get; } } record B(object Q) : A { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0102: The type 'A' already contains a definition for 'P' // public object P { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("A", "P").WithLocation(4, 19), // (6,16): error CS0102: The type 'A' already contains a definition for 'Q' // public int Q { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("A", "Q").WithLocation(6, 16), // (8,17): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record B(object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(8, 17)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void NominalRecordWith() { var src = @" using System; record C { public int X { get; init; } public string Y; public int Z { get; set; } public static void Main() { var c = new C() { X = 1, Y = ""2"", Z = 3 }; var c2 = new C() { X = 1, Y = ""2"", Z = 3 }; Console.WriteLine(c.Equals(c2)); var c3 = c2 with { X = 3, Y = ""2"", Z = 1 }; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c3.Equals(c2)); Console.WriteLine(c2.X + "" "" + c2.Y + "" "" + c2.Z); } }"; CompileAndVerify(src, expectedOutput: @" True True False 1 2 3").VerifyDiagnostics(); } [Theory] [InlineData(true)] [InlineData(false)] public void WithExprReference(bool emitRef) { var src = @" public record C { public int X { get; init; } } public record D(int Y) : C;"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var src2 = @" using System; class E { public static void Main() { var c = new C() { X = 1 }; var c2 = c with { X = 2 }; Console.WriteLine(c.X); Console.WriteLine(c2.X); var d = new D(2) { X = 1 }; var d2 = d with { X = 2, Y = 3 }; Console.WriteLine(d.X + "" "" + d.Y); Console.WriteLine(d2.X + "" "" + d2.Y); C c3 = d; C c4 = d2; c3 = c3 with { X = 3 }; c4 = c4 with { X = 4 }; d = (D)c3; d2 = (D)c4; Console.WriteLine(d.X + "" "" + d.Y); Console.WriteLine(d2.X + "" "" + d2.Y); } }"; var verifier = CompileAndVerify(src2, references: new[] { emitRef ? comp.EmitToImageReference() : comp.ToMetadataReference() }, expectedOutput: @" 1 2 1 2 2 3 3 2 4 3").VerifyDiagnostics(); verifier.VerifyIL("E.Main", @" { // Code size 318 (0x13e) .maxstack 3 .locals init (C V_0, //c D V_1, //d D V_2, //d2 C V_3, //c3 C V_4, //c4 int V_5) IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: callvirt ""void C.X.init"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0013: dup IL_0014: ldc.i4.2 IL_0015: callvirt ""void C.X.init"" IL_001a: ldloc.0 IL_001b: callvirt ""int C.X.get"" IL_0020: call ""void System.Console.WriteLine(int)"" IL_0025: callvirt ""int C.X.get"" IL_002a: call ""void System.Console.WriteLine(int)"" IL_002f: ldc.i4.2 IL_0030: newobj ""D..ctor(int)"" IL_0035: dup IL_0036: ldc.i4.1 IL_0037: callvirt ""void C.X.init"" IL_003c: stloc.1 IL_003d: ldloc.1 IL_003e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0043: castclass ""D"" IL_0048: dup IL_0049: ldc.i4.2 IL_004a: callvirt ""void C.X.init"" IL_004f: dup IL_0050: ldc.i4.3 IL_0051: callvirt ""void D.Y.init"" IL_0056: stloc.2 IL_0057: ldloc.1 IL_0058: callvirt ""int C.X.get"" IL_005d: stloc.s V_5 IL_005f: ldloca.s V_5 IL_0061: call ""string int.ToString()"" IL_0066: ldstr "" "" IL_006b: ldloc.1 IL_006c: callvirt ""int D.Y.get"" IL_0071: stloc.s V_5 IL_0073: ldloca.s V_5 IL_0075: call ""string int.ToString()"" IL_007a: call ""string string.Concat(string, string, string)"" IL_007f: call ""void System.Console.WriteLine(string)"" IL_0084: ldloc.2 IL_0085: callvirt ""int C.X.get"" IL_008a: stloc.s V_5 IL_008c: ldloca.s V_5 IL_008e: call ""string int.ToString()"" IL_0093: ldstr "" "" IL_0098: ldloc.2 IL_0099: callvirt ""int D.Y.get"" IL_009e: stloc.s V_5 IL_00a0: ldloca.s V_5 IL_00a2: call ""string int.ToString()"" IL_00a7: call ""string string.Concat(string, string, string)"" IL_00ac: call ""void System.Console.WriteLine(string)"" IL_00b1: ldloc.1 IL_00b2: stloc.3 IL_00b3: ldloc.2 IL_00b4: stloc.s V_4 IL_00b6: ldloc.3 IL_00b7: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_00bc: dup IL_00bd: ldc.i4.3 IL_00be: callvirt ""void C.X.init"" IL_00c3: stloc.3 IL_00c4: ldloc.s V_4 IL_00c6: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_00cb: dup IL_00cc: ldc.i4.4 IL_00cd: callvirt ""void C.X.init"" IL_00d2: stloc.s V_4 IL_00d4: ldloc.3 IL_00d5: castclass ""D"" IL_00da: stloc.1 IL_00db: ldloc.s V_4 IL_00dd: castclass ""D"" IL_00e2: stloc.2 IL_00e3: ldloc.1 IL_00e4: callvirt ""int C.X.get"" IL_00e9: stloc.s V_5 IL_00eb: ldloca.s V_5 IL_00ed: call ""string int.ToString()"" IL_00f2: ldstr "" "" IL_00f7: ldloc.1 IL_00f8: callvirt ""int D.Y.get"" IL_00fd: stloc.s V_5 IL_00ff: ldloca.s V_5 IL_0101: call ""string int.ToString()"" IL_0106: call ""string string.Concat(string, string, string)"" IL_010b: call ""void System.Console.WriteLine(string)"" IL_0110: ldloc.2 IL_0111: callvirt ""int C.X.get"" IL_0116: stloc.s V_5 IL_0118: ldloca.s V_5 IL_011a: call ""string int.ToString()"" IL_011f: ldstr "" "" IL_0124: ldloc.2 IL_0125: callvirt ""int D.Y.get"" IL_012a: stloc.s V_5 IL_012c: ldloca.s V_5 IL_012e: call ""string int.ToString()"" IL_0133: call ""string string.Concat(string, string, string)"" IL_0138: call ""void System.Console.WriteLine(string)"" IL_013d: ret }"); } [Theory] [InlineData(true)] [InlineData(false)] public void WithExprReference_WithCovariantReturns(bool emitRef) { var src = @" public record C { public int X { get; init; } } public record D(int Y) : C;"; var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? src : new[] { src, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics(); var src2 = @" using System; class E { public static void Main() { var c = new C() { X = 1 }; var c2 = CHelper(c); Console.WriteLine(c.X); Console.WriteLine(c2.X); var d = new D(2) { X = 1 }; var d2 = DHelper(d); Console.WriteLine(d.X + "" "" + d.Y); Console.WriteLine(d2.X + "" "" + d2.Y); } private static C CHelper(C c) { return c with { X = 2 }; } private static D DHelper(D d) { return d with { X = 2, Y = 3 }; } }"; var verifier = CompileAndVerify(RuntimeUtilities.IsCoreClrRuntime ? src2 : new[] { src2, IsExternalInitTypeDefinition }, references: new[] { emitRef ? comp.EmitToImageReference() : comp.ToMetadataReference() }, expectedOutput: @" 1 2 1 2 2 3", targetFramework: TargetFramework.StandardLatest).VerifyDiagnostics().VerifyIL("E.CHelper", @" { // Code size 14 (0xe) .maxstack 3 IL_0000: ldarg.0 IL_0001: callvirt ""C C.<Clone>$()"" IL_0006: dup IL_0007: ldc.i4.2 IL_0008: callvirt ""void C.X.init"" IL_000d: ret } "); if (RuntimeUtilities.IsCoreClrRuntime) { verifier.VerifyIL("E.DHelper", @" { // Code size 21 (0x15) .maxstack 3 IL_0000: ldarg.0 IL_0001: callvirt ""D D.<Clone>$()"" IL_0006: dup IL_0007: ldc.i4.2 IL_0008: callvirt ""void C.X.init"" IL_000d: dup IL_000e: ldc.i4.3 IL_000f: callvirt ""void D.Y.init"" IL_0014: ret } "); } else { verifier.VerifyIL("E.DHelper", @" { // Code size 26 (0x1a) .maxstack 3 IL_0000: ldarg.0 IL_0001: callvirt ""C C.<Clone>$()"" IL_0006: castclass ""D"" IL_000b: dup IL_000c: ldc.i4.2 IL_000d: callvirt ""void C.X.init"" IL_0012: dup IL_0013: ldc.i4.3 IL_0014: callvirt ""void D.Y.init"" IL_0019: ret } "); } } private static ImmutableArray<Symbol> GetProperties(CSharpCompilation comp, string typeName) { return comp.GetMember<NamedTypeSymbol>(typeName).GetMembers().WhereAsArray(m => m.Kind == SymbolKind.Property); } [Fact] public void BaseArguments_01() { var src = @" using System; record Base { public Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} } record C(int X, int Y = 123) : Base(X, Y) { int Z = 123; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.Z); } C(int X, int Y, int Z = 124) : this(X, Y) {} }"; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2 123").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 31 (0x1f) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.s 123 IL_0011: stfld ""int C.Z"" IL_0016: ldarg.0 IL_0017: ldarg.1 IL_0018: ldarg.2 IL_0019: call ""Base..ctor(int, int)"" IL_001e: ret } "); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal(Accessibility.Public, symbol.ContainingSymbol.DeclaredAccessibility); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single(); Assert.Equal("Base(X, Y)", baseWithargs.ToString()); Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs)); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString()); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString()); model = comp.GetSemanticModel(tree); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString()); model = comp.GetSemanticModel(tree); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString()); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); #nullable disable var operation = model.GetOperation(baseWithargs); VerifyOperationTree(comp, operation, @" IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') 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) "); Assert.Null(model.GetOperation(baseWithargs.Type)); Assert.Null(model.GetOperation(baseWithargs.Parent)); Assert.Same(operation.Parent.Parent, model.GetOperation(baseWithargs.Parent.Parent)); Assert.Equal(SyntaxKind.RecordDeclaration, baseWithargs.Parent.Parent.Kind()); VerifyOperationTree(comp, operation.Parent.Parent, @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'record C(in ... }') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') 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) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'record C(in ... }') ExpressionBody: null "); Assert.Null(operation.Parent.Parent.Parent); VerifyFlowGraph(comp, operation.Parent.Parent.Syntax, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') 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) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); var equalsValue = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First(); Assert.Equal("= 123", equalsValue.ToString()); model.VerifyOperationTree(equalsValue, @" IParameterInitializerOperation (Parameter: [System.Int32 Y = 123]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= 123') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 123) (Syntax: '123') "); #nullable enable } { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": this(X, Y)", baseWithargs.ToString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString()); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString())); model.VerifyOperationTree(baseWithargs, @" IInvocationOperation ( C..ctor(System.Int32 X, [System.Int32 Y = 123])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': this(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ': this(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') 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) "); var equalsValue = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Last(); Assert.Equal("= 124", equalsValue.ToString()); model.VerifyOperationTree(equalsValue, @" IParameterInitializerOperation (Parameter: [System.Int32 Z = 124]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= 124') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 124) (Syntax: '124') "); model.VerifyOperationTree(baseWithargs.Parent, @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'C(int X, in ... is(X, Y) {}') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': this(X, Y)') Expression: IInvocationOperation ( C..ctor(System.Int32 X, [System.Int32 Y = 123])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': this(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ': this(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') 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) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{}') ExpressionBody: null "); } } [Fact] public void BaseArguments_02() { var src = @" using System; record Base { public Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} } record C(int X) : Base(Test(X, out var y), y) { public static void Main() { var c = new C(1); } private static int Test(int x, out int y) { y = 2; return x; } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var yDecl = OutVarTests.GetOutVarDeclaration(tree, "y"); var yRef = OutVarTests.GetReferences(tree, "y").ToArray(); Assert.Equal(2, yRef.Length); OutVarTests.VerifyModelForOutVar(model, yDecl, yRef[0]); OutVarTests.VerifyNotAnOutLocal(model, yRef[1]); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1); Assert.Equal("Test(X, out var y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); var y = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "y").First(); Assert.Equal("y", y.Parent!.ToString()); Assert.Equal("(Test(X, out var y), y)", y.Parent!.Parent!.ToString()); Assert.Equal("Base(Test(X, out var y), y)", y.Parent!.Parent!.Parent!.ToString()); symbol = model.GetSymbolInfo(y).Symbol; Assert.Equal(SymbolKind.Local, symbol!.Kind); Assert.Equal("System.Int32 y", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "y")); Assert.Contains("y", model.LookupNames(x.SpanStart)); var test = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").First(); Assert.Equal("(Test(X, out var y), y)", test.Parent!.Parent!.Parent!.ToString()); symbol = model.GetSymbolInfo(test).Symbol; Assert.Equal(SymbolKind.Method, symbol!.Kind); Assert.Equal("System.Int32 C.Test(System.Int32 x, out System.Int32 y)", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "Test")); Assert.Contains("Test", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_03() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (13,16): error CS8861: Unexpected argument list. // record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 16) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_04() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C(int X, int Y) { } partial record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (17,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[0])); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[1])); } [Fact] public void BaseArguments_05() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C : Base(X, Y) { } partial record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (13,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 24), // (17,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray(); Assert.Equal(2, xs.Length); foreach (var x in xs) { Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[0])); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[1])); } [Fact] public void BaseArguments_06() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C(int X, int Y) : Base(X, Y) { } partial record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (17,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray(); Assert.Equal(2, xs.Length); var x = xs[0]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); x = xs[1]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); model.VerifyOperationTree(recordDeclarations[0], @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'partial rec ... }') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') 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) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'partial rec ... }') ExpressionBody: null "); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[1])); } [Fact] public void BaseArguments_07() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C : Base(X, Y) { } partial record C(int X, int Y) : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (13,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray(); Assert.Equal(2, xs.Length); var x = xs[1]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); x = xs[0]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[0])); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); model.VerifyOperationTree(recordDeclarations[1], @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'partial rec ... }') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') 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) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'partial rec ... }') ExpressionBody: null "); } [Fact] public void BaseArguments_08() { var src = @" record Base { public Base(int Y) { } public Base() {} } record C(int X) : Base(Y) { public int Y = 0; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.Y' // record C(int X) : Base(Y) Diagnostic(ErrorCode.ERR_ObjectRequired, "Y").WithArguments("C.Y").WithLocation(11, 24) ); } [Fact] public void BaseArguments_09() { var src = @" record Base { public Base(int X) { } public Base() {} } record C(int X) : Base(this.X) { public int Y = 0; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,24): error CS0027: Keyword 'this' is not available in the current context // record C(int X) : Base(this.X) Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(11, 24) ); } [Fact] public void BaseArguments_10() { var src = @" record Base { public Base(int X) { } public Base() {} } record C(dynamic X) : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,27): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments. // record C(dynamic X) : Base(X) Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, "(X)").WithLocation(11, 27) ); } [Fact] public void BaseArguments_11() { var src = @" record Base { public Base(int X, int Y) { } public Base() {} } record C(int X) : Base(Test(X, out var y), y) { int Z = y; private static int Test(int x, out int y) { y = 2; return x; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,13): error CS0103: The name 'y' does not exist in the current context // int Z = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(13, 13) ); } [Fact] public void BaseArguments_12() { var src = @" using System; class Base { public Base(int X) { } } class C : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (11,7): error CS7036: There is no argument given that corresponds to the required formal parameter 'X' of 'Base.Base(int)' // class C : Base(X) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("X", "Base.Base(int)").WithLocation(11, 7), // (11,15): error CS8861: Unexpected argument list. // class C : Base(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(11, 15) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_13() { var src = @" using System; interface Base { } struct C : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (8,16): error CS8861: Unexpected argument list. // struct C : Base(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(8, 16) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_14() { var src = @" using System; interface Base { } interface C : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (8,19): error CS8861: Unexpected argument list. // interface C : Base(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(8, 19) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_15() { var src = @" using System; record Base { public Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} } partial record C { } partial record C(int X, int Y) : Base(X, Y) { int Z = 123; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.Z); } } partial record C { } "; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2 123").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 31 (0x1f) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.s 123 IL_0011: stfld ""int C.Z"" IL_0016: ldarg.0 IL_0017: ldarg.1 IL_0018: ldarg.2 IL_0019: call ""Base..ctor(int, int)"" IL_001e: ret } "); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_16() { var src = @" using System; record Base { public Base(Func<int> X) { Console.WriteLine(X()); } public Base() {} } record C(int X) : Base(() => X) { public static void Main() { var c = new C(1); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"1").VerifyDiagnostics(); } [Fact] public void BaseArguments_17() { var src = @" record Base { public Base(int X, int Y) { } public Base() {} } record C(int X, int y) : Base(Test(X, out var y), Test(X, out var z)) { int Z = z; private static int Test(int x, out int y) { y = 2; return x; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,28): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // : Base(Test(X, out var y), Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(12, 28), // (15,13): error CS0103: The name 'z' does not exist in the current context // int Z = z; Diagnostic(ErrorCode.ERR_NameNotInContext, "z").WithArguments("z").WithLocation(15, 13) ); } [Fact] public void BaseArguments_18() { var src = @" record Base { public Base(int X, int Y) { } public Base() {} } record C(int X, int y) : Base(Test(X + 1, out var z), Test(X + 2, out var z)) { private static int Test(int x, out int y) { y = 2; return x; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,32): error CS0128: A local variable or function named 'z' is already defined in this scope // Test(X + 2, out var z)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "z").WithArguments("z").WithLocation(13, 32) ); } [Fact] public void BaseArguments_19() { var src = @" record Base { public Base(int X) { } public Base() {} } record C(int X, int Y) : Base(GetInt(X, out var xx) + xx, Y), I { C(int X, int Y, int Z) : this(X, Y, Z, 1) { return; } static int GetInt(int x1, out int x2) { throw null; } } interface I {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,30): error CS1729: 'Base' does not contain a constructor that takes 2 arguments // record C(int X, int Y) : Base(GetInt(X, out var xx) + xx, Y) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(GetInt(X, out var xx) + xx, Y)").WithArguments("Base", "2").WithLocation(11, 30), // (13,30): error CS1729: 'C' does not contain a constructor that takes 4 arguments // C(int X, int Y, int Z) : this(X, Y, Z, 1) {} Diagnostic(ErrorCode.ERR_BadCtorArgCount, "this").WithArguments("C", "4").WithLocation(13, 30) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); SymbolInfo symbolInfo; PrimaryConstructorBaseTypeSyntax speculativePrimaryInitializer; ConstructorInitializerSyntax speculativeBaseInitializer; { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single(); Assert.Equal("Base(GetInt(X, out var xx) + xx, Y)", baseWithargs.ToString()); Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs)); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); string[] candidates = new[] { "Base..ctor(Base original)", "Base..ctor(System.Int32 X)", "Base..ctor()" }; Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); model = comp.GetSemanticModel(tree); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); model = comp.GetSemanticModel(tree); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); SemanticModel speculativeModel; speculativePrimaryInitializer = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1))); speculativeBaseInitializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, speculativePrimaryInitializer.ArgumentList); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.False(model.TryGetSpeculativeSemanticModel(tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().SpanStart, speculativeBaseInitializer, out _)); var otherBasePosition = ((BaseListSyntax)baseWithargs.Parent!).Types[1].SpanStart; Assert.False(model.TryGetSpeculativeSemanticModel(otherBasePosition, speculativePrimaryInitializer, out _)); Assert.True(model.TryGetSpeculativeSemanticModel(baseWithargs.SpanStart, speculativePrimaryInitializer, out speculativeModel!)); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel!.GetSymbolInfo((SyntaxNode)speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel.GetSymbolInfo(speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", CSharpExtensions.GetSymbolInfo(speculativeModel, speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.True(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out speculativeModel!)); var xxDecl = OutVarTests.GetOutVarDeclaration(speculativePrimaryInitializer.SyntaxTree, "xx"); var xxRef = OutVarTests.GetReferences(speculativePrimaryInitializer.SyntaxTree, "xx").ToArray(); Assert.Equal(1, xxRef.Length); OutVarTests.VerifyModelForOutVar(speculativeModel, xxDecl, xxRef); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel!.GetSymbolInfo((SyntaxNode)speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel.GetSymbolInfo(speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", CSharpExtensions.GetSymbolInfo(speculativeModel, speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Throws<ArgumentNullException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (PrimaryConstructorBaseTypeSyntax)null!, out _)); Assert.Throws<ArgumentException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, baseWithargs, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(otherBasePosition, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, otherBasePosition, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.SpanStart, speculativePrimaryInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single().ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": this(X, Y, Z, 1)", baseWithargs.ToString()); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); string[] candidates = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)", "C..ctor(System.Int32 X, System.Int32 Y, System.Int32 Z)" }; Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString())); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } } [Fact] public void BaseArguments_20() { var src = @" class Base { public Base(int X) { } public Base() {} } class C : Base(GetInt(X, out var xx) + xx, Y), I { C(int X, int Y, int Z) : base(X, Y, Z, 1) { return; } static int GetInt(int x1, out int x2) { throw null; } } interface I {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,15): error CS8861: Unexpected argument list. // class C : Base(GetInt(X, out var xx) + xx, Y), I Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(GetInt(X, out var xx) + xx, Y)").WithLocation(11, 15), // (13,30): error CS1729: 'Base' does not contain a constructor that takes 4 arguments // C(int X, int Y, int Z) : base(X, Y, Z, 1) { return; } Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("Base", "4").WithLocation(13, 30) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); SymbolInfo symbolInfo; PrimaryConstructorBaseTypeSyntax speculativePrimaryInitializer; ConstructorInitializerSyntax speculativeBaseInitializer; { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single(); Assert.Equal("Base(GetInt(X, out var xx) + xx, Y)", baseWithargs.ToString()); Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs)); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); Assert.Empty(model.GetMemberGroup(baseWithargs)); speculativePrimaryInitializer = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1))); speculativeBaseInitializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, speculativePrimaryInitializer.ArgumentList); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.False(model.TryGetSpeculativeSemanticModel(tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().SpanStart, speculativeBaseInitializer, out _)); var otherBasePosition = ((BaseListSyntax)baseWithargs.Parent!).Types[1].SpanStart; Assert.False(model.TryGetSpeculativeSemanticModel(otherBasePosition, speculativePrimaryInitializer, out _)); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.SpanStart, speculativePrimaryInitializer, out _)); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _)); Assert.Throws<ArgumentNullException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (PrimaryConstructorBaseTypeSyntax)null!, out _)); Assert.Throws<ArgumentException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, baseWithargs, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(otherBasePosition, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, otherBasePosition, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single().ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": base(X, Y, Z, 1)", baseWithargs.ToString()); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); string[] candidates = new[] { "Base..ctor(System.Int32 X)", "Base..ctor()" }; Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString())); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } } [Fact] public void Equality_02() { var source = @"using static System.Console; record C; class Program { static void Main() { var x = new C(); var y = new C(); WriteLine(x.Equals(y) && x.GetHashCode() == y.GetHashCode()); WriteLine(((object)x).Equals(y)); WriteLine(((System.IEquatable<C>)x).Equals(y)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var ordinaryMethods = comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray(); Assert.Equal(6, ordinaryMethods.Length); foreach (var m in ordinaryMethods) { Assert.True(m.IsImplicitlyDeclared); } var verifier = CompileAndVerify(comp, expectedOutput: @"True True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("C.Equals(object)", @"{ // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: callvirt ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type C.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ret }"); } [Fact] public void Equality_03() { var source = @"using static System.Console; record C { private static int _nextId = 0; private int _id; public C() { _id = _nextId++; } } class Program { static void Main() { var x = new C(); var y = new C(); WriteLine(x.Equals(x)); WriteLine(x.Equals(y)); WriteLine(y.Equals(y)); } }"; var verifier = CompileAndVerify(source, expectedOutput: @"True False True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C._id"" IL_0025: ldarg.1 IL_0026: ldfld ""int C._id"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type C.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ldc.i4 0xa5555529 IL_0015: mul IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C._id"" IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_0026: add IL_0027: ret }"); var clone = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.True(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Fact] public void Equality_04() { var source = @"using static System.Console; record A; record B1(int P) : A { internal B1() : this(0) { } // Use record base call syntax instead internal int P { get; set; } // Use record base call syntax instead } record B2(int P) : A { internal B2() : this(0) { } // Use record base call syntax instead internal int P { get; set; } // Use record base call syntax instead } class Program { static B1 NewB1(int p) => new B1 { P = p }; // Use record base call syntax instead static B2 NewB2(int p) => new B2 { P = p }; // Use record base call syntax instead static void Main() { WriteLine(new A().Equals(NewB1(1))); WriteLine(NewB1(1).Equals(new A())); WriteLine(NewB1(1).Equals(NewB2(1))); WriteLine(new A().Equals((A)NewB2(1))); WriteLine(((A)NewB2(1)).Equals(new A())); WriteLine(((A)NewB2(1)).Equals(NewB2(1)) && ((A)NewB2(1)).GetHashCode() == NewB2(1).GetHashCode()); WriteLine(NewB2(1).Equals((A)NewB2(1))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"False False False False False True True").VerifyDiagnostics( // (3,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B1(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(3, 15), // (8,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B2(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(8, 15) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("B1.Equals(B1)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int B1.<P>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int B1.<P>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); verifier.VerifyIL("B1.GetHashCode()", @"{ // Code size 30 (0x1e) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""int B1.<P>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_001c: add IL_001d: ret }"); } [Fact] public void Equality_05() { var source = @"using static System.Console; record A(int P) { internal A() : this(0) { } // Use record base call syntax instead internal int P { get; set; } // Use record base call syntax instead } record B1(int P) : A { internal B1() : this(0) { } // Use record base call syntax instead } record B2(int P) : A { internal B2() : this(0) { } // Use record base call syntax instead } class Program { static A NewA(int p) => new A { P = p }; // Use record base call syntax instead static B1 NewB1(int p) => new B1 { P = p }; // Use record base call syntax instead static B2 NewB2(int p) => new B2 { P = p }; // Use record base call syntax instead static void Main() { WriteLine(NewA(1).Equals(NewA(2))); WriteLine(NewA(1).Equals(NewA(1)) && NewA(1).GetHashCode() == NewA(1).GetHashCode()); WriteLine(NewA(1).Equals(NewB1(1))); WriteLine(NewB1(1).Equals(NewA(1))); WriteLine(NewB1(1).Equals(NewB2(1))); WriteLine(NewA(1).Equals((A)NewB2(1))); WriteLine(((A)NewB2(1)).Equals(NewA(1))); WriteLine(((A)NewB2(1)).Equals(NewB2(1))); WriteLine(NewB2(1).Equals((A)NewB2(1))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"False True False False False False False True True").VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record A(int P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14), // (7,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B1(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(7, 15), // (11,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B2(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(11, 15) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int A.<P>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int A.<P>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("B1.Equals(B1)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); verifier.VerifyIL("B1.GetHashCode()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ret }"); } [Fact] public void Equality_06() { var source = @" using System; using static System.Console; record A; record B : A { protected override Type EqualityContract => typeof(A); public virtual bool Equals(B b) => base.Equals((A)b); } record C : B; class Program { static void Main() { WriteLine(new A().Equals(new A())); WriteLine(new A().Equals(new B())); WriteLine(new A().Equals(new C())); WriteLine(new B().Equals(new A())); WriteLine(new B().Equals(new B())); WriteLine(new B().Equals(new C())); WriteLine(new C().Equals(new A())); WriteLine(new C().Equals(new B())); WriteLine(new C().Equals(new C())); WriteLine(((A)new C()).Equals(new A())); WriteLine(((A)new C()).Equals(new B())); WriteLine(((A)new C()).Equals(new C())); WriteLine(new C().Equals((A)new C())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().First(); Assert.Null(model.GetOperation(recordDeclaration)); var verifier = CompileAndVerify(comp, expectedOutput: @"True True False False True False False False True False False True True").VerifyDiagnostics( // (8,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(8, 25) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); } [Fact] public void Equality_07() { var source = @"using System; using static System.Console; record A; record B : A; record C : B; class Program { static void Main() { WriteLine(new A().Equals(new A())); WriteLine(new A().Equals(new B())); WriteLine(new A().Equals(new C())); WriteLine(new B().Equals(new A())); WriteLine(new B().Equals(new B())); WriteLine(new B().Equals(new C())); WriteLine(new C().Equals(new A())); WriteLine(new C().Equals(new B())); WriteLine(new C().Equals(new C())); WriteLine(((A)new B()).Equals(new A())); WriteLine(((A)new B()).Equals(new B())); WriteLine(((A)new B()).Equals(new C())); WriteLine(((A)new C()).Equals(new A())); WriteLine(((A)new C()).Equals(new B())); WriteLine(((A)new C()).Equals(new C())); WriteLine(((B)new C()).Equals(new A())); WriteLine(((B)new C()).Equals(new B())); WriteLine(((B)new C()).Equals(new C())); WriteLine(new C().Equals((A)new C())); WriteLine(((IEquatable<A>)new B()).Equals(new A())); WriteLine(((IEquatable<A>)new B()).Equals(new B())); WriteLine(((IEquatable<A>)new B()).Equals(new C())); WriteLine(((IEquatable<A>)new C()).Equals(new A())); WriteLine(((IEquatable<A>)new C()).Equals(new B())); WriteLine(((IEquatable<A>)new C()).Equals(new C())); WriteLine(((IEquatable<B>)new C()).Equals(new A())); WriteLine(((IEquatable<B>)new C()).Equals(new B())); WriteLine(((IEquatable<B>)new C()).Equals(new C())); WriteLine(((IEquatable<C>)new C()).Equals(new C())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"True False False False True False False False True False True False False False True False False True True False True False False False True False False True True").VerifyDiagnostics(); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("B.Equals(A)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("C.Equals(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.get_EqualityContract"), isOverride: false); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.get_EqualityContract"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C.get_EqualityContract"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName), isOverride: false); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.CloneMethodName), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.GetHashCode"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.GetHashCode"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C.GetHashCode"), isOverride: true); VerifyVirtualMethods(comp.GetMembers("A.Equals"), ("System.Boolean A.Equals(A? other)", false), ("System.Boolean A.Equals(System.Object? obj)", true)); VerifyVirtualMethods(comp.GetMembers("B.Equals"), ("System.Boolean B.Equals(B? other)", false), ("System.Boolean B.Equals(A? other)", true), ("System.Boolean B.Equals(System.Object? obj)", true)); ImmutableArray<Symbol> cEquals = comp.GetMembers("C.Equals"); VerifyVirtualMethods(cEquals, ("System.Boolean C.Equals(C? other)", false), ("System.Boolean C.Equals(B? other)", true), ("System.Boolean C.Equals(System.Object? obj)", true)); var baseEquals = cEquals[1]; Assert.Equal("System.Boolean C.Equals(B? other)", baseEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, baseEquals.DeclaredAccessibility); Assert.True(baseEquals.IsOverride); Assert.True(baseEquals.IsSealed); Assert.True(baseEquals.IsImplicitlyDeclared); } private static void VerifyVirtualMethod(MethodSymbol method, bool isOverride) { Assert.Equal(!isOverride, method.IsVirtual); Assert.Equal(isOverride, method.IsOverride); Assert.True(method.IsMetadataVirtual()); Assert.Equal(!isOverride, method.IsMetadataNewSlot()); } private static void VerifyVirtualMethods(ImmutableArray<Symbol> members, params (string displayString, bool isOverride)[] values) { Assert.Equal(members.Length, values.Length); for (int i = 0; i < members.Length; i++) { var method = (MethodSymbol)members[i]; (string displayString, bool isOverride) = values[i]; Assert.Equal(displayString, method.ToTestDisplayString(includeNonNullable: true)); VerifyVirtualMethod(method, isOverride); } } [WorkItem(44895, "https://github.com/dotnet/roslyn/issues/44895")] [Fact] public void Equality_08() { var source = @" using System; using static System.Console; record A(int X) { internal A() : this(0) { } // Use record base call syntax instead internal int X { get; set; } // Use record base call syntax instead } record B : A { internal B() { } // Use record base call syntax instead internal B(int X, int Y) : base(X) { this.Y = Y; } internal int Y { get; set; } protected override Type EqualityContract => typeof(A); public virtual bool Equals(B b) => base.Equals((A)b); } record C(int X, int Y, int Z) : B { internal C() : this(0, 0, 0) { } // Use record base call syntax instead internal int Z { get; set; } // Use record base call syntax instead } class Program { static A NewA(int x) => new A { X = x }; // Use record base call syntax instead static B NewB(int x, int y) => new B { X = x, Y = y }; static C NewC(int x, int y, int z) => new C { X = x, Y = y, Z = z }; static void Main() { WriteLine(NewA(1).Equals(NewA(1))); WriteLine(NewA(1).Equals(NewB(1, 2))); WriteLine(NewA(1).Equals(NewC(1, 2, 3))); WriteLine(NewB(1, 2).Equals(NewA(1))); WriteLine(NewB(1, 2).Equals(NewB(1, 2))); WriteLine(NewB(1, 2).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewA(1))); WriteLine(NewC(1, 2, 3).Equals(NewB(1, 2))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(4, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 4))); WriteLine(((A)NewB(1, 2)).Equals(NewA(1))); WriteLine(((A)NewB(1, 2)).Equals(NewB(1, 2))); WriteLine(((A)NewB(1, 2)).Equals(NewC(1, 2, 3))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewC(1, 2, 3))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewC(1, 2, 3)) && NewC(1, 2, 3).GetHashCode() == NewC(1, 2, 3).GetHashCode()); WriteLine(NewC(1, 2, 3).Equals((A)NewC(1, 2, 3))); } }"; // https://github.com/dotnet/roslyn/issues/44895: C.Equals() should compare B.Y. var verifier = CompileAndVerify(source, expectedOutput: @"True True False False True False False False True False True False False True False False False True False False True True").VerifyDiagnostics( // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (15,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(15, 25), // (17,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(17, 14), // (17,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(17, 21), // (17,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(17, 28) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int A.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int A.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); // https://github.com/dotnet/roslyn/issues/44895: C.Equals() should compare B.Y. verifier.VerifyIL("C.Equals(C)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int C.<Z>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int C.<Z>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 30 (0x1e) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int B.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""int C.<Z>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_001c: add IL_001d: ret }"); } [Fact] public void Equality_09() { var source = @"using static System.Console; record A(int X) { internal A() : this(0) { } // Use record base call syntax instead internal int X { get; set; } // Use record base call syntax instead } record B(int X, int Y) : A { internal B() : this(0, 0) { } // Use record base call syntax instead internal int Y { get; set; } } record C(int X, int Y, int Z) : B { internal C() : this(0, 0, 0) { } // Use record base call syntax instead internal int Z { get; set; } // Use record base call syntax instead } class Program { static A NewA(int x) => new A { X = x }; // Use record base call syntax instead static B NewB(int x, int y) => new B { X = x, Y = y }; static C NewC(int x, int y, int z) => new C { X = x, Y = y, Z = z }; static void Main() { WriteLine(NewA(1).Equals(NewA(1))); WriteLine(NewA(1).Equals(NewB(1, 2))); WriteLine(NewA(1).Equals(NewC(1, 2, 3))); WriteLine(NewB(1, 2).Equals(NewA(1))); WriteLine(NewB(1, 2).Equals(NewB(1, 2))); WriteLine(NewB(1, 2).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewA(1))); WriteLine(NewC(1, 2, 3).Equals(NewB(1, 2))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(4, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 4))); WriteLine(((A)NewB(1, 2)).Equals(NewA(1))); WriteLine(((A)NewB(1, 2)).Equals(NewB(1, 2))); WriteLine(((A)NewB(1, 2)).Equals(NewC(1, 2, 3))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewC(1, 2, 3))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals((A)NewC(1, 2, 3))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().ElementAt(1); Assert.Equal("B", recordDeclaration.Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclaration)); var verifier = CompileAndVerify(comp, expectedOutput: @"True False False False True False False False True False False False False True False False False True False False True True").VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14), // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14), // (7,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 21), // (12,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(12, 14), // (12,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(12, 21), // (12,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(12, 28) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int A.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int A.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("B.Equals(A)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int B.<Y>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int B.<Y>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); verifier.VerifyIL("C.Equals(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int C.<Z>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int C.<Z>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); } [Fact] public void Equality_11() { var source = @"using System; record A { protected virtual Type EqualityContract => typeof(object); } record B1(object P) : A; record B2(object P) : A; class Program { static void Main() { Console.WriteLine(new A().Equals(new A())); Console.WriteLine(new A().Equals(new B1((object)null))); Console.WriteLine(new B1((object)null).Equals(new A())); Console.WriteLine(new B1((object)null).Equals(new B1((object)null))); Console.WriteLine(new B1((object)null).Equals(new B2((object)null))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); // init-only is unverifiable CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"True False False True False").VerifyDiagnostics(); } [Fact] public void Equality_12() { var source = @"using System; abstract record A { public A() { } protected abstract Type EqualityContract { get; } } record B1(object P) : A; record B2(object P) : A; class Program { static void Main() { var b1 = new B1((object)null); var b2 = new B2((object)null); Console.WriteLine(b1.Equals(b1)); Console.WriteLine(b1.Equals(b2)); Console.WriteLine(((A)b1).Equals(b1)); Console.WriteLine(((A)b1).Equals(b2)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); // init-only is unverifiable CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"True False True False").VerifyDiagnostics(); } [Fact] public void Equality_13() { var source = @"record A { protected System.Type EqualityContract => typeof(A); } record B : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,27): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed. // protected System.Type EqualityContract => typeof(A); Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 27), // (5,8): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(5, 8)); } [Fact] public void Equality_14() { var source = @"record A; record B : A { protected sealed override System.Type EqualityContract => typeof(B); } record C : B; "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics( // (4,43): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed. // protected sealed override System.Type EqualityContract => typeof(B); Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(4, 43), // (6,8): error CS0239: 'C.EqualityContract': cannot override inherited member 'B.EqualityContract' because it is sealed // record C : B; Diagnostic(ErrorCode.ERR_CantOverrideSealed, "C").WithArguments("C.EqualityContract", "B.EqualityContract").WithLocation(6, 8)); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); string expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses ? "B B." + WellKnownMemberNames.CloneMethodName + "()" : "A B." + WellKnownMemberNames.CloneMethodName + "()"; var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Type B.EqualityContract.get", "System.String B.ToString()", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", expectedClone, "B..ctor(B original)", "B..ctor()", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Equality_15() { var source = @"using System; record A; record B1 : A { public B1(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(A); public virtual bool Equals(B1 o) => base.Equals((A)o); } record B2 : A { public B2(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(B2); public virtual bool Equals(B2 o) => base.Equals((A)o); } class Program { static void Main() { Console.WriteLine(new B1(1).Equals(new B1(2))); Console.WriteLine(new B1(1).Equals(new B2(1))); Console.WriteLine(new B2(1).Equals(new B2(2))); } }"; CompileAndVerify(source, expectedOutput: @"True False True").VerifyDiagnostics( // (8,25): warning CS8851: 'B1' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B1 o) => base.Equals((A)o); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B1").WithLocation(8, 25), // (15,25): warning CS8851: 'B2' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B2 o) => base.Equals((A)o); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B2").WithLocation(15, 25) ); } [Fact] public void Equality_16() { var source = @"using System; record A; record B1 : A { public B1(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(string); public virtual bool Equals(B1 b) => base.Equals((A)b); } record B2 : A { public B2(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(string); public virtual bool Equals(B2 b) => base.Equals((A)b); } class Program { static void Main() { Console.WriteLine(new B1(1).Equals(new B1(2))); Console.WriteLine(new B1(1).Equals(new B2(2))); Console.WriteLine(new B2(1).Equals(new B2(2))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"True False True").VerifyDiagnostics( // (8,25): warning CS8851: 'B1' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B1 b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B1").WithLocation(8, 25), // (15,25): warning CS8851: 'B2' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B2 b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B2").WithLocation(15, 25) ); } [Fact] public void Equality_17() { var source = @"using static System.Console; record A; record B1(int P) : A { } record B2(int P) : A { } class Program { static void Main() { WriteLine(new B1(1).Equals(new B1(1))); WriteLine(new B1(1).Equals(new B1(2))); WriteLine(new B2(3).Equals(new B2(3))); WriteLine(new B2(3).Equals(new B2(4))); WriteLine(((A)new B1(1)).Equals(new B1(1))); WriteLine(((A)new B1(1)).Equals(new B1(2))); WriteLine(((A)new B2(3)).Equals(new B2(3))); WriteLine(((A)new B2(3)).Equals(new B2(4))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); // init-only is unverifiable CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"True False True False True False True False").VerifyDiagnostics(); var actualMembers = comp.GetMember<NamedTypeSymbol>("B1").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "B1..ctor(System.Int32 P)", "System.Type B1.EqualityContract.get", "System.Type B1.EqualityContract { get; }", "System.Int32 B1.<P>k__BackingField", "System.Int32 B1.P.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B1.P.init", "System.Int32 B1.P { get; init; }", "System.String B1.ToString()", "System.Boolean B1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B1.op_Inequality(B1? left, B1? right)", "System.Boolean B1.op_Equality(B1? left, B1? right)", "System.Int32 B1.GetHashCode()", "System.Boolean B1.Equals(System.Object? obj)", "System.Boolean B1.Equals(A? other)", "System.Boolean B1.Equals(B1? other)", "A B1." + WellKnownMemberNames.CloneMethodName + "()", "B1..ctor(B1 original)", "void B1.Deconstruct(out System.Int32 P)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Theory] [InlineData(false)] [InlineData(true)] public void Equality_18(bool useCompilationReference) { var sourceA = @"public record A;"; var comp = CreateCompilation(sourceA); comp.VerifyDiagnostics(); var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference(); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.get_EqualityContract"), isOverride: false); VerifyVirtualMethods(comp.GetMembers("A.Equals"), ("System.Boolean A.Equals(A? other)", false), ("System.Boolean A.Equals(System.Object? obj)", true)); var sourceB = @"record B : A;"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.get_EqualityContract"), isOverride: true); VerifyVirtualMethods(comp.GetMembers("B.Equals"), ("System.Boolean B.Equals(B? other)", false), ("System.Boolean B.Equals(A? other)", true), ("System.Boolean B.Equals(System.Object? obj)", true)); } [Fact] public void Equality_19() { var source = @"using static System.Console; record A<T>; record B : A<int>; class Program { static void Main() { WriteLine(new A<int>().Equals(new A<int>())); WriteLine(new A<int>().Equals(new B())); WriteLine(new B().Equals(new A<int>())); WriteLine(new B().Equals(new B())); WriteLine(((A<int>)new B()).Equals(new A<int>())); WriteLine(((A<int>)new B()).Equals(new B())); WriteLine(new B().Equals((A<int>)new B())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"True False False True False True True").VerifyDiagnostics(); verifier.VerifyIL("A<T>.Equals(A<T>)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A<T>.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A<T>.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("B.Equals(A<int>)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A<int>.Equals(A<int>)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); } [Fact] public void Equality_20() { var source = @" record C; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__GetHashCode); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // record C; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C;").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1) ); } [Fact] public void Equality_21() { var source = @" record C; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // record C; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C;").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1) ); } [Fact] [WorkItem(44988, "https://github.com/dotnet/roslyn/issues/44988")] public void Equality_22() { var source = @" record C { int x = 0; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // record C Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record C { int x = 0; }").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // record C Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record C { int x = 0; }").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1), // (4,9): warning CS0414: The field 'C.x' is assigned but its value is never used // int x = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x").WithLocation(4, 9) ); } [Fact] public void IEquatableT_01() { var source = @"record A<T>; record B : A<int>; class Program { static void F<T>(System.IEquatable<T> t) { } static void M<T>() { F(new A<T>()); F(new B()); F<A<int>>(new B()); F<B>(new B()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,9): error CS0411: The type arguments for method 'Program.F<T>(IEquatable<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(new B()); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.IEquatable<T>)").WithLocation(11, 9)); } [Fact] public void IEquatableT_02() { var source = @"using System; record A; record B<T> : A; record C : B<int>; class Program { static string F<T>(IEquatable<T> t) { return typeof(T).Name; } static void Main() { Console.WriteLine(F(new A())); Console.WriteLine(F<A>(new C())); Console.WriteLine(F<B<int>>(new C())); Console.WriteLine(F<C>(new C())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A A B`1 C").VerifyDiagnostics(); } [Fact] public void IEquatableT_03() { var source = @"#nullable enable using System; record A<T> : IEquatable<A<T>> { } record B : A<object>, IEquatable<A<object>>, IEquatable<B?>; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B?>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B?>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_04() { var source = @"using System; record A<T> { internal static bool Report(string s) { Console.WriteLine(s); return false; } public virtual bool Equals(A<T> other) => Report(""A<T>.Equals(A<T>)""); } record B : A<object> { public virtual bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { var a = new A<object>(); var b = new B(); _ = a.Equals(b); _ = ((A<object>)b).Equals(b); _ = b.Equals(a); _ = b.Equals(b); _ = ((IEquatable<A<object>>)a).Equals(b); _ = ((IEquatable<A<object>>)b).Equals(b); _ = ((IEquatable<B>)b).Equals(b); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A<T>.Equals(A<T>) B.Equals(B) B.Equals(B) B.Equals(B) A<T>.Equals(A<T>) B.Equals(B) B.Equals(B)").VerifyDiagnostics( // (5,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A<T> other) => Report("A<T>.Equals(A<T>)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 25), // (9,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_05() { var source = @"using System; record A<T> : IEquatable<A<T>> { internal static bool Report(string s) { Console.WriteLine(s); return false; } public virtual bool Equals(A<T> other) => Report(""A<T>.Equals(A<T>)""); } record B : A<object>, IEquatable<A<object>>, IEquatable<B> { public virtual bool Equals(B other) => Report(""B.Equals(B)""); } record C : A<object>, IEquatable<A<object>>, IEquatable<C> { } class Program { static void Main() { var a = new A<object>(); var b = new B(); _ = a.Equals(b); _ = ((A<object>)b).Equals(b); _ = b.Equals(a); _ = b.Equals(b); _ = ((IEquatable<A<object>>)a).Equals(b); _ = ((IEquatable<A<object>>)b).Equals(b); _ = ((IEquatable<B>)b).Equals(b); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A<T>.Equals(A<T>) B.Equals(B) B.Equals(B) B.Equals(B) A<T>.Equals(A<T>) B.Equals(B) B.Equals(B)", symbolValidator: m => { var b = m.GlobalNamespace.GetTypeMember("B"); Assert.Equal("B.Equals(B)", b.FindImplementationForInterfaceMember(b.InterfacesNoUseSiteDiagnostics()[1].GetMember("Equals")).ToDisplayString()); var c = m.GlobalNamespace.GetTypeMember("C"); Assert.Equal("C.Equals(C?)", c.FindImplementationForInterfaceMember(c.InterfacesNoUseSiteDiagnostics()[1].GetMember("Equals")).ToDisplayString()); }).VerifyDiagnostics( // (5,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A<T> other) => Report("A<T>.Equals(A<T>)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 25), // (9,25): warning CS8851: '{B}' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_06() { var source = @"using System; record A<T> : IEquatable<A<T>> { internal static bool Report(string s) { Console.WriteLine(s); return false; } bool IEquatable<A<T>>.Equals(A<T> other) => Report(""A<T>.Equals(A<T>)""); } record B : A<object>, IEquatable<A<object>>, IEquatable<B> { bool IEquatable<A<object>>.Equals(A<object> other) => Report(""B.Equals(A<object>)""); bool IEquatable<B>.Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { var a = new A<object>(); var b = new B(); _ = a.Equals(b); _ = ((A<object>)b).Equals(b); _ = b.Equals(a); _ = b.Equals(b); _ = ((IEquatable<A<object>>)a).Equals(b); _ = ((IEquatable<A<object>>)b).Equals(b); _ = ((IEquatable<B>)b).Equals(b); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A<T>.Equals(A<T>) B.Equals(A<object>) B.Equals(B)").VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_07() { var source = @"using System; record A<T> : IEquatable<B1>, IEquatable<B2> { bool IEquatable<B1>.Equals(B1 other) => false; bool IEquatable<B2>.Equals(B2 other) => false; } record B1 : A<object>; record B2 : A<int>; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<B2>", "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<B2>", "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B1"); AssertEx.Equal(new[] { "System.IEquatable<B1>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<B2>", "System.IEquatable<A<System.Object>>", "System.IEquatable<B1>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B2"); AssertEx.Equal(new[] { "System.IEquatable<B2>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<A<System.Int32>>", "System.IEquatable<B2>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_08() { var source = @"interface I<T> { } record A<T> : I<A<T>> { } record B : A<object>, I<A<object>>, I<B> { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "I<A<T>>", "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "I<A<T>>", "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "I<A<System.Object>>", "I<B>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "I<A<System.Object>>", "I<B>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_09() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"record A<T>; record B : A<int>; "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record B : A<int>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(2, 8) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_10() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"record A<T> : System.IEquatable<A<T>>; record B : A<int>, System.IEquatable<B>; "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.ToString()': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,22): error CS0234: The type or namespace name 'IEquatable<>' does not exist in the namespace 'System' (are you missing an assembly reference?) // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IEquatable<A<T>>").WithArguments("IEquatable<>", "System").WithLocation(1, 22), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(2, 8), // (2,27): error CS0234: The type or namespace name 'IEquatable<>' does not exist in the namespace 'System' (are you missing an assembly reference?) // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IEquatable<B>").WithArguments("IEquatable<>", "System").WithLocation(2, 27)); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<B>", "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "System.IEquatable<B>", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_11() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"using System; record A<T> : IEquatable<A<T>>; record B : A<int>, IEquatable<B>; "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,1): hidden CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(1, 1), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.ToString()': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,15): error CS0246: The type or namespace name 'IEquatable<>' could not be found (are you missing a using directive or an assembly reference?) // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IEquatable<A<T>>").WithArguments("IEquatable<>").WithLocation(2, 15), // (3,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(3, 8), // (3,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(3, 8), // (3,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(3, 8), // (3,20): error CS0246: The type or namespace name 'IEquatable<>' could not be found (are you missing a using directive or an assembly reference?) // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IEquatable<B>").WithArguments("IEquatable<>").WithLocation(3, 20)); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "IEquatable<B>", "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "IEquatable<B>", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_12() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); void Other(); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"record A; class Program { static void Main() { System.IEquatable<A> a = new A(); _ = a.Equals(null); } }"; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8), // (1,8): error CS0535: 'A' does not implement interface member 'IEquatable<A>.Other()' // record A; Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("A", "System.IEquatable<A>.Other()").WithLocation(1, 8)); } [Fact] public void IEquatableT_13() { var source = @"record A { internal virtual bool Equals(A other) => false; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,8): error CS0737: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is not public. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(1, 8), // (3,27): error CS8873: Record member 'A.Equals(A)' must be public. // internal virtual bool Equals(A other) => false; Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(3, 27), // (3,27): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // internal virtual bool Equals(A other) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(3, 27) ); } [Fact] public void IEquatableT_14() { var source = @"record A { public bool Equals(A other) => false; } record B : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,17): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed. // public bool Equals(A other) => false; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(3, 17), // (3,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(3, 17), // (5,8): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // record B : A Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(5, 8)); } [WorkItem(45026, "https://github.com/dotnet/roslyn/issues/45026")] [Fact] public void IEquatableT_15() { var source = @"using System; record R { bool IEquatable<R>.Equals(R other) => false; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void IEquatableT_16() { var source = @"using System; class A<T> { record B<U> : IEquatable<B<T>> { bool IEquatable<B<T>>.Equals(B<T> other) => false; bool IEquatable<B<U>>.Equals(B<U> other) => false; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,12): error CS0695: 'A<T>.B<U>' cannot implement both 'IEquatable<A<T>.B<T>>' and 'IEquatable<A<T>.B<U>>' because they may unify for some type parameter substitutions // record B<U> : IEquatable<B<T>> Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "B").WithArguments("A<T>.B<U>", "System.IEquatable<A<T>.B<T>>", "System.IEquatable<A<T>.B<U>>").WithLocation(4, 12)); } [Fact] public void InterfaceImplementation() { var source = @" interface I { int P1 { get; init; } int P2 { get; init; } int P3 { get; set; } } record R(int P1) : I { public int P2 { get; init; } int I.P3 { get; set; } public static void Main() { I r = new R(42) { P2 = 43 }; r.P3 = 44; System.Console.Write((r.P1, r.P2, r.P3)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44)", verify: Verification.Skipped /* init-only */); } [Fact] public void Initializers_01() { var src = @" using System; record C(int X) { int Z = X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Single(); Assert.Equal("C", recordDeclaration.Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclaration)); } [Fact] public void Initializers_02() { var src = @" record C(int X) { static int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,20): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // static int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 20) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; init; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_03() { var src = @" record C(int X) { const int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // const int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 19) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; init; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_04() { var src = @" using System; record C(int X) { Func<int> Z = () => X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z()); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("() => X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("lambda expression", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_05() { var src = @" using System; record Base { public Base(Func<int> X) { Console.WriteLine(X()); } public Base() {} } record C(int X) : Base(() => 100 + X++) { Func<int> Y = () => 200 + X++; Func<int> Z = () => 300 + X++; public static void Main() { var c = new C(1); Console.WriteLine(c.Y()); Console.WriteLine(c.Z()); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 101 202 303 ").VerifyDiagnostics(); } [Fact] public void SynthesizedRecordPointerProperty() { var src = @" record R(int P1, int* P2, delegate*<int> P3);"; var comp = CreateCompilation(src); var p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P1"); Assert.False(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P2"); Assert.True(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P3"); Assert.True(p.HasPointerType); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_RefOrOut() { var src = @" record R(ref int P1, out int P2); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0177: The out parameter 'P2' must be assigned to before control leaves the current method // record R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_ParamUnassigned, "R").WithArguments("P2").WithLocation(2, 8), // (2,10): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(2, 10), // (2,22): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(2, 22) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_RefOrOut_WithBase() { var src = @" record Base(int I); record R(ref int P1, out int P2) : Base(P2 = 1); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,10): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2) : Base(P2 = 1); Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(3, 10), // (3,22): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2) : Base(P2 = 1); Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(3, 22) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_In() { var src = @" record R(in int P1); public class C { public static void Main() { var r = new R(42); int i = 43; var r2 = new R(in i); System.Console.Write((r.P1, r2.P1)); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43)", verify: Verification.Skipped /* init-only */); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(in System.Int32 P1)", "R..ctor(R original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_This() { var src = @" record R(this int i); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,10): error CS0027: Keyword 'this' is not available in the current context // record R(this int i); Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(2, 10) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_Params() { var src = @" record R(params int[] Array); public class C { public static void Main() { var r = new R(42, 43); var r2 = new R(new[] { 44, 45 }); System.Console.Write((r.Array[0], r.Array[1], r2.Array[0], r2.Array[1])); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44, 45)", verify: Verification.Skipped /* init-only */); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(params System.Int32[] Array)", "R..ctor(R original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue() { var src = @" record R(int P = 42) { public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue_AndPropertyWithInitializer() { var src = @" record R(int P = 1) { public int P { get; init; } = 42; public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record R(int P = 1) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14) ); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: stfld ""int R.<P>k__BackingField"" IL_0008: ldarg.0 IL_0009: call ""object..ctor()"" IL_000e: nop IL_000f: ret }"); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue_AndPropertyWithoutInitializer() { var src = @" record R(int P = 42) { public int P { get; init; } public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record R(int P = 42) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14) ); var verifier = CompileAndVerify(comp, expectedOutput: "0", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int)", @" { // Code size 8 (0x8) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: ret }"); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue_AndPropertyWithInitializer_CopyingParameter() { var src = @" record R(int P = 42) { public int P { get; init; } = P; public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<P>k__BackingField"" IL_0007: ldarg.0 IL_0008: call ""object..ctor()"" IL_000d: nop IL_000e: ret }"); } [Fact] public void AttributesOnPrimaryConstructorParameters_01() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public record Test( [field: A] [property: B] [param: C] [D] int P1) { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => a.AttributeClass!.Name is "A" or "B" or "C" or "D")); } } [Fact] public void AttributesOnPrimaryConstructorParameters_02() { string source = @" [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class D : System.Attribute { } public record Test( [field: A] [property: B] [param: C] [D] int P1) { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_03() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public abstract int P1 { get; init; } } public record Test( [field: A] [property: B] [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_04() { string source = @" [System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = true) ] public class A : System.Attribute { } public record Test( [method: A] int P1) { [method: A] void M1() {} } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new string[] { }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new string[] { }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new string[] { }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (8,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property, param'. All attributes in this block will be ignored. // [method: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field, property, param").WithLocation(8, 6) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_05() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public virtual int P1 { get; init; } } public record Test( [field: A] [property: B] [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); Assert.Null(@class.GetMember<PropertySymbol>("P1")); Assert.Null(@class.GetMember<FieldSymbol>("<P1>k__BackingField")); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (27,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param").WithLocation(27, 6), // (28,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. // [property: B] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param").WithLocation(28, 6), // (31,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // int P1) : Base Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(31, 9) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_06() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public int P1 { get; init; } } public record Test( [field: A] [property: B] [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); Assert.Null(@class.GetMember<PropertySymbol>("P1")); Assert.Null(@class.GetMember<FieldSymbol>("<P1>k__BackingField")); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (27,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param").WithLocation(27, 6), // (28,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. // [property: B] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param").WithLocation(28, 6), // (31,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // int P1) : Base Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(31, 9) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_07() { string source = @" [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public int P1 { get; init; } } public record Test( [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (20,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // int P1) : Base Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(20, 9) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_08() { string source = @" #nullable enable using System.Diagnostics.CodeAnalysis; record C<T>([property: NotNull] T? P1, T? P2) where T : class { protected C(C<T> other) { T x = P1; T y = P2; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition, NotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = P2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P2").WithLocation(10, 15) ); } [Fact] public void AttributesOnPrimaryConstructorParameters_09_CallerMemberName() { string source = @" using System.Runtime.CompilerServices; record R([CallerMemberName] string S = """"); class C { public static void Main() { var r = new R(); System.Console.Write(r.S); } } "; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, expectedOutput: "Main", parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe, verify: Verification.Skipped /* init-only */); comp.VerifyDiagnostics(); } [Fact] public void RecordWithConstraints_NullableWarning() { var src = @" #nullable enable record R<T>(T P) where T : class; record R2<T>(T P) where T : class { } public class C { public static void Main() { var r = new R<string?>(""R""); var r2 = new R2<string?>(""R2""); System.Console.Write((r.P, r2.P)); } }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (10,23): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r = new R<string?>("R"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R<T>", "T", "string?").WithLocation(10, 23), // (11,25): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R2<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r2 = new R2<string?>("R2"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R2<T>", "T", "string?").WithLocation(11, 25) ); CompileAndVerify(comp, expectedOutput: "(R, R2)", verify: Verification.Skipped /* init-only */); } [Fact] public void RecordWithConstraints_ConstraintError() { var src = @" record R<T>(T P) where T : class; record R2<T>(T P) where T : class { } public class C { public static void Main() { _ = new R<int>(1); _ = new R2<int>(2); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,19): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R<T>' // _ = new R<int>(1); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R<T>", "T", "int").WithLocation(9, 19), // (10,20): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R2<T>' // _ = new R2<int>(2); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R2<T>", "T", "int").WithLocation(10, 20) ); } [Fact] public void AccessCheckProtected03() { CSharpCompilation c = CreateCompilation(@" record X<T> { } record A { } record B { record C : X<C.D.E> { protected record D : A { public record E { } } } } ", targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, c.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (c.Assembly.RuntimeSupportsCovariantReturnsOfClasses) { c.VerifyDiagnostics( // (8,12): error CS0060: Inconsistent accessibility: base type 'X<B.C.D.E>' is less accessible than class 'B.C' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("B.C", "X<B.C.D.E>").WithLocation(8, 12), // (8,12): error CS0051: Inconsistent accessibility: parameter type 'X<B.C.D.E>' is less accessible than method 'B.C.Equals(X<B.C.D.E>?)' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisParamType, "C").WithArguments("B.C.Equals(X<B.C.D.E>?)", "X<B.C.D.E>").WithLocation(8, 12) ); } else { c.VerifyDiagnostics( // (8,12): error CS0060: Inconsistent accessibility: base type 'X<B.C.D.E>' is less accessible than class 'B.C' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("B.C", "X<B.C.D.E>").WithLocation(8, 12), // (8,12): error CS0050: Inconsistent accessibility: return type 'X<B.C.D.E>' is less accessible than method 'B.C.<Clone>$()' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisReturnType, "C").WithArguments("B.C.<Clone>$()", "X<B.C.D.E>").WithLocation(8, 12), // (8,12): error CS0051: Inconsistent accessibility: parameter type 'X<B.C.D.E>' is less accessible than method 'B.C.Equals(X<B.C.D.E>?)' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisParamType, "C").WithArguments("B.C.Equals(X<B.C.D.E>?)", "X<B.C.D.E>").WithLocation(8, 12) ); } } [Fact] public void TestTargetType_Abstract() { var source = @" abstract record C { void M() { C x0 = new(); var x1 = (C)new(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,16): error CS0144: Cannot create an instance of the abstract type or interface 'C' // C x0 = new(); Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(6, 16), // (7,21): error CS0144: Cannot create an instance of the abstract type or interface 'C' // var x1 = (C)new(); Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(7, 21) ); } [Fact] public void CyclicBases4() { var text = @" record A<T> : B<A<T>> { } record B<T> : A<B<T>> { A<T> F() { return null; } } "; var comp = CreateCompilation(text); comp.GetDeclarationDiagnostics().Verify( // (2,8): error CS0146: Circular base type dependency involving 'B<A<T>>' and 'A<T>' // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("B<A<T>>", "A<T>").WithLocation(2, 8), // (3,8): error CS0146: Circular base type dependency involving 'A<B<T>>' and 'B<T>' // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("A<B<T>>", "B<T>").WithLocation(3, 8), // (2,8): error CS0115: 'A<T>.ToString()': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (3,8): error CS0115: 'B<T>.EqualityContract': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.EqualityContract").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.Equals(object?)': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.Equals(object?)").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.GetHashCode()': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.GetHashCode()").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.PrintMembers(StringBuilder)': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.ToString()': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.ToString()").WithLocation(3, 8) ); } [Fact] public void CS0250ERR_CallingBaseFinalizeDeprecated() { var text = @" record B { } record C : B { ~C() { base.Finalize(); // CS0250 } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (10,7): error CS0250: Do not directly call your base type Finalize method. It is called automatically from your destructor. Diagnostic(ErrorCode.ERR_CallingBaseFinalizeDeprecated, "base.Finalize()") ); } [Fact] public void PartialClassWithDifferentTupleNamesInBaseTypes() { var source = @" public record Base<T> { } public partial record C1 : Base<(int a, int b)> { } public partial record C1 : Base<(int notA, int notB)> { } public partial record C2 : Base<(int a, int b)> { } public partial record C2 : Base<(int, int)> { } public partial record C3 : Base<(int a, int b)> { } public partial record C3 : Base<(int a, int b)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,23): error CS0263: Partial declarations of 'C2' must not specify different base classes // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C2").WithArguments("C2").WithLocation(5, 23), // (3,23): error CS0263: Partial declarations of 'C1' must not specify different base classes // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C1").WithArguments("C1").WithLocation(3, 23), // (5,23): error CS0115: 'C2.ToString()': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.ToString()").WithLocation(5, 23), // (5,23): error CS0115: 'C2.EqualityContract': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.EqualityContract").WithLocation(5, 23), // (5,23): error CS0115: 'C2.Equals(object?)': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.Equals(object?)").WithLocation(5, 23), // (5,23): error CS0115: 'C2.GetHashCode()': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.GetHashCode()").WithLocation(5, 23), // (5,23): error CS0115: 'C2.PrintMembers(StringBuilder)': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 23), // (3,23): error CS0115: 'C1.ToString()': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.ToString()").WithLocation(3, 23), // (3,23): error CS0115: 'C1.EqualityContract': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.EqualityContract").WithLocation(3, 23), // (3,23): error CS0115: 'C1.Equals(object?)': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.Equals(object?)").WithLocation(3, 23), // (3,23): error CS0115: 'C1.GetHashCode()': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.GetHashCode()").WithLocation(3, 23), // (3,23): error CS0115: 'C1.PrintMembers(StringBuilder)': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 23) ); } [Fact] public void CS0267ERR_PartialMisplaced() { var test = @" partial public record C // CS0267 { } "; CreateCompilation(test).VerifyDiagnostics( // (2,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial public class C // CS0267 Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1)); } [Fact] public void AttributeContainsGeneric() { string source = @" [Goo<int>] class G { } record Goo<T> { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2) ); } [Fact] public void CS0406ERR_ClassBoundNotFirst() { var source = @"interface I { } record A { } record B { } class C<T, U> where T : I, A where U : A, B { void M<V>() where V : U, A, B { } }"; CreateCompilation(source).VerifyDiagnostics( // (5,18): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(5, 18), // (6,18): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(6, 18), // (8,30): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(8, 30), // (8,33): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(8, 33)); } [Fact] public void SealedStaticRecord() { var source = @" sealed static record R; "; CreateCompilation(source).VerifyDiagnostics( // (2,22): error CS0106: The modifier 'static' is not valid for this item // sealed static record R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 22) ); } [Fact] public void CS0513ERR_AbstractInConcreteClass02() { var text = @" record C { public abstract event System.Action E; public abstract int this[int x] { get; set; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,41): error CS0513: 'C.E' is abstract but it is contained in non-abstract type 'C' // public abstract event System.Action E; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("C.E", "C"), // (5,39): error CS0513: 'C.this[int].get' is abstract but it is contained in non-abstract type 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("C.this[int].get", "C"), // (5,44): error CS0513: 'C.this[int].set' is abstract but it is contained in non-abstract type 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("C.this[int].set", "C")); } [Fact] public void ConversionToBase() { var source = @" public record Base<T> { } public record Derived : Base<(int a, int b)> { public static explicit operator Base<(int, int)>(Derived x) { return null; } public static explicit operator Derived(Base<(int, int)> x) { return null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,37): error CS0553: 'Derived.explicit operator Derived(Base<(int, int)>)': user-defined conversions to or from a base type are not allowed // public static explicit operator Derived(Base<(int, int)> x) Diagnostic(ErrorCode.ERR_ConversionWithBase, "Derived").WithArguments("Derived.explicit operator Derived(Base<(int, int)>)").WithLocation(9, 37), // (5,37): error CS0553: 'Derived.explicit operator Base<(int, int)>(Derived)': user-defined conversions to or from a base type are not allowed // public static explicit operator Base<(int, int)>(Derived x) Diagnostic(ErrorCode.ERR_ConversionWithBase, "Base<(int, int)>").WithArguments("Derived.explicit operator Base<(int, int)>(Derived)").WithLocation(5, 37) ); } [Fact] public void CS0554ERR_ConversionWithDerived() { var text = @" public record B { public static implicit operator B(D d) // CS0554 { return null; } } public record D : B {} "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,37): error CS0554: 'B.implicit operator B(D)': user-defined conversions to or from a derived type are not allowed // public static implicit operator B(D d) // CS0554 Diagnostic(ErrorCode.ERR_ConversionWithDerived, "B").WithArguments("B.implicit operator B(D)") ); } [Fact] public void CS0574ERR_BadDestructorName() { var test = @" namespace x { public record iii { ~iiii(){} public static void Main() { } } } "; CreateCompilation(test).VerifyDiagnostics( // (6,10): error CS0574: Name of destructor must match name of type // ~iiii(){} Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(6, 10)); } [Fact] public void StaticBasePartial() { var text = @" static record NV { } public partial record C1 { } partial record C1 : NV { } public partial record C1 { } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses) { comp.VerifyDiagnostics( // (2,15): error CS0106: The modifier 'static' is not valid for this item // static record NV Diagnostic(ErrorCode.ERR_BadMemberFlag, "NV").WithArguments("static").WithLocation(2, 15), // (6,23): error CS0051: Inconsistent accessibility: parameter type 'NV' is less accessible than method 'C1.Equals(NV?)' // public partial record C1 Diagnostic(ErrorCode.ERR_BadVisParamType, "C1").WithArguments("C1.Equals(NV?)", "NV").WithLocation(6, 23), // (10,16): error CS0060: Inconsistent accessibility: base class 'NV' is less accessible than class 'C1' // partial record C1 : NV Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 16) ); } else { comp.VerifyDiagnostics( // (2,15): error CS0106: The modifier 'static' is not valid for this item // static record NV Diagnostic(ErrorCode.ERR_BadMemberFlag, "NV").WithArguments("static").WithLocation(2, 15), // (6,23): error CS0050: Inconsistent accessibility: return type 'NV' is less accessible than method 'C1.<Clone>$()' // public partial record C1 Diagnostic(ErrorCode.ERR_BadVisReturnType, "C1").WithArguments("C1.<Clone>$()", "NV").WithLocation(6, 23), // (6,23): error CS0051: Inconsistent accessibility: parameter type 'NV' is less accessible than method 'C1.Equals(NV?)' // public partial record C1 Diagnostic(ErrorCode.ERR_BadVisParamType, "C1").WithArguments("C1.Equals(NV?)", "NV").WithLocation(6, 23), // (10,16): error CS0060: Inconsistent accessibility: base class 'NV' is less accessible than class 'C1' // partial record C1 : NV Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 16) ); } } [Fact] public void StaticRecordWithConstructorAndDestructor() { var text = @" static record R(int I) { R() : this(0) { } ~R() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,15): error CS0106: The modifier 'static' is not valid for this item // static record R(int I) Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 15) ); } [Fact] public void RecordWithPartialMethodExplicitImplementation() { var source = @"record R { partial void M(); }"; CreateCompilation(source).VerifyDiagnostics( // (3,18): error CS0751: A partial method must be declared within a partial type // partial void M(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 18) ); } [Fact] public void RecordWithMultipleBaseTypes() { var source = @" record Base1; record Base2; record R : Base1, Base2 { }"; CreateCompilation(source).VerifyDiagnostics( // (4,19): error CS1721: Class 'R' cannot have multiple base classes: 'Base1' and 'Base2' // record R : Base1, Base2 Diagnostic(ErrorCode.ERR_NoMultipleInheritance, "Base2").WithArguments("R", "Base1", "Base2").WithLocation(4, 19) ); } [Fact] public void RecordWithInterfaceBeforeBase() { var source = @" record Base; interface I { } record R : I, Base; "; CreateCompilation(source).VerifyDiagnostics( // (4,15): error CS1722: Base class 'Base' must come before any interfaces // record R : I, Base; Diagnostic(ErrorCode.ERR_BaseClassMustBeFirst, "Base").WithArguments("Base").WithLocation(4, 15) ); } [Fact] public void RecordLoadedInVisualBasicDisplaysAsClass() { var src = @" public record A; "; var compRef = CreateCompilation(src).EmitToImageReference(); var vbComp = CreateVisualBasicCompilation("", referencedAssemblies: new[] { compRef }); var symbol = vbComp.GlobalNamespace.GetTypeMember("A"); Assert.False(symbol.IsRecord); Assert.Equal("class A", SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void AnalyzerActions_01() { var text1 = @" record A([Attr1]int X = 0) : I1 {} record B([Attr2]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3]int Z = 4) : base(5) {} } interface I1 {} class Attr1 : System.Attribute {} class Attr2 : System.Attribute {} class Attr3 : System.Attribute {} "; var analyzer = new AnalyzerActions_01_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount13); Assert.Equal(1, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(1, analyzer.FireCount17); Assert.Equal(1, analyzer.FireCount18); Assert.Equal(1, analyzer.FireCount19); Assert.Equal(1, analyzer.FireCount20); Assert.Equal(1, analyzer.FireCount21); Assert.Equal(1, analyzer.FireCount22); Assert.Equal(1, analyzer.FireCount23); Assert.Equal(1, analyzer.FireCount24); Assert.Equal(1, analyzer.FireCount25); Assert.Equal(1, analyzer.FireCount26); Assert.Equal(1, analyzer.FireCount27); Assert.Equal(1, analyzer.FireCount28); Assert.Equal(1, analyzer.FireCount29); Assert.Equal(1, analyzer.FireCount30); Assert.Equal(1, analyzer.FireCount31); } private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer { public int FireCount0; public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; public int FireCount13; public int FireCount14; public int FireCount15; public int FireCount16; public int FireCount17; public int FireCount18; public int FireCount19; public int FireCount20; public int FireCount21; public int FireCount22; public int FireCount23; public int FireCount24; public int FireCount25; public int FireCount26; public int FireCount27; public int FireCount28; public int FireCount29; public int FireCount30; public int FireCount31; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Handle5, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); } protected void Handle1(SyntaxNodeAnalysisContext context) { var literal = (LiteralExpressionSyntax)context.Node; switch (literal.ToString()) { case "0": Interlocked.Increment(ref FireCount0); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "1": Interlocked.Increment(ref FireCount1); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "2": Interlocked.Increment(ref FireCount2); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "3": Interlocked.Increment(ref FireCount3); Assert.Equal("System.Int32 B.M()", context.ContainingSymbol.ToTestDisplayString()); break; case "4": Interlocked.Increment(ref FireCount4); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; case "5": Interlocked.Increment(ref FireCount5); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(literal.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle2(SyntaxNodeAnalysisContext context) { var equalsValue = (EqualsValueClauseSyntax)context.Node; switch (equalsValue.ToString()) { case "= 0": Interlocked.Increment(ref FireCount15); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "= 1": Interlocked.Increment(ref FireCount16); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "= 4": Interlocked.Increment(ref FireCount6); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(equalsValue.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle3(SyntaxNodeAnalysisContext context) { var initializer = (ConstructorInitializerSyntax)context.Node; switch (initializer.ToString()) { case ": base(5)": Interlocked.Increment(ref FireCount7); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(initializer.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle4(SyntaxNodeAnalysisContext context) { Interlocked.Increment(ref FireCount8); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); } protected void Handle5(SyntaxNodeAnalysisContext context) { var baseType = (PrimaryConstructorBaseTypeSyntax)context.Node; switch (baseType.ToString()) { case "A(2)": switch (context.ContainingSymbol.ToTestDisplayString()) { case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount9); break; case "B": Interlocked.Increment(ref FireCount17); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } Assert.Same(baseType.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle6(SyntaxNodeAnalysisContext context) { var record = (RecordDeclarationSyntax)context.Node; switch (context.ContainingSymbol.ToTestDisplayString()) { case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount10); break; case "B": Interlocked.Increment(ref FireCount11); break; case "A": Interlocked.Increment(ref FireCount12); break; case "C": Interlocked.Increment(ref FireCount13); break; case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount14); break; default: Assert.True(false); break; } Assert.Same(record.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle7(SyntaxNodeAnalysisContext context) { var identifier = (IdentifierNameSyntax)context.Node; switch (identifier.Identifier.ValueText) { case "A": switch (identifier.Parent!.ToString()) { case "A(2)": Interlocked.Increment(ref FireCount18); Assert.Equal("B", context.ContainingSymbol.ToTestDisplayString()); break; case "A": Interlocked.Increment(ref FireCount19); Assert.Equal(SyntaxKind.SimpleBaseType, identifier.Parent.Kind()); Assert.Equal("C", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } break; case "Attr1": Interlocked.Increment(ref FireCount24); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "Attr2": Interlocked.Increment(ref FireCount25); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "Attr3": Interlocked.Increment(ref FireCount26); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; } } protected void Handle8(SyntaxNodeAnalysisContext context) { var baseType = (SimpleBaseTypeSyntax)context.Node; switch (baseType.ToString()) { case "I1": switch (context.ContainingSymbol.ToTestDisplayString()) { case "A": Interlocked.Increment(ref FireCount20); break; case "B": Interlocked.Increment(ref FireCount21); break; case "C": Interlocked.Increment(ref FireCount22); break; default: Assert.True(false); break; } break; case "A": switch (context.ContainingSymbol.ToTestDisplayString()) { case "C": Interlocked.Increment(ref FireCount23); break; default: Assert.True(false); break; } break; case "System.Attribute": break; default: Assert.True(false); break; } } protected void Handle9(SyntaxNodeAnalysisContext context) { var parameterList = (ParameterListSyntax)context.Node; switch (parameterList.ToString()) { case "([Attr1]int X = 0)": Interlocked.Increment(ref FireCount27); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "([Attr2]int Y = 1)": Interlocked.Increment(ref FireCount28); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "([Attr3]int Z = 4)": Interlocked.Increment(ref FireCount29); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; case "()": break; default: Assert.True(false); break; } } protected void Handle10(SyntaxNodeAnalysisContext context) { var argumentList = (ArgumentListSyntax)context.Node; switch (argumentList.ToString()) { case "(2)": Interlocked.Increment(ref FireCount30); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "(5)": Interlocked.Increment(ref FireCount31); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_02() { var text1 = @" record A(int X = 0) {} record C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_02_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); } private class AnalyzerActions_02_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.Method); context.RegisterSymbolAction(Handle, SymbolKind.Property); context.RegisterSymbolAction(Handle, SymbolKind.Parameter); context.RegisterSymbolAction(Handle, SymbolKind.NamedType); } private void Handle(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount2); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount6); break; case "C": Interlocked.Increment(ref FireCount7); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_03() { var text1 = @" record A(int X = 0) {} record C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_03_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(0, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(0, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); } private class AnalyzerActions_03_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolStartAction(Handle1, SymbolKind.Method); context.RegisterSymbolStartAction(Handle1, SymbolKind.Property); context.RegisterSymbolStartAction(Handle1, SymbolKind.Parameter); context.RegisterSymbolStartAction(Handle1, SymbolKind.NamedType); } private void Handle1(SymbolStartAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); context.RegisterSymbolEndAction(Handle2); break; case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount2); context.RegisterSymbolEndAction(Handle3); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); context.RegisterSymbolEndAction(Handle4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount9); Assert.Equal(0, FireCount1); Assert.Equal(0, FireCount2); Assert.Equal(0, FireCount6); Assert.Equal(0, FireCount7); context.RegisterSymbolEndAction(Handle5); break; case "C": Interlocked.Increment(ref FireCount10); Assert.Equal(0, FireCount4); Assert.Equal(0, FireCount8); context.RegisterSymbolEndAction(Handle6); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { Assert.Equal("A..ctor([System.Int32 X = 0])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); } private void Handle3(SymbolAnalysisContext context) { Assert.Equal("System.Int32 A.X { get; init; }", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); } private void Handle4(SymbolAnalysisContext context) { Assert.Equal("C..ctor([System.Int32 Z = 4])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); } private void Handle5(SymbolAnalysisContext context) { Assert.Equal("A", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount11); Assert.Equal(1, FireCount1); Assert.Equal(1, FireCount2); Assert.Equal(1, FireCount6); Assert.Equal(1, FireCount7); } private void Handle6(SymbolAnalysisContext context) { Assert.Equal("C", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount12); Assert.Equal(1, FireCount4); Assert.Equal(1, FireCount8); } } [Fact] public void AnalyzerActions_04() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_04_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(0, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount13); Assert.Equal(1, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(1, analyzer.FireCount17); } private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; public int FireCount13; public int FireCount14; public int FireCount15; public int FireCount16; public int FireCount17; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationAction(Handle1, OperationKind.ConstructorBody); context.RegisterOperationAction(Handle2, OperationKind.Invocation); context.RegisterOperationAction(Handle3, OperationKind.Literal); context.RegisterOperationAction(Handle4, OperationKind.ParameterInitializer); context.RegisterOperationAction(Handle5, OperationKind.PropertyInitializer); context.RegisterOperationAction(Handle5, OperationKind.FieldInitializer); } protected void Handle1(OperationAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind()); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind()); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); Assert.Equal(SyntaxKind.ConstructorDeclaration, context.Operation.Syntax.Kind()); break; default: Assert.True(false); break; } } protected void Handle2(OperationAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount4); Assert.Equal(SyntaxKind.PrimaryConstructorBaseType, context.Operation.Syntax.Kind()); VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation, @" IInvocationOperation ( A..ctor([System.Int32 X = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'A(2)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'A(2)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') 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) "); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount5); Assert.Equal(SyntaxKind.BaseConstructorInitializer, context.Operation.Syntax.Kind()); VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation, @" IInvocationOperation ( A..ctor([System.Int32 X = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base(5)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: ': base(5)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '5') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') 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) "); break; default: Assert.True(false); break; } } protected void Handle3(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "100": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); break; case "0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); break; case "200": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); break; case "1": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount9); break; case "2": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount10); break; case "300": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount11); break; case "4": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount12); break; case "5": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount13); break; case "3": Assert.Equal("System.Int32 B.M()", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount17); break; default: Assert.True(false); break; } } protected void Handle4(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "= 0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount14); break; case "= 1": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount15); break; case "= 4": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount16); break; default: Assert.True(false); break; } } protected void Handle5(OperationAnalysisContext context) { Assert.True(false); } } [Fact] public void AnalyzerActions_05() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_05_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockAction(Handle); } private void Handle(OperationBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); Assert.Equal(3, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind); Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString()); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); Assert.Equal(4, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind); Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString()); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4); Assert.Equal(1, context.OperationBlocks.Length); Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_06() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_06_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount100); Assert.Equal(1, analyzer.FireCount200); Assert.Equal(1, analyzer.FireCount300); Assert.Equal(1, analyzer.FireCount400); Assert.Equal(0, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount13); Assert.Equal(1, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(1, analyzer.FireCount17); Assert.Equal(1, analyzer.FireCount1000); Assert.Equal(1, analyzer.FireCount2000); Assert.Equal(1, analyzer.FireCount3000); Assert.Equal(1, analyzer.FireCount4000); } private class AnalyzerActions_06_Analyzer : AnalyzerActions_04_Analyzer { public int FireCount100; public int FireCount200; public int FireCount300; public int FireCount400; public int FireCount1000; public int FireCount2000; public int FireCount3000; public int FireCount4000; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle); } private void Handle(OperationBlockStartAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount100); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount200); Assert.Equal(3, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind); Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString()); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount300); Assert.Equal(4, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind); Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString()); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount400); Assert.Equal(1, context.OperationBlocks.Length); Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; default: Assert.True(false); break; } } private void RegisterOperationAction(OperationBlockStartAnalysisContext context) { context.RegisterOperationAction(Handle1, OperationKind.ConstructorBody); context.RegisterOperationAction(Handle2, OperationKind.Invocation); context.RegisterOperationAction(Handle3, OperationKind.Literal); context.RegisterOperationAction(Handle4, OperationKind.ParameterInitializer); context.RegisterOperationAction(Handle5, OperationKind.PropertyInitializer); context.RegisterOperationAction(Handle5, OperationKind.FieldInitializer); } private void Handle6(OperationBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1000); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2000); Assert.Equal(3, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind); Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString()); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3000); Assert.Equal(4, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind); Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString()); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4000); Assert.Equal(1, context.OperationBlocks.Length); Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_07() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_07_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(Handle); } private void Handle(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1); break; default: Assert.True(false); break; } break; case "B..ctor([System.Int32 Y = 1])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }: Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } break; case "C..ctor([System.Int32 Z = 4])": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }: Interlocked.Increment(ref FireCount3); break; default: Assert.True(false); break; } break; case "System.Int32 B.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_08() { var text1 = @" record A([Attr1]int X = 0) : I1 {} record B([Attr2]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_08_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount100); Assert.Equal(1, analyzer.FireCount200); Assert.Equal(1, analyzer.FireCount300); Assert.Equal(1, analyzer.FireCount400); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(0, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(0, analyzer.FireCount10); Assert.Equal(0, analyzer.FireCount11); Assert.Equal(0, analyzer.FireCount12); Assert.Equal(0, analyzer.FireCount13); Assert.Equal(0, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(0, analyzer.FireCount17); Assert.Equal(0, analyzer.FireCount18); Assert.Equal(0, analyzer.FireCount19); Assert.Equal(0, analyzer.FireCount20); Assert.Equal(0, analyzer.FireCount21); Assert.Equal(0, analyzer.FireCount22); Assert.Equal(0, analyzer.FireCount23); Assert.Equal(1, analyzer.FireCount24); Assert.Equal(1, analyzer.FireCount25); Assert.Equal(1, analyzer.FireCount26); Assert.Equal(0, analyzer.FireCount27); Assert.Equal(0, analyzer.FireCount28); Assert.Equal(0, analyzer.FireCount29); Assert.Equal(1, analyzer.FireCount30); Assert.Equal(1, analyzer.FireCount31); Assert.Equal(1, analyzer.FireCount1000); Assert.Equal(1, analyzer.FireCount2000); Assert.Equal(1, analyzer.FireCount3000); Assert.Equal(1, analyzer.FireCount4000); } private class AnalyzerActions_08_Analyzer : AnalyzerActions_01_Analyzer { public int FireCount100; public int FireCount200; public int FireCount300; public int FireCount400; public int FireCount1000; public int FireCount2000; public int FireCount3000; public int FireCount4000; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(Handle); } private void Handle(CodeBlockStartAnalysisContext<SyntaxKind> context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount100); break; default: Assert.True(false); break; } break; case "B..ctor([System.Int32 Y = 1])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }: Interlocked.Increment(ref FireCount200); break; default: Assert.True(false); break; } break; case "C..ctor([System.Int32 Z = 4])": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }: Interlocked.Increment(ref FireCount300); break; default: Assert.True(false); break; } break; case "System.Int32 B.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount400); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Handle5, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); context.RegisterCodeBlockEndAction(Handle11); } private void Handle11(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1000); break; default: Assert.True(false); break; } break; case "B..ctor([System.Int32 Y = 1])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }: Interlocked.Increment(ref FireCount2000); break; default: Assert.True(false); break; } break; case "C..ctor([System.Int32 Z = 4])": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }: Interlocked.Increment(ref FireCount3000); break; default: Assert.True(false); break; } break; case "System.Int32 B.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4000); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_09() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_09_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); } private class AnalyzerActions_09_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle1, SymbolKind.Method); context.RegisterSymbolAction(Handle2, SymbolKind.Property); context.RegisterSymbolAction(Handle3, SymbolKind.Parameter); } private void Handle1(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount5); break; case "System.Int32 B.Y { get; init; }": Interlocked.Increment(ref FireCount6); break; default: Assert.True(false); break; } } private void Handle3(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount7); break; case "[System.Int32 Y = 1]": Interlocked.Increment(ref FireCount8); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount9); break; default: Assert.True(false); break; } } } [Fact] [WorkItem(46657, "https://github.com/dotnet/roslyn/issues/46657")] public void CanDeclareIteratorInRecord() { var source = @" using System.Collections.Generic; public record X(int a) { public static void Main() { foreach(var i in new X(42).GetItems()) { System.Console.Write(i); } } public IEnumerable<int> GetItems() { yield return a; yield return a + 1; } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9) .VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "4243", verify: Verification.Skipped /* init-only */); } [Fact] public void DefaultCtor_01() { var src = @" record C { } class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); } [Fact] public void DefaultCtor_02() { var src = @" record B(int x); record C : B { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,8): error CS1729: 'B' does not contain a constructor that takes 0 arguments // record C : B Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(4, 8) ); } [Fact] public void DefaultCtor_03() { var src = @" record C { public C(C c){} } class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); } [Fact] public void DefaultCtor_04() { var src = @" record B(int x); record C : B { public C(C c) : base(c) {} } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,8): error CS1729: 'B' does not contain a constructor that takes 0 arguments // record C : B Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(4, 8) ); } [Fact] public void DefaultCtor_05() { var src = @" record C(int x); class Program { static void Main() { _ = new C(); } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (8,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'C.C(int)' // _ = new C(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("x", "C.C(int)").WithLocation(8, 17) ); } [Fact] public void DefaultCtor_06() { var src = @" record C { C(int x) {} } class Program { static void Main() { _ = new C(); } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (11,17): error CS1729: 'C' does not contain a constructor that takes 0 arguments // _ = new C(); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("C", "0").WithLocation(11, 17) ); } [Fact] public void DefaultCtor_07() { var src = @" class C { C(C x) {} } class Program { static void Main() { _ = new C(); } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (11,17): error CS1729: 'C' does not contain a constructor that takes 0 arguments // _ = new C(); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("C", "0").WithLocation(11, 17) ); } [Fact] [WorkItem(47867, "https://github.com/dotnet/roslyn/issues/47867")] public void ToString_RecordWithStaticMembers() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); record C1(int I1) { public static int field1 = 44; public const int field2 = 44; public static int P1 { set { } } public static int P2 { get { return 1; } set { } } public static int P3 { get { return 1; } } } "; var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.ReleaseExe); CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compDebug.VerifyEmitDiagnostics(); CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compRelease.VerifyEmitDiagnostics(); } [Fact] [WorkItem(47867, "https://github.com/dotnet/roslyn/issues/47867")] public void ToString_NestedRecord() { var src = @" var c1 = new Outer.C1(42); System.Console.Write(c1.ToString()); public class Outer { public record C1(int I1); } "; var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.ReleaseExe); CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compDebug.VerifyEmitDiagnostics(); CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compRelease.VerifyEmitDiagnostics(); } [Fact] public void ToString_Cycle_01() { var src = @" using System; var rec = new Rec(); rec.Inner = rec; try { rec.ToString(); } catch (Exception ex) { Console.Write(ex.GetType().FullName); } public record Rec { public Rec Inner; } "; CompileAndVerify(src, expectedOutput: "System.InsufficientExecutionStackException"); } [Fact] public void ToString_Cycle_02() { var src = @" using System; var rec = new Rec(); rec.Inner = rec; try { rec.ToString(); } catch (Exception ex) { Console.Write(ex.GetType().FullName); } public record Base { public Rec Inner; } public record Rec : Base { } "; CompileAndVerify(src, expectedOutput: "System.InsufficientExecutionStackException"); } [Fact] public void ToString_Cycle_03() { var src = @" using System; var rec = new Rec(); rec.RecStruct.Rec = rec; try { rec.ToString(); } catch (Exception ex) { Console.Write(ex.GetType().FullName); } public record Rec { public RecStruct RecStruct; } public record struct RecStruct { public Rec Rec; } "; CompileAndVerify(src, expectedOutput: "System.InsufficientExecutionStackException"); } [Fact] public void ToString_Cycle_04() { var src = @" public record Rec { public RecStruct RecStruct; } public record struct RecStruct { public Rec Rec; } "; var comp = CreateCompilation(src); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("Rec.PrintMembers", @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""RecStruct = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldflda ""RecStruct Rec.RecStruct"" IL_0018: constrained. ""RecStruct"" IL_001e: callvirt ""string object.ToString()"" IL_0023: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0028: pop IL_0029: ldc.i4.1 IL_002a: ret }"); comp.MakeMemberMissing(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__EnsureSufficientExecutionStack); verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("Rec.PrintMembers", @" { // Code size 38 (0x26) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""RecStruct = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldflda ""RecStruct Rec.RecStruct"" IL_0013: constrained. ""RecStruct"" IL_0019: callvirt ""string object.ToString()"" IL_001e: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0023: pop IL_0024: ldc.i4.1 IL_0025: ret }"); } [Fact] [WorkItem(50040, "https://github.com/dotnet/roslyn/issues/50040")] public void RaceConditionInAddMembers() { var src = @" #nullable enable using System; using System.Linq.Expressions; using System.Threading.Tasks; var collection = new Collection<Hamster>(); Hamster h = null!; await collection.MethodAsync(entity => entity.Name! == ""bar"", h); public record Collection<T> where T : Document { public Task MethodAsync<TDerived>(Expression<Func<TDerived, bool>> filter, TDerived td) where TDerived : T => throw new NotImplementedException(); public Task MethodAsync<TDerived2>(Task<TDerived2> filterDefinition, TDerived2 td) where TDerived2 : T => throw new NotImplementedException(); } public sealed record HamsterCollection : Collection<Hamster> { } public abstract class Document { } public sealed class Hamster : Document { public string? Name { get; private set; } } "; for (int i = 0; i < 100; i++) { var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); } } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact] public void XmlDoc_RecordClass() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record class C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Cref() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for <see cref=""I1""/></param> public record C(int I1) { /// <summary>Summary</summary> /// <param name=""x"">Description for <see cref=""x""/></param> public void M(int x) { } } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,52): warning CS1574: XML comment has cref attribute 'x' that could not be resolved // /// <param name="x">Description for <see cref="x"/></param> Diagnostic(ErrorCode.WRN_BadXMLRef, "x").WithArguments("x").WithLocation(7, 52) ); var tree = comp.SyntaxTrees.Single(); var docComments = tree.GetCompilationUnitRoot().DescendantTrivia().Select(trivia => trivia.GetStructure()).OfType<DocumentationCommentTriviaSyntax>(); var cref = docComments.First().DescendantNodes().OfType<XmlCrefAttributeSyntax>().First().Cref; Assert.Equal("I1", cref.ToString()); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal(SymbolKind.Property, model.GetSymbolInfo(cref).Symbol!.Kind); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Error() { var src = @" /// <summary>Summary</summary> /// <param name=""Error""></param> /// <param name=""I1""></param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (3,18): warning CS1572: XML comment has a param tag for 'Error', but there is no parameter by that name // /// <param name="Error"></param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Error").WithArguments("Error").WithLocation(3, 18), // (3,18): warning CS1572: XML comment has a param tag for 'Error', but there is no parameter by that name // /// <param name="Error"></param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Error").WithArguments("Error").WithLocation(3, 18) ); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Duplicate() { var src = @" /// <summary>Summary</summary> /// <param name=""I1""></param> /// <param name=""I1""></param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (4,12): warning CS1571: XML comment has a duplicate param tag for 'I1' // /// <param name="I1"></param> Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""I1""").WithArguments("I1").WithLocation(4, 12), // (4,12): warning CS1571: XML comment has a duplicate param tag for 'I1' // /// <param name="I1"></param> Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""I1""").WithArguments("I1").WithLocation(4, 12) ); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_ParamRef() { var src = @" /// <summary>Summary <paramref name=""I1""/></summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary <paramref name=""I1""/></summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_ParamRef_Error() { var src = @" /// <summary>Summary <paramref name=""Error""/></summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,38): warning CS1734: XML comment on 'C' has a paramref tag for 'Error', but there is no parameter by that name // /// <summary>Summary <paramref name="Error"/></summary> Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "Error").WithArguments("Error", "C").WithLocation(2, 38), // (2,38): warning CS1734: XML comment on 'C.C(int)' has a paramref tag for 'Error', but there is no parameter by that name // /// <summary>Summary <paramref name="Error"/></summary> Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "Error").WithArguments("Error", "C.C(int)").WithLocation(2, 38) ); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_WithExplicitProperty() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record C(int I1) { /// <summary>Property summary</summary> public int I1 { get; init; } = I1; } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal( @"<member name=""P:C.I1""> <summary>Property summary</summary> </member> ", property.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_EmptyParameterList() { var src = @" /// <summary>Summary</summary> public record C(); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.IsEmpty).Single(); Assert.Equal( @"<member name=""M:C.#ctor""> <summary>Summary</summary> </member> ", constructor.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListSecond() { var src = @" public partial record C; /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var c = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", c.GetDocumentationCommentXml()); var cConstructor = c.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cConstructor.GetDocumentationCommentXml()); Assert.Equal("", cConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", c.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListFirst() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record D(int I1); public partial record D; namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var d = comp.GetMember<NamedTypeSymbol>("D"); Assert.Equal( @"<member name=""T:D""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", d.GetDocumentationCommentXml()); var dConstructor = d.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:D.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", dConstructor.GetDocumentationCommentXml()); Assert.Equal("", dConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", d.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListFirst_XmlDocSecond() { var src = @" public partial record E(int I1); /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record E; namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)' // public partial record E(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(2, 23), // (5,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(5, 18) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal("", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListSecond_XmlDocFirst() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record E; public partial record E(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (3,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(3, 18), // (6,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)' // public partial record E(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(6, 23) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal("", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DuplicateParameterList_XmlDocSecond() { var src = @" public partial record C(int I1); /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'C.C(int)' // public partial record C(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "C").WithArguments("C.C(int)").WithLocation(2, 23), // (5,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(5, 18), // (6,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record C(int I1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(6, 24) ); var c = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", c.GetDocumentationCommentXml()); var cConstructor = c.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, cConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal("", cConstructor.GetDocumentationCommentXml()); Assert.Equal("", cConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", c.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DuplicateParameterList_XmlDocFirst() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record D(int I1); public partial record D(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (6,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record D(int I1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(6, 24) ); var d = comp.GetMember<NamedTypeSymbol>("D"); Assert.Equal( @"<member name=""T:D""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", d.GetDocumentationCommentXml()); var dConstructor = d.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:D.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", dConstructor.GetDocumentationCommentXml()); Assert.Equal("", dConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", d.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DuplicateParameterList_XmlDocOnBoth() { var src = @" /// <summary>Summary1</summary> /// <param name=""I1"">Description1 for I1</param> public partial record E(int I1); /// <summary>Summary2</summary> /// <param name=""I1"">Description2 for I1</param> public partial record E(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description2 for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(7, 18), // (8,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record E(int I1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(8, 24) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> <summary>Summary2</summary> <param name=""I1"">Description2 for I1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal( @"<member name=""M:E.#ctor(System.Int32)""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> </member> ", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DifferentParameterLists_XmlDocSecond() { var src = @" public partial record E(int I1); /// <summary>Summary2</summary> /// <param name=""S1"">Description2 for S1</param> public partial record E(string S1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)' // public partial record E(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(2, 23), // (5,18): warning CS1572: XML comment has a param tag for 'S1', but there is no parameter by that name // /// <param name="S1">Description2 for S1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "S1").WithArguments("S1").WithLocation(5, 18), // (6,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record E(string S1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(string S1)").WithLocation(6, 24) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary2</summary> <param name=""S1"">Description2 for S1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal("", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DifferentParameterLists_XmlDocOnBoth() { var src = @" /// <summary>Summary1</summary> /// <param name=""I1"">Description1 for I1</param> public partial record E(int I1); /// <summary>Summary2</summary> /// <param name=""S1"">Description2 for S1</param> public partial record E(string S1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,18): warning CS1572: XML comment has a param tag for 'S1', but there is no parameter by that name // /// <param name="S1">Description2 for S1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "S1").WithArguments("S1").WithLocation(7, 18), // (8,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record E(string S1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(string S1)").WithLocation(8, 24) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> <summary>Summary2</summary> <param name=""S1"">Description2 for S1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal( @"<member name=""M:E.#ctor(System.Int32)""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> </member> ", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Nested() { var src = @" /// <summary>Summary</summary> public class Outer { /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("Outer.C"); Assert.Equal( @"<member name=""T:Outer.C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:Outer.C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Nested_ReferencingOuterParam() { var src = @" /// <summary>Summary</summary> /// <param name=""O1"">Description for O1</param> public record Outer(object O1) { /// <summary>Summary</summary> public int P1 { get; set; } /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> /// <param name=""O1"">Error O1</param> /// <param name=""P1"">Error P1</param> /// <param name=""C"">Error C</param> public record C(int I1); } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (11,22): warning CS1572: XML comment has a param tag for 'O1', but there is no parameter by that name // /// <param name="O1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "O1").WithArguments("O1").WithLocation(11, 22), // (11,22): warning CS1572: XML comment has a param tag for 'O1', but there is no parameter by that name // /// <param name="O1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "O1").WithArguments("O1").WithLocation(11, 22), // (12,22): warning CS1572: XML comment has a param tag for 'P1', but there is no parameter by that name // /// <param name="P1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "P1").WithArguments("P1").WithLocation(12, 22), // (12,22): warning CS1572: XML comment has a param tag for 'P1', but there is no parameter by that name // /// <param name="P1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "P1").WithArguments("P1").WithLocation(12, 22), // (13,22): warning CS1572: XML comment has a param tag for 'C', but there is no parameter by that name // /// <param name="C">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "C").WithArguments("C").WithLocation(13, 22), // (13,22): warning CS1572: XML comment has a param tag for 'C', but there is no parameter by that name // /// <param name="C">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "C").WithArguments("C").WithLocation(13, 22) ); var cMember = comp.GetMember<NamedTypeSymbol>("Outer.C"); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:Outer.C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> <param name=""O1"">Error O1</param> <param name=""P1"">Error P1</param> <param name=""C"">Error C</param> </member> ", constructor.GetDocumentationCommentXml()); } [Fact, WorkItem(51590, "https://github.com/dotnet/roslyn/issues/51590")] public void SealedIncomplete() { var source = @" public sealed record("; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,21): error CS1001: Identifier expected // public sealed record( Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(2, 21), // (2,22): error CS1026: ) expected // public sealed record( Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(2, 22), // (2,22): error CS1514: { expected // public sealed record( Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(2, 22), // (2,22): error CS1513: } expected // public sealed record( Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(2, 22) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } // hiding } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } // hiding Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Field() { var source = @" public record Base { public int I = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } // hiding } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } // hiding Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Field_HiddenWithConstant() { var source = @" public record Base { public int I = 0; public Base(int ignored) { } } public record C(int I) : Base(I) { public const int I = 0; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,22): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public const int I = 0; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 22) ); } [Fact] public void FieldAsPositionalMember() { var source = @" var a = new A(42); System.Console.Write(a.X); System.Console.Write("" - ""); a.Deconstruct(out int x); System.Console.Write(x); record A(int X) { public int X = X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,10): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(8, 10) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42"); verifier.VerifyIL("A.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_TwoParameters() { var source = @" var a = new A(42, 43); System.Console.Write(a.Y); System.Console.Write("" - ""); a.Deconstruct(out int x, out int y); System.Console.Write(y); record A(int X, int Y) { public int X = X; public int Y = Y; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "43 - 43"); verifier.VerifyIL("A.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: ldfld ""int A.Y"" IL_000f: stind.i4 IL_0010: ret } "); } [Fact] public void FieldAsPositionalMember_Readonly() { var source = @" var a = new A(42); System.Console.Write(a.X); System.Console.Write("" - ""); a.Deconstruct(out int x); System.Console.Write(x); record A(int X) { public readonly int X = X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("A.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_UnusedParameter() { var source = @" record A(int X) { public int X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14), // (4,16): warning CS0649: Field 'A.X' is never assigned to, and will always have its default value 0 // public int X; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "X").WithArguments("A.X", "0").WithLocation(4, 16) ); } [Fact] public void FieldAsPositionalMember_CurrentTypeComesFirst() { var source = @" var c = new C(42); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I { get; set; } = 0; } public record C(int I) : Base { public int I = I; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,16): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public int I = I; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(12, 16) ); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int C.I"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_CurrentTypeComesFirst_FieldInBase() { var source = @" var c = new C(42); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I = 0; } public record C(int I) : Base { public int I { get; set; } = I; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,16): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public int I { get; set; } = I; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(12, 16) ); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int C.I.get"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_FieldFromBase() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int Base.I"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_FieldFromBase_StaticFieldInDerivedType() { var source = @" public record Base { public int I = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public static int I = 42; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public static int I = 42; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23) ); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public static int I = 42; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23) ); source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public static int I { get; set; } = 42; } "; comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public static int I { get; set; } = 42; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23) ); } [Fact] public void FieldAsPositionalMember_Static() { var source = @" record A(int X) { public static int X = 0; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record A(int X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 14) ); } [Fact] public void FieldAsPositionalMember_Const() { var src = @" record C(int P) { const int P = 4; } record C2(int P) { const int P = P; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (2,14): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'. // record C(int P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int", "P").WithLocation(2, 14), // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C(int P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14), // (6,15): error CS8866: Record member 'C2.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'. // record C2(int P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C2.P", "int", "P").WithLocation(6, 15), // (6,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C2(int P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(6, 15), // (8,15): error CS0110: The evaluation of the constant value for 'C2.P' involves a circular definition // const int P = P; Diagnostic(ErrorCode.ERR_CircConstValue, "P").WithArguments("C2.P").WithLocation(8, 15) ); } [Fact] public void FieldAsPositionalMember_Volatile() { var src = @" record C(int P) { public volatile int P = P; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); } [Fact] public void FieldAsPositionalMember_DifferentAccessibility() { var src = @" record C(int P) { private int P = P; } record C2(int P) { protected int P = P; } record C3(int P) { internal int P = P; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); } [Fact] public void FieldAsPositionalMember_WrongType() { var src = @" record C(int P) { public string P = null; public int Q = P; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (2,14): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'. // record C(int P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int", "P").WithLocation(2, 14) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } } "; var expected = new[] { // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(expected); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expected); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod_DeconstructInSource() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } public void Deconstruct(out int i) { i = 0; } } "; var expected = new[] { // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(expected); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expected); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod_WithNew() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) // 1 { public new void I() { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) // 1 Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithGenericMethod() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I<T>() { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (11,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(11, 21), // (13,17): warning CS0108: 'C.I<T>()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I<T>() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I<T>()", "Base.I").WithLocation(13, 17) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_FromGrandBase() { var source = @" public record GrandBase { public int I { get; set; } = 42; } public record Base : GrandBase { public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } } "; var expected = new[] { // (10,21): error CS8913: The positional member 'GrandBase.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("GrandBase.I").WithLocation(10, 21), // (12,17): warning CS0108: 'C.I()' hides inherited member 'GrandBase.I'. Use the new keyword if hiding was intended. // public void I() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "GrandBase.I").WithLocation(12, 17) }; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expected); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_NotHiddenByIndexer() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int Item { get; set; } = 42; public Base(int ignored) { } } public record C(int Item) : Base(Item) { public int this[int x] { get => throw null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int Base.Item.get"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_NotHiddenByIndexer_WithIndexerName() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { [System.Runtime.CompilerServices.IndexerName(""I"")] public int this[int x] { get => throw null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int Base.I.get"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithType() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public class I { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,18): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public class I { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 18) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithEvent() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public event System.Action I; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,32): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public event System.Action I; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 32), // (9,32): warning CS0067: The event 'C.I' is never used // public event System.Action I; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "I").WithArguments("C.I").WithLocation(9, 32) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithConstant() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public const string I = null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,25): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public const string I = null; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 25) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_AbstractInBase() { var source = @" abstract record Base { public abstract int I { get; init; } } record Derived(int I) : Base { public int I() { return 0; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (8,16): warning CS0108: 'Derived.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public int I() { return 0; } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("Derived.I()", "Base.I").WithLocation(8, 16), // (8,16): error CS0102: The type 'Derived' already contains a definition for 'I' // public int I() { return 0; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("Derived", "I").WithLocation(8, 16) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_AbstractInBase_AbstractInDerived() { var source = @" abstract record Base { public abstract int I { get; init; } } abstract record Derived(int I) : Base { public int I() { return 0; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (8,16): error CS0533: 'Derived.I()' hides inherited abstract member 'Base.I' // public int I() { return 0; } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "I").WithArguments("Derived.I()", "Base.I").WithLocation(8, 16), // (8,16): error CS0102: The type 'Derived' already contains a definition for 'I' // public int I() { return 0; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("Derived", "I").WithLocation(8, 16) ); } [Fact] public void InterfaceWithParameters() { var src = @" public interface I { } record R(int X) : I() { } record R2(int X) : I(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,20): error CS8861: Unexpected argument list. // record R(int X) : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 20), // (10,21): error CS8861: Unexpected argument list. // record R2(int X) : I(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 21), // (10,21): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R2(int X) : I(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(10, 21) ); } [Fact] public void InterfaceWithParameters_RecordClass() { var src = @" public interface I { } record class R(int X) : I() { } record class R2(int X) : I(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,26): error CS8861: Unexpected argument list. // record class R(int X) : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 26), // (10,27): error CS8861: Unexpected argument list. // record class R2(int X) : I(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 27), // (10,27): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record class R2(int X) : I(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(10, 27) ); } [Fact] public void BaseErrorTypeWithParameters() { var src = @" record R2(int X) : Error(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0115: 'R2.ToString()': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'R2.EqualityContract': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'R2.Equals(object?)': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'R2.GetHashCode()': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'R2.PrintMembers(StringBuilder)': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,20): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(2, 20), // (2,25): error CS1729: 'Error' does not contain a constructor that takes 1 arguments // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("Error", "1").WithLocation(2, 25) ); } [Fact] public void BaseDynamicTypeWithParameters() { var src = @" record R(int X) : dynamic(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,19): error CS1965: 'R': cannot derive from the dynamic type // record R(int X) : dynamic(X) Diagnostic(ErrorCode.ERR_DeriveFromDynamic, "dynamic").WithArguments("R").WithLocation(2, 19), // (2,26): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : dynamic(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 26) ); } [Fact] public void BaseTypeParameterTypeWithParameters() { var src = @" class C<T> { record R(int X) : T(X) { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,23): error CS0689: Cannot derive from 'T' because it is a type parameter // record R(int X) : T(X) Diagnostic(ErrorCode.ERR_DerivingFromATyVar, "T").WithArguments("T").WithLocation(4, 23), // (4,24): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : T(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(4, 24) ); } [Fact] public void BaseObjectTypeWithParameters() { var src = @" record R(int X) : object(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,25): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : object(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 25) ); } [Fact] public void BaseValueTypeTypeWithParameters() { var src = @" record R(int X) : System.ValueType(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,19): error CS0644: 'R' cannot derive from special class 'ValueType' // record R(int X) : System.ValueType(X) Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "System.ValueType").WithArguments("R", "System.ValueType").WithLocation(2, 19), // (2,35): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : System.ValueType(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 35) ); } [Fact] public void InterfaceWithParameters_NoPrimaryConstructor() { var src = @" public interface I { } record R : I() { } record R2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,13): error CS8861: Unexpected argument list. // record R : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 13), // (10,14): error CS8861: Unexpected argument list. // record R2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 14) ); } [Fact] public void InterfaceWithParameters_Class() { var src = @" public interface I { } class C : I() { } class C2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,12): error CS8861: Unexpected argument list. // class C : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 12), // (10,13): error CS8861: Unexpected argument list. // class C2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 13) ); } [Theory, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [CombinatorialData] public void CrossAssemblySupportingAndNotSupportingCovariantReturns(bool useCompilationReference) { var sourceA = @"public record B(int I) { } public record C(int I) : B(I);"; var compA = CreateEmptyCompilation(new[] { sourceA, IsExternalInitTypeDefinition }, references: TargetFrameworkUtil.GetReferences(TargetFramework.NetStandard20)); compA.VerifyDiagnostics(); Assert.False(compA.Assembly.RuntimeSupportsCovariantReturnsOfClasses); var actualMembers = compA.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 I)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(B? other)", "System.Boolean C.Equals(C? other)", "B C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 I)", }; AssertEx.Equal(expectedMembers, actualMembers); var refA = useCompilationReference ? compA.ToMetadataReference() : compA.EmitToImageReference(); var sourceB = "record D(int I) : C(I);"; // CS1701: Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy var compB = CreateCompilation(sourceB, references: new[] { refA }, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions("CS1701", ReportDiagnostic.Suppress), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compB.VerifyDiagnostics(); Assert.True(compB.Assembly.RuntimeSupportsCovariantReturnsOfClasses); actualMembers = compB.GetMember<NamedTypeSymbol>("D").GetMembers().ToTestDisplayStrings(); expectedMembers = new[] { "D..ctor(System.Int32 I)", "System.Type D.EqualityContract.get", "System.Type D.EqualityContract { get; }", "System.String D.ToString()", "System.Boolean D." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean D.op_Inequality(D? left, D? right)", "System.Boolean D.op_Equality(D? left, D? right)", "System.Int32 D.GetHashCode()", "System.Boolean D.Equals(System.Object? obj)", "System.Boolean D.Equals(C? other)", "System.Boolean D.Equals(D? other)", "D D." + WellKnownMemberNames.CloneMethodName + "()", "D..ctor(D original)", "void D.Deconstruct(out System.Int32 I)" }; AssertEx.Equal(expectedMembers, actualMembers); } } }
1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/Shared/NamedPipeUtil.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO.Pipes; using System.Security.AccessControl; using System.Security.Principal; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// The compiler needs to take advantage of features on named pipes which require target framework /// specific APIs. This class is meant to provide a simple, universal interface on top of the /// multi-targeting code that is needed here. /// </summary> internal static class NamedPipeUtil { // Size of the buffers to use: 64K private const int PipeBufferSize = 0x10000; private static string GetPipeNameOrPath(string pipeName) { if (PlatformInformation.IsUnix) { // If we're on a Unix machine then named pipes are implemented using Unix Domain Sockets. // Most Unix systems have a maximum path length limit for Unix Domain Sockets, with // Mac having a particularly short one. Mac also has a generated temp directory that // can be quite long, leaving very little room for the actual pipe name. Fortunately, // '/tmp' is mandated by POSIX to always be a valid temp directory, so we can use that // instead. return Path.Combine("/tmp", pipeName); } else { return pipeName; } } /// <summary> /// Create a client for the current user only. /// </summary> internal static NamedPipeClientStream CreateClient(string serverName, string pipeName, PipeDirection direction, PipeOptions options) => new NamedPipeClientStream(serverName, GetPipeNameOrPath(pipeName), direction, options | CurrentUserOption); /// <summary> /// Does the client of "pipeStream" have the same identity and elevation as we do? The <see cref="CreateClient"/> and /// <see cref="CreateServer(string, PipeDirection?)" /> methods will already guarantee that the identity of the client and server are the /// same. This method is attempting to validate that the elevation level is the same between both ends of the /// named pipe (want to disallow low priv session sending compilation requests to an elevated one). /// </summary> internal static bool CheckClientElevationMatches(NamedPipeServerStream pipeStream) { if (PlatformInformation.IsWindows) { var serverIdentity = getIdentity(impersonating: false); (string name, bool admin) clientIdentity = default; pipeStream.RunAsClient(() => { clientIdentity = getIdentity(impersonating: true); }); return StringComparer.OrdinalIgnoreCase.Equals(serverIdentity.name, clientIdentity.name) && serverIdentity.admin == clientIdentity.admin; (string name, bool admin) getIdentity(bool impersonating) { var currentIdentity = WindowsIdentity.GetCurrent(impersonating); var currentPrincipal = new WindowsPrincipal(currentIdentity); var elevatedToAdmin = currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator); return (currentIdentity.Name, elevatedToAdmin); } } return true; } /// <summary> /// Create a server for the current user only /// </summary> internal static NamedPipeServerStream CreateServer(string pipeName, PipeDirection? pipeDirection = null) { var pipeOptions = PipeOptions.Asynchronous | PipeOptions.WriteThrough; return CreateServer( pipeName, pipeDirection ?? PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, pipeOptions, PipeBufferSize, PipeBufferSize); } #if NET472 const int s_currentUserOnlyValue = 0x20000000; /// <summary> /// Mono supports CurrentUserOnly even though it's not exposed on the reference assemblies for net472. This /// must be used because ACL security does not work. /// </summary> private static readonly PipeOptions CurrentUserOption = PlatformInformation.IsRunningOnMono ? (PipeOptions)s_currentUserOnlyValue : PipeOptions.None; private static NamedPipeServerStream CreateServer( string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize) => new NamedPipeServerStream( GetPipeNameOrPath(pipeName), direction, maxNumberOfServerInstances, transmissionMode, options | CurrentUserOption, inBufferSize, outBufferSize, CreatePipeSecurity(), HandleInheritability.None); /// <summary> /// Check to ensure that the named pipe server we connected to is owned by the same /// user. /// </summary> internal static bool CheckPipeConnectionOwnership(NamedPipeClientStream pipeStream) { if (PlatformInformation.IsWindows) { var currentIdentity = WindowsIdentity.GetCurrent(); var currentOwner = currentIdentity.Owner; var remotePipeSecurity = pipeStream.GetAccessControl(); var remoteOwner = remotePipeSecurity.GetOwner(typeof(SecurityIdentifier)); return currentOwner.Equals(remoteOwner); } // Client side validation isn't supported on Unix. The model relies on the server side // security here. return true; } internal static PipeSecurity? CreatePipeSecurity() { if (PlatformInformation.IsRunningOnMono) { // Pipe security and additional access rights constructor arguments // are not supported by Mono // https://github.com/dotnet/roslyn/pull/30810 // https://github.com/mono/mono/issues/11406 return null; } var security = new PipeSecurity(); SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner; // Restrict access to just this account. PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow); security.AddAccessRule(rule); security.SetOwner(identifier); return security; } #elif NETCOREAPP private const PipeOptions CurrentUserOption = PipeOptions.CurrentUserOnly; // Validation is handled by CurrentUserOnly internal static bool CheckPipeConnectionOwnership(NamedPipeClientStream pipeStream) => true; // Validation is handled by CurrentUserOnly internal static PipeSecurity? CreatePipeSecurity() => null; private static NamedPipeServerStream CreateServer( string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize) => new NamedPipeServerStream( GetPipeNameOrPath(pipeName), direction, maxNumberOfServerInstances, transmissionMode, options | CurrentUserOption, inBufferSize, outBufferSize); #else #error Unsupported configuration #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.IO.Pipes; using System.Security.AccessControl; using System.Security.Principal; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// The compiler needs to take advantage of features on named pipes which require target framework /// specific APIs. This class is meant to provide a simple, universal interface on top of the /// multi-targeting code that is needed here. /// </summary> internal static class NamedPipeUtil { // Size of the buffers to use: 64K private const int PipeBufferSize = 0x10000; private static string GetPipeNameOrPath(string pipeName) { if (PlatformInformation.IsUnix) { // If we're on a Unix machine then named pipes are implemented using Unix Domain Sockets. // Most Unix systems have a maximum path length limit for Unix Domain Sockets, with // Mac having a particularly short one. Mac also has a generated temp directory that // can be quite long, leaving very little room for the actual pipe name. Fortunately, // '/tmp' is mandated by POSIX to always be a valid temp directory, so we can use that // instead. return Path.Combine("/tmp", pipeName); } else { return pipeName; } } /// <summary> /// Create a client for the current user only. /// </summary> internal static NamedPipeClientStream CreateClient(string serverName, string pipeName, PipeDirection direction, PipeOptions options) => new NamedPipeClientStream(serverName, GetPipeNameOrPath(pipeName), direction, options | CurrentUserOption); /// <summary> /// Does the client of "pipeStream" have the same identity and elevation as we do? The <see cref="CreateClient"/> and /// <see cref="CreateServer(string, PipeDirection?)" /> methods will already guarantee that the identity of the client and server are the /// same. This method is attempting to validate that the elevation level is the same between both ends of the /// named pipe (want to disallow low priv session sending compilation requests to an elevated one). /// </summary> internal static bool CheckClientElevationMatches(NamedPipeServerStream pipeStream) { if (PlatformInformation.IsWindows) { var serverIdentity = getIdentity(impersonating: false); (string name, bool admin) clientIdentity = default; pipeStream.RunAsClient(() => { clientIdentity = getIdentity(impersonating: true); }); return StringComparer.OrdinalIgnoreCase.Equals(serverIdentity.name, clientIdentity.name) && serverIdentity.admin == clientIdentity.admin; (string name, bool admin) getIdentity(bool impersonating) { var currentIdentity = WindowsIdentity.GetCurrent(impersonating); var currentPrincipal = new WindowsPrincipal(currentIdentity); var elevatedToAdmin = currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator); return (currentIdentity.Name, elevatedToAdmin); } } return true; } /// <summary> /// Create a server for the current user only /// </summary> internal static NamedPipeServerStream CreateServer(string pipeName, PipeDirection? pipeDirection = null) { var pipeOptions = PipeOptions.Asynchronous | PipeOptions.WriteThrough; return CreateServer( pipeName, pipeDirection ?? PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, pipeOptions, PipeBufferSize, PipeBufferSize); } #if NET472 const int s_currentUserOnlyValue = 0x20000000; /// <summary> /// Mono supports CurrentUserOnly even though it's not exposed on the reference assemblies for net472. This /// must be used because ACL security does not work. /// </summary> private static readonly PipeOptions CurrentUserOption = PlatformInformation.IsRunningOnMono ? (PipeOptions)s_currentUserOnlyValue : PipeOptions.None; private static NamedPipeServerStream CreateServer( string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize) => new NamedPipeServerStream( GetPipeNameOrPath(pipeName), direction, maxNumberOfServerInstances, transmissionMode, options | CurrentUserOption, inBufferSize, outBufferSize, CreatePipeSecurity(), HandleInheritability.None); /// <summary> /// Check to ensure that the named pipe server we connected to is owned by the same /// user. /// </summary> internal static bool CheckPipeConnectionOwnership(NamedPipeClientStream pipeStream) { if (PlatformInformation.IsWindows) { var currentIdentity = WindowsIdentity.GetCurrent(); var currentOwner = currentIdentity.Owner; var remotePipeSecurity = pipeStream.GetAccessControl(); var remoteOwner = remotePipeSecurity.GetOwner(typeof(SecurityIdentifier)); return currentOwner.Equals(remoteOwner); } // Client side validation isn't supported on Unix. The model relies on the server side // security here. return true; } internal static PipeSecurity? CreatePipeSecurity() { if (PlatformInformation.IsRunningOnMono) { // Pipe security and additional access rights constructor arguments // are not supported by Mono // https://github.com/dotnet/roslyn/pull/30810 // https://github.com/mono/mono/issues/11406 return null; } var security = new PipeSecurity(); SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner; // Restrict access to just this account. PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow); security.AddAccessRule(rule); security.SetOwner(identifier); return security; } #elif NETCOREAPP private const PipeOptions CurrentUserOption = PipeOptions.CurrentUserOnly; // Validation is handled by CurrentUserOnly internal static bool CheckPipeConnectionOwnership(NamedPipeClientStream pipeStream) => true; // Validation is handled by CurrentUserOnly internal static PipeSecurity? CreatePipeSecurity() => null; private static NamedPipeServerStream CreateServer( string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize) => new NamedPipeServerStream( GetPipeNameOrPath(pipeName), direction, maxNumberOfServerInstances, transmissionMode, options | CurrentUserOption, inBufferSize, outBufferSize); #else #error Unsupported configuration #endif } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Features/Core/Portable/DocumentationComments/DocumentationCommentOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.DocumentationComments { internal static class DocumentationCommentOptions { public static readonly PerLanguageOption2<bool> AutoXmlDocCommentGeneration = new(nameof(DocumentationCommentOptions), nameof(AutoXmlDocCommentGeneration), defaultValue: true, storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.AutoComment" : "TextEditor.%LANGUAGE%.Specific.Automatic XML Doc Comment Generation")); } [ExportOptionProvider, Shared] internal sealed class DocumentationCommentOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DocumentationCommentOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(DocumentationCommentOptions.AutoXmlDocCommentGeneration); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.DocumentationComments { internal static class DocumentationCommentOptions { public static readonly PerLanguageOption2<bool> AutoXmlDocCommentGeneration = new(nameof(DocumentationCommentOptions), nameof(AutoXmlDocCommentGeneration), defaultValue: true, storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.AutoComment" : "TextEditor.%LANGUAGE%.Specific.Automatic XML Doc Comment Generation")); } [ExportOptionProvider, Shared] internal sealed class DocumentationCommentOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DocumentationCommentOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(DocumentationCommentOptions.AutoXmlDocCommentGeneration); } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/VisualStudio/Core/Impl/CodeModel/CodeModelProjectCache.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. #nullable disable using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal sealed partial class CodeModelProjectCache { private struct CacheEntry { // NOTE: The logic here is a little bit tricky. We can't just keep a WeakReference to // something like a ComHandle, since it's not something that our clients keep alive. // instead, we keep a weak reference to the inner managed object, which we know will // always be alive if the outer aggregate is alive. We can't just keep a WeakReference // to the RCW for the outer object either, since in cases where we have a DCOM or native // client, the RCW will be cleaned up, even though there is still a native reference // to the underlying native outer object. // // Instead we make use of an implementation detail of the way the CLR's COM aggregation // works. Namely, if all references to the aggregated object are released, the CLR // responds to QI's for IUnknown with a different object. So, we store the original // value, when we know that we have a client, and then we use that to compare to see // if we still have a client alive. // // NOTE: This is _NOT_ AddRef'd. We use it just to store the integer value of the // IUnknown for comparison purposes. private readonly WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> _fileCodeModelWeakComHandle; public CacheEntry(ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> handle) => _fileCodeModelWeakComHandle = new WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(handle); public EnvDTE80.FileCodeModel2 FileCodeModelRcw { get { return _fileCodeModelWeakComHandle.ComAggregateObject; } } internal bool TryGetFileCodeModelInstanceWithoutCaringWhetherRcwIsAlive(out FileCodeModel fileCodeModel) => _fileCodeModelWeakComHandle.TryGetManagedObjectWithoutCaringWhetherNativeObjectIsAlive(out fileCodeModel); public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? ComHandle { get { return _fileCodeModelWeakComHandle.ComHandle; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal sealed partial class CodeModelProjectCache { private struct CacheEntry { // NOTE: The logic here is a little bit tricky. We can't just keep a WeakReference to // something like a ComHandle, since it's not something that our clients keep alive. // instead, we keep a weak reference to the inner managed object, which we know will // always be alive if the outer aggregate is alive. We can't just keep a WeakReference // to the RCW for the outer object either, since in cases where we have a DCOM or native // client, the RCW will be cleaned up, even though there is still a native reference // to the underlying native outer object. // // Instead we make use of an implementation detail of the way the CLR's COM aggregation // works. Namely, if all references to the aggregated object are released, the CLR // responds to QI's for IUnknown with a different object. So, we store the original // value, when we know that we have a client, and then we use that to compare to see // if we still have a client alive. // // NOTE: This is _NOT_ AddRef'd. We use it just to store the integer value of the // IUnknown for comparison purposes. private readonly WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> _fileCodeModelWeakComHandle; public CacheEntry(ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> handle) => _fileCodeModelWeakComHandle = new WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(handle); public EnvDTE80.FileCodeModel2 FileCodeModelRcw { get { return _fileCodeModelWeakComHandle.ComAggregateObject; } } internal bool TryGetFileCodeModelInstanceWithoutCaringWhetherRcwIsAlive(out FileCodeModel fileCodeModel) => _fileCodeModelWeakComHandle.TryGetManagedObjectWithoutCaringWhetherNativeObjectIsAlive(out fileCodeModel); public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? ComHandle { get { return _fileCodeModelWeakComHandle.ComHandle; } } } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/InvalidIdentifierStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.Editor.UnitTests.Structure; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource { /// <summary> /// Identifiers coming from IL can be just about any valid string and since C# doesn't have a way to escape all possible /// IL identifiers, we have to account for the possibility that an item's metadata name could lead to unparseable code. /// </summary> public class InvalidIdentifierStructureTests : AbstractSyntaxStructureProviderTests { protected override string LanguageName => LanguageNames.CSharp; protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource; internal override async Task<ImmutableArray<BlockSpan>> GetBlockSpansWorkerAsync(Document document, int position) { var outliningService = document.GetLanguageService<BlockStructureService>(); return (await outliningService.GetBlockStructureAsync(document, CancellationToken.None)).Spans; } [WorkItem(1174405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174405")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task PrependedDollarSign() { const string code = @" {|hint:$$class C{|textspan: { public void $Invoke(); }|}|}"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [WorkItem(1174405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174405")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task SymbolsAndPunctuation() { const string code = @" {|hint:$$class C{|textspan: { public void !#$%^&*(()_-+=|\}]{[""':;?/>.<,~`(); }|}|}"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [WorkItem(1174405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174405")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task IdentifierThatLooksLikeCode() { const string code = @" {|hint1:$$class C{|textspan1: { public void }|}|} } {|hint2:public class CodeInjection{|textspan2:{ }|}|} /* now everything is commented (); }"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.Editor.UnitTests.Structure; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource { /// <summary> /// Identifiers coming from IL can be just about any valid string and since C# doesn't have a way to escape all possible /// IL identifiers, we have to account for the possibility that an item's metadata name could lead to unparseable code. /// </summary> public class InvalidIdentifierStructureTests : AbstractSyntaxStructureProviderTests { protected override string LanguageName => LanguageNames.CSharp; protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource; internal override async Task<ImmutableArray<BlockSpan>> GetBlockSpansWorkerAsync(Document document, int position) { var outliningService = document.GetLanguageService<BlockStructureService>(); return (await outliningService.GetBlockStructureAsync(document, CancellationToken.None)).Spans; } [WorkItem(1174405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174405")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task PrependedDollarSign() { const string code = @" {|hint:$$class C{|textspan: { public void $Invoke(); }|}|}"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [WorkItem(1174405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174405")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task SymbolsAndPunctuation() { const string code = @" {|hint:$$class C{|textspan: { public void !#$%^&*(()_-+=|\}]{[""':;?/>.<,~`(); }|}|}"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [WorkItem(1174405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174405")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task IdentifierThatLooksLikeCode() { const string code = @" {|hint1:$$class C{|textspan1: { public void }|}|} } {|hint2:public class CodeInjection{|textspan2:{ }|}|} /* now everything is commented (); }"; await VerifyBlockSpansAsync(code, Region("textspan1", "hint1", CSharpStructureHelpers.Ellipsis, autoCollapse: false), Region("textspan2", "hint2", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Features/Core/Portable/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersCodeRefactoringProvider.ConstructorCandidate.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.AddConstructorParametersFromMembers { internal partial class AddConstructorParametersFromMembersCodeRefactoringProvider { private readonly struct ConstructorCandidate { public readonly IMethodSymbol Constructor; public readonly ImmutableArray<ISymbol> MissingMembers; public readonly ImmutableArray<IParameterSymbol> MissingParameters; public ConstructorCandidate(IMethodSymbol constructor, ImmutableArray<ISymbol> missingMembers, ImmutableArray<IParameterSymbol> missingParameters) { Constructor = constructor; MissingMembers = missingMembers; MissingParameters = missingParameters; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.AddConstructorParametersFromMembers { internal partial class AddConstructorParametersFromMembersCodeRefactoringProvider { private readonly struct ConstructorCandidate { public readonly IMethodSymbol Constructor; public readonly ImmutableArray<ISymbol> MissingMembers; public readonly ImmutableArray<IParameterSymbol> MissingParameters; public ConstructorCandidate(IMethodSymbol constructor, ImmutableArray<ISymbol> missingMembers, ImmutableArray<IParameterSymbol> missingParameters) { Constructor = constructor; MissingMembers = missingMembers; MissingParameters = missingParameters; } } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/VisualStudio/Core/Def/Implementation/Venus/ContainedLanguage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { internal partial class ContainedLanguage { private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; private readonly IDiagnosticAnalyzerService _diagnosticAnalyzerService; private readonly Guid _languageServiceGuid; protected readonly Workspace Workspace; protected readonly IComponentModel ComponentModel; public VisualStudioProject? Project { get; } protected readonly ContainedDocument ContainedDocument; public IVsTextBufferCoordinator BufferCoordinator { get; protected set; } /// <summary> /// The subject (secondary) buffer that contains the C# or VB code. /// </summary> public ITextBuffer SubjectBuffer { get; } /// <summary> /// The underlying buffer that contains C# or VB code. NOTE: This is NOT the "document" buffer /// that is saved to disk. Instead it is the view that the user sees. The normal buffer graph /// in Venus includes 4 buffers: /// <code> /// SurfaceBuffer/Databuffer (projection) /// / | /// Subject Buffer (C#/VB projection) | /// | | /// Inert (generated) C#/VB Buffer Document (aspx) buffer /// </code> /// In normal circumstance, the Subject and Inert C# buffer are identical in content, and the /// Surface and Document are also identical. The Subject Buffer is the one that is part of the /// workspace, that most language operations deal with. The surface buffer is the one that the /// view is created over, and the Document buffer is the one that is saved to disk. /// </summary> public ITextBuffer DataBuffer { get; } // Set when a TextViewFIlter is set. We hold onto this to keep our TagSource objects alive even if Venus // disconnects the subject buffer from the view temporarily (which they do frequently). Otherwise, we have to // re-compute all of the tag data when they re-connect it, and this causes issues like classification // flickering. private readonly ITagAggregator<ITag> _bufferTagAggregator; [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal ContainedLanguage( IVsTextBufferCoordinator bufferCoordinator, IComponentModel componentModel, VisualStudioProject? project, IVsHierarchy hierarchy, uint itemid, VisualStudioProjectTracker? projectTrackerOpt, ProjectId projectId, Guid languageServiceGuid, AbstractFormattingRule? vbHelperFormattingRule = null) : this(bufferCoordinator, componentModel, projectTrackerOpt?.Workspace ?? componentModel.GetService<VisualStudioWorkspace>(), projectId, project, GetFilePathFromHierarchyAndItemId(hierarchy, itemid), languageServiceGuid, vbHelperFormattingRule) { } public static string GetFilePathFromHierarchyAndItemId(IVsHierarchy hierarchy, uint itemid) { if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemid, out var filePath))) { // we couldn't look up the document moniker from an hierarchy for an itemid. // Since we only use this moniker as a key, we could fall back to something else, like the document name. Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy."); if (!hierarchy.TryGetItemName(itemid, out filePath!)) { FatalError.ReportAndPropagate(new InvalidOperationException("Failed to get document moniker for a contained document")); } } return filePath; } internal ContainedLanguage( IVsTextBufferCoordinator bufferCoordinator, IComponentModel componentModel, Workspace workspace, ProjectId projectId, VisualStudioProject? project, string filePath, Guid languageServiceGuid, AbstractFormattingRule? vbHelperFormattingRule = null) { this.BufferCoordinator = bufferCoordinator; this.ComponentModel = componentModel; this.Project = project; _languageServiceGuid = languageServiceGuid; this.Workspace = workspace; _editorAdaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>(); _diagnosticAnalyzerService = componentModel.GetService<IDiagnosticAnalyzerService>(); // Get the ITextBuffer for the secondary buffer Marshal.ThrowExceptionForHR(bufferCoordinator.GetSecondaryBuffer(out var secondaryTextLines)); SubjectBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(secondaryTextLines)!; // Get the ITextBuffer for the primary buffer Marshal.ThrowExceptionForHR(bufferCoordinator.GetPrimaryBuffer(out var primaryTextLines)); DataBuffer = _editorAdaptersFactoryService.GetDataBuffer(primaryTextLines)!; // Create our tagger var bufferTagAggregatorFactory = ComponentModel.GetService<IBufferTagAggregatorFactoryService>(); _bufferTagAggregator = bufferTagAggregatorFactory.CreateTagAggregator<ITag>(SubjectBuffer); DocumentId documentId; if (this.Project != null) { documentId = this.Project.AddSourceTextContainer( SubjectBuffer.AsTextContainer(), filePath, sourceCodeKind: SourceCodeKind.Regular, folders: default, designTimeOnly: true, documentServiceProvider: new ContainedDocument.DocumentServiceProvider(DataBuffer)); } else { documentId = DocumentId.CreateNewId(projectId, $"{nameof(ContainedDocument)}: {filePath}"); // We must jam a document into an existing workspace, which we'll assume is safe to do with OnDocumentAdded Workspace.OnDocumentAdded(DocumentInfo.Create(documentId, filePath, filePath: filePath)); Workspace.OnDocumentOpened(documentId, SubjectBuffer.AsTextContainer()); } this.ContainedDocument = new ContainedDocument( componentModel.GetService<IThreadingContext>(), documentId, subjectBuffer: SubjectBuffer, dataBuffer: DataBuffer, bufferCoordinator, this.Workspace, project, componentModel, vbHelperFormattingRule); // TODO: Can contained documents be linked or shared? this.DataBuffer.Changed += OnDataBufferChanged; } private void OnDisconnect() { this.DataBuffer.Changed -= OnDataBufferChanged; if (this.Project != null) { this.Project.RemoveSourceTextContainer(SubjectBuffer.AsTextContainer()); } else { // It's possible the host of the workspace might have already removed the entire project if (Workspace.CurrentSolution.ContainsDocument(ContainedDocument.Id)) { Workspace.OnDocumentRemoved(ContainedDocument.Id); } } this.ContainedDocument.Dispose(); if (_bufferTagAggregator != null) { _bufferTagAggregator.Dispose(); } } private void OnDataBufferChanged(object sender, TextContentChangedEventArgs e) { // we don't actually care what has changed in primary buffer. we just want to re-analyze secondary buffer // when primary buffer has changed to update diagnostic positions. _diagnosticAnalyzerService.Reanalyze(this.Workspace, documentIds: SpecializedCollections.SingletonEnumerable(this.ContainedDocument.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.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { internal partial class ContainedLanguage { private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; private readonly IDiagnosticAnalyzerService _diagnosticAnalyzerService; private readonly Guid _languageServiceGuid; protected readonly Workspace Workspace; protected readonly IComponentModel ComponentModel; public VisualStudioProject? Project { get; } protected readonly ContainedDocument ContainedDocument; public IVsTextBufferCoordinator BufferCoordinator { get; protected set; } /// <summary> /// The subject (secondary) buffer that contains the C# or VB code. /// </summary> public ITextBuffer SubjectBuffer { get; } /// <summary> /// The underlying buffer that contains C# or VB code. NOTE: This is NOT the "document" buffer /// that is saved to disk. Instead it is the view that the user sees. The normal buffer graph /// in Venus includes 4 buffers: /// <code> /// SurfaceBuffer/Databuffer (projection) /// / | /// Subject Buffer (C#/VB projection) | /// | | /// Inert (generated) C#/VB Buffer Document (aspx) buffer /// </code> /// In normal circumstance, the Subject and Inert C# buffer are identical in content, and the /// Surface and Document are also identical. The Subject Buffer is the one that is part of the /// workspace, that most language operations deal with. The surface buffer is the one that the /// view is created over, and the Document buffer is the one that is saved to disk. /// </summary> public ITextBuffer DataBuffer { get; } // Set when a TextViewFIlter is set. We hold onto this to keep our TagSource objects alive even if Venus // disconnects the subject buffer from the view temporarily (which they do frequently). Otherwise, we have to // re-compute all of the tag data when they re-connect it, and this causes issues like classification // flickering. private readonly ITagAggregator<ITag> _bufferTagAggregator; [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal ContainedLanguage( IVsTextBufferCoordinator bufferCoordinator, IComponentModel componentModel, VisualStudioProject? project, IVsHierarchy hierarchy, uint itemid, VisualStudioProjectTracker? projectTrackerOpt, ProjectId projectId, Guid languageServiceGuid, AbstractFormattingRule? vbHelperFormattingRule = null) : this(bufferCoordinator, componentModel, projectTrackerOpt?.Workspace ?? componentModel.GetService<VisualStudioWorkspace>(), projectId, project, GetFilePathFromHierarchyAndItemId(hierarchy, itemid), languageServiceGuid, vbHelperFormattingRule) { } public static string GetFilePathFromHierarchyAndItemId(IVsHierarchy hierarchy, uint itemid) { if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemid, out var filePath))) { // we couldn't look up the document moniker from an hierarchy for an itemid. // Since we only use this moniker as a key, we could fall back to something else, like the document name. Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy."); if (!hierarchy.TryGetItemName(itemid, out filePath!)) { FatalError.ReportAndPropagate(new InvalidOperationException("Failed to get document moniker for a contained document")); } } return filePath; } internal ContainedLanguage( IVsTextBufferCoordinator bufferCoordinator, IComponentModel componentModel, Workspace workspace, ProjectId projectId, VisualStudioProject? project, string filePath, Guid languageServiceGuid, AbstractFormattingRule? vbHelperFormattingRule = null) { this.BufferCoordinator = bufferCoordinator; this.ComponentModel = componentModel; this.Project = project; _languageServiceGuid = languageServiceGuid; this.Workspace = workspace; _editorAdaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>(); _diagnosticAnalyzerService = componentModel.GetService<IDiagnosticAnalyzerService>(); // Get the ITextBuffer for the secondary buffer Marshal.ThrowExceptionForHR(bufferCoordinator.GetSecondaryBuffer(out var secondaryTextLines)); SubjectBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(secondaryTextLines)!; // Get the ITextBuffer for the primary buffer Marshal.ThrowExceptionForHR(bufferCoordinator.GetPrimaryBuffer(out var primaryTextLines)); DataBuffer = _editorAdaptersFactoryService.GetDataBuffer(primaryTextLines)!; // Create our tagger var bufferTagAggregatorFactory = ComponentModel.GetService<IBufferTagAggregatorFactoryService>(); _bufferTagAggregator = bufferTagAggregatorFactory.CreateTagAggregator<ITag>(SubjectBuffer); DocumentId documentId; if (this.Project != null) { documentId = this.Project.AddSourceTextContainer( SubjectBuffer.AsTextContainer(), filePath, sourceCodeKind: SourceCodeKind.Regular, folders: default, designTimeOnly: true, documentServiceProvider: new ContainedDocument.DocumentServiceProvider(DataBuffer)); } else { documentId = DocumentId.CreateNewId(projectId, $"{nameof(ContainedDocument)}: {filePath}"); // We must jam a document into an existing workspace, which we'll assume is safe to do with OnDocumentAdded Workspace.OnDocumentAdded(DocumentInfo.Create(documentId, filePath, filePath: filePath)); Workspace.OnDocumentOpened(documentId, SubjectBuffer.AsTextContainer()); } this.ContainedDocument = new ContainedDocument( componentModel.GetService<IThreadingContext>(), documentId, subjectBuffer: SubjectBuffer, dataBuffer: DataBuffer, bufferCoordinator, this.Workspace, project, componentModel, vbHelperFormattingRule); // TODO: Can contained documents be linked or shared? this.DataBuffer.Changed += OnDataBufferChanged; } private void OnDisconnect() { this.DataBuffer.Changed -= OnDataBufferChanged; if (this.Project != null) { this.Project.RemoveSourceTextContainer(SubjectBuffer.AsTextContainer()); } else { // It's possible the host of the workspace might have already removed the entire project if (Workspace.CurrentSolution.ContainsDocument(ContainedDocument.Id)) { Workspace.OnDocumentRemoved(ContainedDocument.Id); } } this.ContainedDocument.Dispose(); if (_bufferTagAggregator != null) { _bufferTagAggregator.Dispose(); } } private void OnDataBufferChanged(object sender, TextContentChangedEventArgs e) { // we don't actually care what has changed in primary buffer. we just want to re-analyze secondary buffer // when primary buffer has changed to update diagnostic positions. _diagnosticAnalyzerService.Reanalyze(this.Workspace, documentIds: SpecializedCollections.SingletonEnumerable(this.ContainedDocument.Id)); } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/Core/Portable/PEWriter/Miscellaneous.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Roslyn.Utilities; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { /// <summary> /// A container for static helper methods that are used for manipulating and computing iterators. /// </summary> internal static class IteratorHelper { /// <summary> /// True if the given enumerable is not null and contains at least one element. /// </summary> public static bool EnumerableIsNotEmpty<T>([NotNullWhen(returnValue: true)] IEnumerable<T>? enumerable) { if (enumerable == null) { return false; } var asIListT = enumerable as IList<T>; if (asIListT != null) { return asIListT.Count != 0; } var asIList = enumerable as IList; if (asIList != null) { return asIList.Count != 0; } return enumerable.GetEnumerator().MoveNext(); } /// <summary> /// True if the given enumerable is null or contains no elements /// </summary> public static bool EnumerableIsEmpty<T>([NotNullWhen(returnValue: false)] IEnumerable<T>? enumerable) { return !EnumerableIsNotEmpty<T>(enumerable); } /// <summary> /// Returns the number of elements in the given enumerable. A null enumerable is allowed and results in 0. /// </summary> public static uint EnumerableCount<T>(IEnumerable<T>? enumerable) { // ^ ensures result >= 0; if (enumerable == null) { return 0; } var asIListT = enumerable as IList<T>; if (asIListT != null) { return (uint)asIListT.Count; } var asIList = enumerable as IList; if (asIList != null) { return (uint)asIList.Count; } uint result = 0; IEnumerator<T> enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) { result++; } return result & 0x7FFFFFFF; } } /// <summary> /// A declarative specification of a security action applied to a set of permissions. Used by the CLR loader to enforce security restrictions. /// Each security attribute represents a serialized permission or permission set for a specified security action. /// The union of the security attributes with identical security action, define the permission set to which the security action applies. /// </summary> internal struct SecurityAttribute { public DeclarativeSecurityAction Action { get; } public ICustomAttribute Attribute { get; } public SecurityAttribute(DeclarativeSecurityAction action, ICustomAttribute attribute) { Action = action; Attribute = attribute; } } /// <summary> /// Information about how values of managed types should be marshalled to and from unmanaged types. /// </summary> internal interface IMarshallingInformation { /// <summary> /// <see cref="ITypeReference"/> or a string (usually a fully-qualified type name of a type implementing the custom marshaller, but Dev11 allows any string). /// </summary> object GetCustomMarshaller(EmitContext context); /// <summary> /// An argument string (cookie) passed to the custom marshaller at run time. /// </summary> string CustomMarshallerRuntimeArgument { get; } /// <summary> /// The unmanaged element type of the unmanaged array. /// -1 if it should be omitted from the marshal blob. /// </summary> System.Runtime.InteropServices.UnmanagedType ElementType { get; } /// <summary> /// Specifies the index of the parameter that contains the value of the Interface Identifier (IID) of the marshalled object. /// -1 if it should be omitted from the marshal blob. /// </summary> int IidParameterIndex { get; } /// <summary> /// The unmanaged type to which the managed type will be marshalled. This can be UnmanagedType.CustomMarshaler, in which case the unmanaged type /// is decided at runtime. /// </summary> System.Runtime.InteropServices.UnmanagedType UnmanagedType { get; } /// <summary> /// The number of elements in the fixed size portion of the unmanaged array. /// -1 if it should be omitted from the marshal blob. /// </summary> int NumberOfElements { get; } /// <summary> /// The zero based index of the parameter in the unmanaged method that contains the number of elements in the variable portion of unmanaged array. /// If -1, the variable portion is of size zero, or the caller conveys the size of the variable portion of the array to the unmanaged method in some other way. /// </summary> short ParamIndex { get; } /// <summary> /// The type to which the variant values of all elements of the safe array must belong. See also SafeArrayElementUserDefinedSubtype. /// (The element type of a safe array is VARIANT. The "sub type" specifies the value of all of the tag fields (vt) of the element values. ) /// -1 if it should be omitted from the marshal blob. /// </summary> VarEnum SafeArrayElementSubtype { get; } /// <summary> /// A reference to the user defined type to which the variant values of all elements of the safe array must belong. /// (The element type of a safe array is VARIANT. The tag fields will all be either VT_DISPATCH or VT_UNKNOWN or VT_RECORD. /// The "user defined sub type" specifies the type of value the ppdispVal/ppunkVal/pvRecord fields of the element values may point to.) /// </summary> ITypeReference GetSafeArrayElementUserDefinedSubtype(EmitContext context); } /// <summary> /// Implemented by any entity that has a name. /// </summary> internal interface INamedEntity { /// <summary> /// The name of the entity. /// </summary> string? Name { get; } } /// <summary> /// The name of the entity depends on other metadata (tokens, signatures) originated from /// PeWriter. /// </summary> internal interface IContextualNamedEntity : INamedEntity { /// <summary> /// Method must be called before calling INamedEntity.Name. /// </summary> void AssociateWithMetadataWriter(MetadataWriter metadataWriter); } /// <summary> /// Implemented by an entity that is always a member of a particular parameter list, such as an IParameterDefinition. /// Provides a way to determine the position where the entity appears in the parameter list. /// </summary> internal interface IParameterListEntry { /// <summary> /// The position in the parameter list where this instance can be found. /// </summary> ushort Index { get; } } /// <summary> /// Information that describes how a method from the underlying Platform is to be invoked. /// </summary> internal interface IPlatformInvokeInformation { /// <summary> /// Module providing the method/field. /// </summary> string? ModuleName { get; } /// <summary> /// Name of the method providing the implementation. /// </summary> string? EntryPointName { get; } /// <summary> /// Flags that determine marshalling behavior. /// </summary> MethodImportAttributes Flags { get; } } internal class ResourceSection { internal ResourceSection(byte[] sectionBytes, uint[] relocations) { RoslynDebug.Assert(sectionBytes != null); RoslynDebug.Assert(relocations != null); SectionBytes = sectionBytes; Relocations = relocations; } internal readonly byte[] SectionBytes; //This is the offset into SectionBytes that should be modified. //It should have the section's RVA added to it. internal readonly uint[] Relocations; } /// <summary> /// A resource file formatted according to Win32 API conventions and typically obtained from a Portable Executable (PE) file. /// See the Win32 UpdateResource method for more details. /// </summary> internal interface IWin32Resource { /// <summary> /// A string that identifies what type of resource this is. Only valid if this.TypeId &lt; 0. /// </summary> string TypeName { get; // ^ requires this.TypeId < 0; } /// <summary> /// An integer tag that identifies what type of resource this is. If the value is less than 0, this.TypeName should be used instead. /// </summary> int TypeId { get; } /// <summary> /// The name of the resource. Only valid if this.Id &lt; 0. /// </summary> string Name { get; // ^ requires this.Id < 0; } /// <summary> /// An integer tag that identifies this resource. If the value is less than 0, this.Name should be used instead. /// </summary> int Id { get; } /// <summary> /// The language for which this resource is appropriate. /// </summary> uint LanguageId { get; } /// <summary> /// The code page for which this resource is appropriate. /// </summary> uint CodePage { get; } /// <summary> /// The data of the resource. /// </summary> IEnumerable<byte> Data { 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; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Roslyn.Utilities; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { /// <summary> /// A container for static helper methods that are used for manipulating and computing iterators. /// </summary> internal static class IteratorHelper { /// <summary> /// True if the given enumerable is not null and contains at least one element. /// </summary> public static bool EnumerableIsNotEmpty<T>([NotNullWhen(returnValue: true)] IEnumerable<T>? enumerable) { if (enumerable == null) { return false; } var asIListT = enumerable as IList<T>; if (asIListT != null) { return asIListT.Count != 0; } var asIList = enumerable as IList; if (asIList != null) { return asIList.Count != 0; } return enumerable.GetEnumerator().MoveNext(); } /// <summary> /// True if the given enumerable is null or contains no elements /// </summary> public static bool EnumerableIsEmpty<T>([NotNullWhen(returnValue: false)] IEnumerable<T>? enumerable) { return !EnumerableIsNotEmpty<T>(enumerable); } /// <summary> /// Returns the number of elements in the given enumerable. A null enumerable is allowed and results in 0. /// </summary> public static uint EnumerableCount<T>(IEnumerable<T>? enumerable) { // ^ ensures result >= 0; if (enumerable == null) { return 0; } var asIListT = enumerable as IList<T>; if (asIListT != null) { return (uint)asIListT.Count; } var asIList = enumerable as IList; if (asIList != null) { return (uint)asIList.Count; } uint result = 0; IEnumerator<T> enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) { result++; } return result & 0x7FFFFFFF; } } /// <summary> /// A declarative specification of a security action applied to a set of permissions. Used by the CLR loader to enforce security restrictions. /// Each security attribute represents a serialized permission or permission set for a specified security action. /// The union of the security attributes with identical security action, define the permission set to which the security action applies. /// </summary> internal struct SecurityAttribute { public DeclarativeSecurityAction Action { get; } public ICustomAttribute Attribute { get; } public SecurityAttribute(DeclarativeSecurityAction action, ICustomAttribute attribute) { Action = action; Attribute = attribute; } } /// <summary> /// Information about how values of managed types should be marshalled to and from unmanaged types. /// </summary> internal interface IMarshallingInformation { /// <summary> /// <see cref="ITypeReference"/> or a string (usually a fully-qualified type name of a type implementing the custom marshaller, but Dev11 allows any string). /// </summary> object GetCustomMarshaller(EmitContext context); /// <summary> /// An argument string (cookie) passed to the custom marshaller at run time. /// </summary> string CustomMarshallerRuntimeArgument { get; } /// <summary> /// The unmanaged element type of the unmanaged array. /// -1 if it should be omitted from the marshal blob. /// </summary> System.Runtime.InteropServices.UnmanagedType ElementType { get; } /// <summary> /// Specifies the index of the parameter that contains the value of the Interface Identifier (IID) of the marshalled object. /// -1 if it should be omitted from the marshal blob. /// </summary> int IidParameterIndex { get; } /// <summary> /// The unmanaged type to which the managed type will be marshalled. This can be UnmanagedType.CustomMarshaler, in which case the unmanaged type /// is decided at runtime. /// </summary> System.Runtime.InteropServices.UnmanagedType UnmanagedType { get; } /// <summary> /// The number of elements in the fixed size portion of the unmanaged array. /// -1 if it should be omitted from the marshal blob. /// </summary> int NumberOfElements { get; } /// <summary> /// The zero based index of the parameter in the unmanaged method that contains the number of elements in the variable portion of unmanaged array. /// If -1, the variable portion is of size zero, or the caller conveys the size of the variable portion of the array to the unmanaged method in some other way. /// </summary> short ParamIndex { get; } /// <summary> /// The type to which the variant values of all elements of the safe array must belong. See also SafeArrayElementUserDefinedSubtype. /// (The element type of a safe array is VARIANT. The "sub type" specifies the value of all of the tag fields (vt) of the element values. ) /// -1 if it should be omitted from the marshal blob. /// </summary> VarEnum SafeArrayElementSubtype { get; } /// <summary> /// A reference to the user defined type to which the variant values of all elements of the safe array must belong. /// (The element type of a safe array is VARIANT. The tag fields will all be either VT_DISPATCH or VT_UNKNOWN or VT_RECORD. /// The "user defined sub type" specifies the type of value the ppdispVal/ppunkVal/pvRecord fields of the element values may point to.) /// </summary> ITypeReference GetSafeArrayElementUserDefinedSubtype(EmitContext context); } /// <summary> /// Implemented by any entity that has a name. /// </summary> internal interface INamedEntity { /// <summary> /// The name of the entity. /// </summary> string? Name { get; } } /// <summary> /// The name of the entity depends on other metadata (tokens, signatures) originated from /// PeWriter. /// </summary> internal interface IContextualNamedEntity : INamedEntity { /// <summary> /// Method must be called before calling INamedEntity.Name. /// </summary> void AssociateWithMetadataWriter(MetadataWriter metadataWriter); } /// <summary> /// Implemented by an entity that is always a member of a particular parameter list, such as an IParameterDefinition. /// Provides a way to determine the position where the entity appears in the parameter list. /// </summary> internal interface IParameterListEntry { /// <summary> /// The position in the parameter list where this instance can be found. /// </summary> ushort Index { get; } } /// <summary> /// Information that describes how a method from the underlying Platform is to be invoked. /// </summary> internal interface IPlatformInvokeInformation { /// <summary> /// Module providing the method/field. /// </summary> string? ModuleName { get; } /// <summary> /// Name of the method providing the implementation. /// </summary> string? EntryPointName { get; } /// <summary> /// Flags that determine marshalling behavior. /// </summary> MethodImportAttributes Flags { get; } } internal class ResourceSection { internal ResourceSection(byte[] sectionBytes, uint[] relocations) { RoslynDebug.Assert(sectionBytes != null); RoslynDebug.Assert(relocations != null); SectionBytes = sectionBytes; Relocations = relocations; } internal readonly byte[] SectionBytes; //This is the offset into SectionBytes that should be modified. //It should have the section's RVA added to it. internal readonly uint[] Relocations; } /// <summary> /// A resource file formatted according to Win32 API conventions and typically obtained from a Portable Executable (PE) file. /// See the Win32 UpdateResource method for more details. /// </summary> internal interface IWin32Resource { /// <summary> /// A string that identifies what type of resource this is. Only valid if this.TypeId &lt; 0. /// </summary> string TypeName { get; // ^ requires this.TypeId < 0; } /// <summary> /// An integer tag that identifies what type of resource this is. If the value is less than 0, this.TypeName should be used instead. /// </summary> int TypeId { get; } /// <summary> /// The name of the resource. Only valid if this.Id &lt; 0. /// </summary> string Name { get; // ^ requires this.Id < 0; } /// <summary> /// An integer tag that identifies this resource. If the value is less than 0, this.Name should be used instead. /// </summary> int Id { get; } /// <summary> /// The language for which this resource is appropriate. /// </summary> uint LanguageId { get; } /// <summary> /// The code page for which this resource is appropriate. /// </summary> uint CodePage { get; } /// <summary> /// The data of the resource. /// </summary> IEnumerable<byte> Data { get; } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/Core/Portable/ReferenceManager/AssemblyData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis { internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol> { /// <summary> /// Information about an assembly, used as an input for the Binder class. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal abstract class AssemblyData { /// <summary> /// Identity of the assembly. /// </summary> public abstract AssemblyIdentity Identity { get; } /// <summary> /// Identity of assemblies referenced by this assembly. /// References should always be returned in the same order. /// </summary> public abstract ImmutableArray<AssemblyIdentity> AssemblyReferences { get; } /// <summary> /// The sequence of AssemblySymbols the Binder can choose from. /// </summary> public abstract IEnumerable<TAssemblySymbol> AvailableSymbols { get; } /// <summary> /// Check if provided AssemblySymbol is created for assembly described by this instance. /// This method is expected to return true for every AssemblySymbol returned by /// AvailableSymbols property. /// </summary> /// <param name="assembly"> /// The AssemblySymbol to check. /// </param> /// <returns>Boolean.</returns> public abstract bool IsMatchingAssembly(TAssemblySymbol? assembly); /// <summary> /// Resolve assembly references against assemblies described by provided AssemblyData objects. /// In other words, match assembly identities returned by AssemblyReferences property against /// assemblies described by provided AssemblyData objects. /// </summary> /// <param name="assemblies">An array of AssemblyData objects to match against.</param> /// <param name="assemblyIdentityComparer">Used to compare assembly identities.</param> /// <returns> /// For each assembly referenced by this assembly (<see cref="AssemblyReferences"/>) /// a description of how it binds to one of the input assemblies. /// </returns> public abstract AssemblyReferenceBinding[] BindAssemblyReferences(ImmutableArray<AssemblyData> assemblies, AssemblyIdentityComparer assemblyIdentityComparer); public abstract bool ContainsNoPiaLocalTypes { get; } public abstract bool IsLinked { get; } public abstract bool DeclaresTheObjectClass { get; } /// <summary> /// Get the source compilation backing this assembly, if one exists. /// Returns null otherwise. /// </summary> public abstract Compilation? SourceCompilation { get; } private string GetDebuggerDisplay() => $"{GetType().Name}: [{Identity.GetDisplayName()}]"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis { internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol> { /// <summary> /// Information about an assembly, used as an input for the Binder class. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal abstract class AssemblyData { /// <summary> /// Identity of the assembly. /// </summary> public abstract AssemblyIdentity Identity { get; } /// <summary> /// Identity of assemblies referenced by this assembly. /// References should always be returned in the same order. /// </summary> public abstract ImmutableArray<AssemblyIdentity> AssemblyReferences { get; } /// <summary> /// The sequence of AssemblySymbols the Binder can choose from. /// </summary> public abstract IEnumerable<TAssemblySymbol> AvailableSymbols { get; } /// <summary> /// Check if provided AssemblySymbol is created for assembly described by this instance. /// This method is expected to return true for every AssemblySymbol returned by /// AvailableSymbols property. /// </summary> /// <param name="assembly"> /// The AssemblySymbol to check. /// </param> /// <returns>Boolean.</returns> public abstract bool IsMatchingAssembly(TAssemblySymbol? assembly); /// <summary> /// Resolve assembly references against assemblies described by provided AssemblyData objects. /// In other words, match assembly identities returned by AssemblyReferences property against /// assemblies described by provided AssemblyData objects. /// </summary> /// <param name="assemblies">An array of AssemblyData objects to match against.</param> /// <param name="assemblyIdentityComparer">Used to compare assembly identities.</param> /// <returns> /// For each assembly referenced by this assembly (<see cref="AssemblyReferences"/>) /// a description of how it binds to one of the input assemblies. /// </returns> public abstract AssemblyReferenceBinding[] BindAssemblyReferences(ImmutableArray<AssemblyData> assemblies, AssemblyIdentityComparer assemblyIdentityComparer); public abstract bool ContainsNoPiaLocalTypes { get; } public abstract bool IsLinked { get; } public abstract bool DeclaresTheObjectClass { get; } /// <summary> /// Get the source compilation backing this assembly, if one exists. /// Returns null otherwise. /// </summary> public abstract Compilation? SourceCompilation { get; } private string GetDebuggerDisplay() => $"{GetType().Name}: [{Identity.GetDisplayName()}]"; } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/EditorFeatures/Core/Shared/Extensions/SnapshotPointExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class SnapshotPointExtensions { public static void GetLineAndCharacter(this SnapshotPoint point, out int lineNumber, out int characterIndex) => point.Snapshot.GetLineAndCharacter(point.Position, out lineNumber, out characterIndex); public static int GetContainingLineNumber(this SnapshotPoint point) => point.GetContainingLine().LineNumber; public static ITrackingPoint CreateTrackingPoint(this SnapshotPoint point, PointTrackingMode trackingMode) => point.Snapshot.CreateTrackingPoint(point, trackingMode); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class SnapshotPointExtensions { public static void GetLineAndCharacter(this SnapshotPoint point, out int lineNumber, out int characterIndex) => point.Snapshot.GetLineAndCharacter(point.Position, out lineNumber, out characterIndex); public static int GetContainingLineNumber(this SnapshotPoint point) => point.GetContainingLine().LineNumber; public static ITrackingPoint CreateTrackingPoint(this SnapshotPoint point, PointTrackingMode trackingMode) => point.Snapshot.CreateTrackingPoint(point, trackingMode); } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Features/Core/Portable/Completion/Providers/CompletionLinkedFilesSymbolEquivalenceComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractSymbolCompletionProvider<TSyntaxContext> { private sealed class CompletionLinkedFilesSymbolEquivalenceComparer : IEqualityComparer<(ISymbol symbol, bool preselect)> { public static readonly CompletionLinkedFilesSymbolEquivalenceComparer Instance = new(); public bool Equals((ISymbol symbol, bool preselect) x, (ISymbol symbol, bool preselect) y) => LinkedFilesSymbolEquivalenceComparer.Instance.Equals(x.symbol, y.symbol); public int GetHashCode((ISymbol symbol, bool preselect) obj) => LinkedFilesSymbolEquivalenceComparer.Instance.GetHashCode(obj.symbol); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractSymbolCompletionProvider<TSyntaxContext> { private sealed class CompletionLinkedFilesSymbolEquivalenceComparer : IEqualityComparer<(ISymbol symbol, bool preselect)> { public static readonly CompletionLinkedFilesSymbolEquivalenceComparer Instance = new(); public bool Equals((ISymbol symbol, bool preselect) x, (ISymbol symbol, bool preselect) y) => LinkedFilesSymbolEquivalenceComparer.Instance.Equals(x.symbol, y.symbol); public int GetHashCode((ISymbol symbol, bool preselect) obj) => LinkedFilesSymbolEquivalenceComparer.Instance.GetHashCode(obj.symbol); } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/ConversionKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp { internal enum ConversionKind : byte { UnsetConversionKind = 0, NoConversion, Identity, ImplicitNumeric, ImplicitEnumeration, ImplicitThrow, ImplicitTupleLiteral, ImplicitTuple, ExplicitTupleLiteral, ExplicitTuple, ImplicitNullable, NullLiteral, ImplicitReference, Boxing, ImplicitPointerToVoid, ImplicitNullToPointer, // Any explicit conversions involving pointers not covered by PointerToVoid or NullToPointer. // Currently, this is just implicit function pointer conversions. ImplicitPointer, ImplicitDynamic, ExplicitDynamic, ImplicitConstant, ImplicitUserDefined, AnonymousFunction, MethodGroup, ExplicitNumeric, ExplicitEnumeration, ExplicitNullable, ExplicitReference, Unboxing, ExplicitUserDefined, ExplicitPointerToPointer, ExplicitIntegerToPointer, ExplicitPointerToInteger, // The IntPtr conversions are not described by the specification but we must // implement them for compatibility with the native compiler. IntPtr, InterpolatedString, // a conversion from an interpolated string to IFormattable or FormattableString SwitchExpression, // a conversion from a switch expression to a type which each arm can convert to ConditionalExpression, // a conversion from a conditional expression to a type which each side can convert to Deconstruction, // The Deconstruction conversion is not part of the language, it is an implementation detail StackAllocToPointerType, StackAllocToSpanType, // PinnedObjectToPointer is not directly a part of the language // It is used by lowering of "fixed" statements to represent conversion of an object reference (O) to an unmanaged pointer (*) // The conversion is unsafe and makes sense only if (O) is pinned. PinnedObjectToPointer, DefaultLiteral, // a conversion from a `default` literal to any type ObjectCreation, // a conversion from a `new()` expression to any type InterpolatedStringHandler, // A conversion from an interpolated string literal to a type attributed with InterpolatedStringBuilderAttribute } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp { internal enum ConversionKind : byte { UnsetConversionKind = 0, NoConversion, Identity, ImplicitNumeric, ImplicitEnumeration, ImplicitThrow, ImplicitTupleLiteral, ImplicitTuple, ExplicitTupleLiteral, ExplicitTuple, ImplicitNullable, NullLiteral, ImplicitReference, Boxing, ImplicitPointerToVoid, ImplicitNullToPointer, // Any explicit conversions involving pointers not covered by PointerToVoid or NullToPointer. // Currently, this is just implicit function pointer conversions. ImplicitPointer, ImplicitDynamic, ExplicitDynamic, ImplicitConstant, ImplicitUserDefined, AnonymousFunction, MethodGroup, ExplicitNumeric, ExplicitEnumeration, ExplicitNullable, ExplicitReference, Unboxing, ExplicitUserDefined, ExplicitPointerToPointer, ExplicitIntegerToPointer, ExplicitPointerToInteger, // The IntPtr conversions are not described by the specification but we must // implement them for compatibility with the native compiler. IntPtr, InterpolatedString, // a conversion from an interpolated string to IFormattable or FormattableString SwitchExpression, // a conversion from a switch expression to a type which each arm can convert to ConditionalExpression, // a conversion from a conditional expression to a type which each side can convert to Deconstruction, // The Deconstruction conversion is not part of the language, it is an implementation detail StackAllocToPointerType, StackAllocToSpanType, // PinnedObjectToPointer is not directly a part of the language // It is used by lowering of "fixed" statements to represent conversion of an object reference (O) to an unmanaged pointer (*) // The conversion is unsafe and makes sense only if (O) is pinned. PinnedObjectToPointer, DefaultLiteral, // a conversion from a `default` literal to any type ObjectCreation, // a conversion from a `new()` expression to any type InterpolatedStringHandler, // A conversion from an interpolated string literal to a type attributed with InterpolatedStringBuilderAttribute } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxTriviaListTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxTriviaListTests : CSharpTestBase { [Fact] public void Equality() { var node1 = SyntaxFactory.Token(SyntaxKind.AbstractKeyword); var node2 = SyntaxFactory.Token(SyntaxKind.VirtualKeyword); EqualityTesting.AssertEqual(default(SyntaxTriviaList), default(SyntaxTriviaList)); EqualityTesting.AssertEqual(new SyntaxTriviaList(node1, node1.Node, 0, 0), new SyntaxTriviaList(node1, node1.Node, 0, 0)); EqualityTesting.AssertNotEqual(new SyntaxTriviaList(node1, node1.Node, 0, 1), new SyntaxTriviaList(node1, node1.Node, 0, 0)); EqualityTesting.AssertNotEqual(new SyntaxTriviaList(node1, node2.Node, 0, 0), new SyntaxTriviaList(node1, node1.Node, 0, 0)); EqualityTesting.AssertNotEqual(new SyntaxTriviaList(node2, node1.Node, 0, 0), new SyntaxTriviaList(node1, node1.Node, 0, 0)); // position not considered: EqualityTesting.AssertEqual(new SyntaxTriviaList(node1, node1.Node, 1, 0), new SyntaxTriviaList(node1, node1.Node, 0, 0)); } [Fact] public void Reverse_Equality() { var node1 = SyntaxFactory.Token(SyntaxKind.AbstractKeyword); var node2 = SyntaxFactory.Token(SyntaxKind.VirtualKeyword); EqualityTesting.AssertEqual(default(SyntaxTriviaList.Reversed), default(SyntaxTriviaList.Reversed)); EqualityTesting.AssertEqual(new SyntaxTriviaList(node1, node1.Node, 0, 0).Reverse(), new SyntaxTriviaList(node1, node1.Node, 0, 0).Reverse()); EqualityTesting.AssertNotEqual(new SyntaxTriviaList(node1, node1.Node, 0, 1).Reverse(), new SyntaxTriviaList(node1, node1.Node, 0, 0).Reverse()); EqualityTesting.AssertNotEqual(new SyntaxTriviaList(node1, node2.Node, 0, 0).Reverse(), new SyntaxTriviaList(node1, node1.Node, 0, 0).Reverse()); EqualityTesting.AssertNotEqual(new SyntaxTriviaList(node2, node1.Node, 0, 0).Reverse(), new SyntaxTriviaList(node1, node1.Node, 0, 0).Reverse()); // position not considered: EqualityTesting.AssertEqual(new SyntaxTriviaList(node1, node1.Node, 1, 0).Reverse(), new SyntaxTriviaList(node1, node1.Node, 0, 0).Reverse()); } [Fact] public void TestAddInsertRemoveReplace() { var list = SyntaxFactory.ParseLeadingTrivia("/*A*//*B*//*C*/"); Assert.Equal(3, list.Count); Assert.Equal("/*A*/", list[0].ToString()); Assert.Equal("/*B*/", list[1].ToString()); Assert.Equal("/*C*/", list[2].ToString()); Assert.Equal("/*A*//*B*//*C*/", list.ToFullString()); var elementA = list[0]; var elementB = list[1]; var elementC = list[2]; Assert.Equal(0, list.IndexOf(elementA)); Assert.Equal(1, list.IndexOf(elementB)); Assert.Equal(2, list.IndexOf(elementC)); var triviaD = SyntaxFactory.ParseLeadingTrivia("/*D*/")[0]; var triviaE = SyntaxFactory.ParseLeadingTrivia("/*E*/")[0]; var newList = list.Add(triviaD); Assert.Equal(4, newList.Count); Assert.Equal("/*A*//*B*//*C*//*D*/", newList.ToFullString()); newList = list.AddRange(new[] { triviaD, triviaE }); Assert.Equal(5, newList.Count); Assert.Equal("/*A*//*B*//*C*//*D*//*E*/", newList.ToFullString()); newList = list.Insert(0, triviaD); Assert.Equal(4, newList.Count); Assert.Equal("/*D*//*A*//*B*//*C*/", newList.ToFullString()); newList = list.Insert(1, triviaD); Assert.Equal(4, newList.Count); Assert.Equal("/*A*//*D*//*B*//*C*/", newList.ToFullString()); newList = list.Insert(2, triviaD); Assert.Equal(4, newList.Count); Assert.Equal("/*A*//*B*//*D*//*C*/", newList.ToFullString()); newList = list.Insert(3, triviaD); Assert.Equal(4, newList.Count); Assert.Equal("/*A*//*B*//*C*//*D*/", newList.ToFullString()); newList = list.InsertRange(0, new[] { triviaD, triviaE }); Assert.Equal(5, newList.Count); Assert.Equal("/*D*//*E*//*A*//*B*//*C*/", newList.ToFullString()); newList = list.InsertRange(1, new[] { triviaD, triviaE }); Assert.Equal(5, newList.Count); Assert.Equal("/*A*//*D*//*E*//*B*//*C*/", newList.ToFullString()); newList = list.InsertRange(2, new[] { triviaD, triviaE }); Assert.Equal(5, newList.Count); Assert.Equal("/*A*//*B*//*D*//*E*//*C*/", newList.ToFullString()); newList = list.InsertRange(3, new[] { triviaD, triviaE }); Assert.Equal(5, newList.Count); Assert.Equal("/*A*//*B*//*C*//*D*//*E*/", newList.ToFullString()); newList = list.RemoveAt(0); Assert.Equal(2, newList.Count); Assert.Equal("/*B*//*C*/", newList.ToFullString()); newList = list.RemoveAt(list.Count - 1); Assert.Equal(2, newList.Count); Assert.Equal("/*A*//*B*/", newList.ToFullString()); newList = list.Remove(elementA); Assert.Equal(2, newList.Count); Assert.Equal("/*B*//*C*/", newList.ToFullString()); newList = list.Remove(elementB); Assert.Equal(2, newList.Count); Assert.Equal("/*A*//*C*/", newList.ToFullString()); newList = list.Remove(elementC); Assert.Equal(2, newList.Count); Assert.Equal("/*A*//*B*/", newList.ToFullString()); newList = list.Replace(elementA, triviaD); Assert.Equal(3, newList.Count); Assert.Equal("/*D*//*B*//*C*/", newList.ToFullString()); newList = list.Replace(elementB, triviaD); Assert.Equal(3, newList.Count); Assert.Equal("/*A*//*D*//*C*/", newList.ToFullString()); newList = list.Replace(elementC, triviaD); Assert.Equal(3, newList.Count); Assert.Equal("/*A*//*B*//*D*/", newList.ToFullString()); newList = list.ReplaceRange(elementA, new[] { triviaD, triviaE }); Assert.Equal(4, newList.Count); Assert.Equal("/*D*//*E*//*B*//*C*/", newList.ToFullString()); newList = list.ReplaceRange(elementB, new[] { triviaD, triviaE }); Assert.Equal(4, newList.Count); Assert.Equal("/*A*//*D*//*E*//*C*/", newList.ToFullString()); newList = list.ReplaceRange(elementC, new[] { triviaD, triviaE }); Assert.Equal(4, newList.Count); Assert.Equal("/*A*//*B*//*D*//*E*/", newList.ToFullString()); newList = list.ReplaceRange(elementA, new SyntaxTrivia[] { }); Assert.Equal(2, newList.Count); Assert.Equal("/*B*//*C*/", newList.ToFullString()); newList = list.ReplaceRange(elementB, new SyntaxTrivia[] { }); Assert.Equal(2, newList.Count); Assert.Equal("/*A*//*C*/", newList.ToFullString()); newList = list.ReplaceRange(elementC, new SyntaxTrivia[] { }); Assert.Equal(2, newList.Count); Assert.Equal("/*A*//*B*/", newList.ToFullString()); Assert.Equal(-1, list.IndexOf(triviaD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, triviaD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(list.Count + 1, triviaD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { triviaD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(list.Count + 1, new[] { triviaD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(list.Count)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxTrivia))); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxTrivia))); Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxTrivia>)null)); Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxTrivia>)null)); Assert.Throws<ArgumentNullException>(() => list.ReplaceRange(elementA, (IEnumerable<SyntaxTrivia>)null)); } [Fact] public void TestAddInsertRemoveReplaceOnEmptyList() { DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxFactory.ParseLeadingTrivia("/*A*/").RemoveAt(0)); DoTestAddInsertRemoveReplaceOnEmptyList(default(SyntaxTriviaList)); } private void DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxTriviaList list) { Assert.Equal(0, list.Count); var triviaD = SyntaxFactory.ParseLeadingTrivia("/*D*/")[0]; var triviaE = SyntaxFactory.ParseLeadingTrivia("/*E*/")[0]; var newList = list.Add(triviaD); Assert.Equal(1, newList.Count); Assert.Equal("/*D*/", newList.ToFullString()); newList = list.AddRange(new[] { triviaD, triviaE }); Assert.Equal(2, newList.Count); Assert.Equal("/*D*//*E*/", newList.ToFullString()); newList = list.Insert(0, triviaD); Assert.Equal(1, newList.Count); Assert.Equal("/*D*/", newList.ToFullString()); newList = list.InsertRange(0, new[] { triviaD, triviaE }); Assert.Equal(2, newList.Count); Assert.Equal("/*D*//*E*/", newList.ToFullString()); newList = list.Remove(triviaD); Assert.Equal(0, newList.Count); Assert.Equal(-1, list.IndexOf(triviaD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(0)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(1, triviaD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, triviaD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(1, new[] { triviaD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { triviaD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.Replace(triviaD, triviaE)); Assert.Throws<ArgumentOutOfRangeException>(() => list.ReplaceRange(triviaD, new[] { triviaE })); Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxTrivia))); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxTrivia))); Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxTrivia>)null)); Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxTrivia>)null)); } [Fact] public void Extensions() { var list = SyntaxFactory.ParseLeadingTrivia("/*A*//*B*//*C*/"); Assert.Equal(0, list.IndexOf(SyntaxKind.MultiLineCommentTrivia)); Assert.True(list.Any(SyntaxKind.MultiLineCommentTrivia)); Assert.Equal(-1, list.IndexOf(SyntaxKind.SingleLineCommentTrivia)); Assert.False(list.Any(SyntaxKind.SingleLineCommentTrivia)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxTriviaListTests : CSharpTestBase { [Fact] public void Equality() { var node1 = SyntaxFactory.Token(SyntaxKind.AbstractKeyword); var node2 = SyntaxFactory.Token(SyntaxKind.VirtualKeyword); EqualityTesting.AssertEqual(default(SyntaxTriviaList), default(SyntaxTriviaList)); EqualityTesting.AssertEqual(new SyntaxTriviaList(node1, node1.Node, 0, 0), new SyntaxTriviaList(node1, node1.Node, 0, 0)); EqualityTesting.AssertNotEqual(new SyntaxTriviaList(node1, node1.Node, 0, 1), new SyntaxTriviaList(node1, node1.Node, 0, 0)); EqualityTesting.AssertNotEqual(new SyntaxTriviaList(node1, node2.Node, 0, 0), new SyntaxTriviaList(node1, node1.Node, 0, 0)); EqualityTesting.AssertNotEqual(new SyntaxTriviaList(node2, node1.Node, 0, 0), new SyntaxTriviaList(node1, node1.Node, 0, 0)); // position not considered: EqualityTesting.AssertEqual(new SyntaxTriviaList(node1, node1.Node, 1, 0), new SyntaxTriviaList(node1, node1.Node, 0, 0)); } [Fact] public void Reverse_Equality() { var node1 = SyntaxFactory.Token(SyntaxKind.AbstractKeyword); var node2 = SyntaxFactory.Token(SyntaxKind.VirtualKeyword); EqualityTesting.AssertEqual(default(SyntaxTriviaList.Reversed), default(SyntaxTriviaList.Reversed)); EqualityTesting.AssertEqual(new SyntaxTriviaList(node1, node1.Node, 0, 0).Reverse(), new SyntaxTriviaList(node1, node1.Node, 0, 0).Reverse()); EqualityTesting.AssertNotEqual(new SyntaxTriviaList(node1, node1.Node, 0, 1).Reverse(), new SyntaxTriviaList(node1, node1.Node, 0, 0).Reverse()); EqualityTesting.AssertNotEqual(new SyntaxTriviaList(node1, node2.Node, 0, 0).Reverse(), new SyntaxTriviaList(node1, node1.Node, 0, 0).Reverse()); EqualityTesting.AssertNotEqual(new SyntaxTriviaList(node2, node1.Node, 0, 0).Reverse(), new SyntaxTriviaList(node1, node1.Node, 0, 0).Reverse()); // position not considered: EqualityTesting.AssertEqual(new SyntaxTriviaList(node1, node1.Node, 1, 0).Reverse(), new SyntaxTriviaList(node1, node1.Node, 0, 0).Reverse()); } [Fact] public void TestAddInsertRemoveReplace() { var list = SyntaxFactory.ParseLeadingTrivia("/*A*//*B*//*C*/"); Assert.Equal(3, list.Count); Assert.Equal("/*A*/", list[0].ToString()); Assert.Equal("/*B*/", list[1].ToString()); Assert.Equal("/*C*/", list[2].ToString()); Assert.Equal("/*A*//*B*//*C*/", list.ToFullString()); var elementA = list[0]; var elementB = list[1]; var elementC = list[2]; Assert.Equal(0, list.IndexOf(elementA)); Assert.Equal(1, list.IndexOf(elementB)); Assert.Equal(2, list.IndexOf(elementC)); var triviaD = SyntaxFactory.ParseLeadingTrivia("/*D*/")[0]; var triviaE = SyntaxFactory.ParseLeadingTrivia("/*E*/")[0]; var newList = list.Add(triviaD); Assert.Equal(4, newList.Count); Assert.Equal("/*A*//*B*//*C*//*D*/", newList.ToFullString()); newList = list.AddRange(new[] { triviaD, triviaE }); Assert.Equal(5, newList.Count); Assert.Equal("/*A*//*B*//*C*//*D*//*E*/", newList.ToFullString()); newList = list.Insert(0, triviaD); Assert.Equal(4, newList.Count); Assert.Equal("/*D*//*A*//*B*//*C*/", newList.ToFullString()); newList = list.Insert(1, triviaD); Assert.Equal(4, newList.Count); Assert.Equal("/*A*//*D*//*B*//*C*/", newList.ToFullString()); newList = list.Insert(2, triviaD); Assert.Equal(4, newList.Count); Assert.Equal("/*A*//*B*//*D*//*C*/", newList.ToFullString()); newList = list.Insert(3, triviaD); Assert.Equal(4, newList.Count); Assert.Equal("/*A*//*B*//*C*//*D*/", newList.ToFullString()); newList = list.InsertRange(0, new[] { triviaD, triviaE }); Assert.Equal(5, newList.Count); Assert.Equal("/*D*//*E*//*A*//*B*//*C*/", newList.ToFullString()); newList = list.InsertRange(1, new[] { triviaD, triviaE }); Assert.Equal(5, newList.Count); Assert.Equal("/*A*//*D*//*E*//*B*//*C*/", newList.ToFullString()); newList = list.InsertRange(2, new[] { triviaD, triviaE }); Assert.Equal(5, newList.Count); Assert.Equal("/*A*//*B*//*D*//*E*//*C*/", newList.ToFullString()); newList = list.InsertRange(3, new[] { triviaD, triviaE }); Assert.Equal(5, newList.Count); Assert.Equal("/*A*//*B*//*C*//*D*//*E*/", newList.ToFullString()); newList = list.RemoveAt(0); Assert.Equal(2, newList.Count); Assert.Equal("/*B*//*C*/", newList.ToFullString()); newList = list.RemoveAt(list.Count - 1); Assert.Equal(2, newList.Count); Assert.Equal("/*A*//*B*/", newList.ToFullString()); newList = list.Remove(elementA); Assert.Equal(2, newList.Count); Assert.Equal("/*B*//*C*/", newList.ToFullString()); newList = list.Remove(elementB); Assert.Equal(2, newList.Count); Assert.Equal("/*A*//*C*/", newList.ToFullString()); newList = list.Remove(elementC); Assert.Equal(2, newList.Count); Assert.Equal("/*A*//*B*/", newList.ToFullString()); newList = list.Replace(elementA, triviaD); Assert.Equal(3, newList.Count); Assert.Equal("/*D*//*B*//*C*/", newList.ToFullString()); newList = list.Replace(elementB, triviaD); Assert.Equal(3, newList.Count); Assert.Equal("/*A*//*D*//*C*/", newList.ToFullString()); newList = list.Replace(elementC, triviaD); Assert.Equal(3, newList.Count); Assert.Equal("/*A*//*B*//*D*/", newList.ToFullString()); newList = list.ReplaceRange(elementA, new[] { triviaD, triviaE }); Assert.Equal(4, newList.Count); Assert.Equal("/*D*//*E*//*B*//*C*/", newList.ToFullString()); newList = list.ReplaceRange(elementB, new[] { triviaD, triviaE }); Assert.Equal(4, newList.Count); Assert.Equal("/*A*//*D*//*E*//*C*/", newList.ToFullString()); newList = list.ReplaceRange(elementC, new[] { triviaD, triviaE }); Assert.Equal(4, newList.Count); Assert.Equal("/*A*//*B*//*D*//*E*/", newList.ToFullString()); newList = list.ReplaceRange(elementA, new SyntaxTrivia[] { }); Assert.Equal(2, newList.Count); Assert.Equal("/*B*//*C*/", newList.ToFullString()); newList = list.ReplaceRange(elementB, new SyntaxTrivia[] { }); Assert.Equal(2, newList.Count); Assert.Equal("/*A*//*C*/", newList.ToFullString()); newList = list.ReplaceRange(elementC, new SyntaxTrivia[] { }); Assert.Equal(2, newList.Count); Assert.Equal("/*A*//*B*/", newList.ToFullString()); Assert.Equal(-1, list.IndexOf(triviaD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, triviaD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(list.Count + 1, triviaD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { triviaD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(list.Count + 1, new[] { triviaD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(list.Count)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxTrivia))); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxTrivia))); Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxTrivia>)null)); Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxTrivia>)null)); Assert.Throws<ArgumentNullException>(() => list.ReplaceRange(elementA, (IEnumerable<SyntaxTrivia>)null)); } [Fact] public void TestAddInsertRemoveReplaceOnEmptyList() { DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxFactory.ParseLeadingTrivia("/*A*/").RemoveAt(0)); DoTestAddInsertRemoveReplaceOnEmptyList(default(SyntaxTriviaList)); } private void DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxTriviaList list) { Assert.Equal(0, list.Count); var triviaD = SyntaxFactory.ParseLeadingTrivia("/*D*/")[0]; var triviaE = SyntaxFactory.ParseLeadingTrivia("/*E*/")[0]; var newList = list.Add(triviaD); Assert.Equal(1, newList.Count); Assert.Equal("/*D*/", newList.ToFullString()); newList = list.AddRange(new[] { triviaD, triviaE }); Assert.Equal(2, newList.Count); Assert.Equal("/*D*//*E*/", newList.ToFullString()); newList = list.Insert(0, triviaD); Assert.Equal(1, newList.Count); Assert.Equal("/*D*/", newList.ToFullString()); newList = list.InsertRange(0, new[] { triviaD, triviaE }); Assert.Equal(2, newList.Count); Assert.Equal("/*D*//*E*/", newList.ToFullString()); newList = list.Remove(triviaD); Assert.Equal(0, newList.Count); Assert.Equal(-1, list.IndexOf(triviaD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(0)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(1, triviaD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, triviaD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(1, new[] { triviaD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { triviaD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.Replace(triviaD, triviaE)); Assert.Throws<ArgumentOutOfRangeException>(() => list.ReplaceRange(triviaD, new[] { triviaE })); Assert.Throws<ArgumentOutOfRangeException>(() => list.Add(default(SyntaxTrivia))); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(0, default(SyntaxTrivia))); Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxTrivia>)null)); Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxTrivia>)null)); } [Fact] public void Extensions() { var list = SyntaxFactory.ParseLeadingTrivia("/*A*//*B*//*C*/"); Assert.Equal(0, list.IndexOf(SyntaxKind.MultiLineCommentTrivia)); Assert.True(list.Any(SyntaxKind.MultiLineCommentTrivia)); Assert.Equal(-1, list.IndexOf(SyntaxKind.SingleLineCommentTrivia)); Assert.False(list.Any(SyntaxKind.SingleLineCommentTrivia)); } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/CSharp/Portable/Binder/LocalInProgressBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This binder keeps track of the local variable (if any) that is currently being evaluated /// so that it can be passed into the next call to LocalSymbol.GetConstantValue (and /// its callers). /// </summary> internal sealed class LocalInProgressBinder : Binder { private readonly LocalSymbol _inProgress; internal LocalInProgressBinder(LocalSymbol inProgress, Binder next) : base(next) { _inProgress = inProgress; } internal override LocalSymbol LocalInProgress { get { return _inProgress; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This binder keeps track of the local variable (if any) that is currently being evaluated /// so that it can be passed into the next call to LocalSymbol.GetConstantValue (and /// its callers). /// </summary> internal sealed class LocalInProgressBinder : Binder { private readonly LocalSymbol _inProgress; internal LocalInProgressBinder(LocalSymbol inProgress, Binder next) : base(next) { _inProgress = inProgress; } internal override LocalSymbol LocalInProgress { get { return _inProgress; } } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.EventSymbolKey.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class EventSymbolKey { public static void Create(IEventSymbol symbol, SymbolKeyWriter visitor) { visitor.WriteString(symbol.MetadataName); visitor.WriteSymbolKey(symbol.ContainingType); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var metadataName = reader.ReadString(); var containingTypeResolution = reader.ReadSymbolKey(out var containingTypeFailureReason); if (containingTypeFailureReason != null) { failureReason = $"({nameof(EventSymbolKey)} {nameof(containingTypeResolution)} failed -> {containingTypeFailureReason})"; return default; } using var result = GetMembersOfNamedType<IEventSymbol>(containingTypeResolution, metadataName); return CreateResolution(result, $"({nameof(EventSymbolKey)} '{metadataName}' not found)", out failureReason); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class EventSymbolKey { public static void Create(IEventSymbol symbol, SymbolKeyWriter visitor) { visitor.WriteString(symbol.MetadataName); visitor.WriteSymbolKey(symbol.ContainingType); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var metadataName = reader.ReadString(); var containingTypeResolution = reader.ReadSymbolKey(out var containingTypeFailureReason); if (containingTypeFailureReason != null) { failureReason = $"({nameof(EventSymbolKey)} {nameof(containingTypeResolution)} failed -> {containingTypeFailureReason})"; return default; } using var result = GetMembersOfNamedType<IEventSymbol>(containingTypeResolution, metadataName); return CreateResolution(result, $"({nameof(EventSymbolKey)} '{metadataName}' not found)", out failureReason); } } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/Core/Portable/Operations/OperationFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Operations { internal static class OperationFactory { public static IInvalidOperation CreateInvalidOperation(SemanticModel semanticModel, SyntaxNode syntax, ImmutableArray<IOperation> children, bool isImplicit) { return new InvalidOperation(children, semanticModel, syntax, type: null, constantValue: null, isImplicit: isImplicit); } public static readonly IConvertibleConversion IdentityConversion = new IdentityConvertibleConversion(); private class IdentityConvertibleConversion : IConvertibleConversion { public CommonConversion ToCommonConversion() => new CommonConversion(exists: true, isIdentity: true, isNumeric: false, isReference: false, methodSymbol: null, isImplicit: true, isNullable: 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.Immutable; namespace Microsoft.CodeAnalysis.Operations { internal static class OperationFactory { public static IInvalidOperation CreateInvalidOperation(SemanticModel semanticModel, SyntaxNode syntax, ImmutableArray<IOperation> children, bool isImplicit) { return new InvalidOperation(children, semanticModel, syntax, type: null, constantValue: null, isImplicit: isImplicit); } public static readonly IConvertibleConversion IdentityConversion = new IdentityConvertibleConversion(); private class IdentityConvertibleConversion : IConvertibleConversion { public CommonConversion ToCommonConversion() => new CommonConversion(exists: true, isIdentity: true, isNumeric: false, isReference: false, methodSymbol: null, isImplicit: true, isNullable: false); } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Features/Core/Portable/EditAndContinue/EditAndContinueDocumentAnalysesCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Calculates and caches results of changed documents analysis. /// The work is triggered by an incremental analyzer on idle or explicitly when "continue" operation is executed. /// Contains analyses of the latest observed document versions. /// </summary> internal sealed class EditAndContinueDocumentAnalysesCache { private readonly object _guard = new(); private readonly Dictionary<DocumentId, (AsyncLazy<DocumentAnalysisResults> results, Project baseProject, Document document, ImmutableArray<LinePositionSpan> activeStatementSpans, EditAndContinueCapabilities capabilities)> _analyses = new(); private readonly AsyncLazy<ActiveStatementsMap> _baseActiveStatements; public EditAndContinueDocumentAnalysesCache(AsyncLazy<ActiveStatementsMap> baseActiveStatements) { _baseActiveStatements = baseActiveStatements; } public async ValueTask<ImmutableArray<DocumentAnalysisResults>> GetDocumentAnalysesAsync(CommittedSolution oldSolution, IReadOnlyList<(Document? oldDocument, Document newDocument)> documents, ActiveStatementSpanProvider activeStatementSpanProvider, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { try { if (documents.IsEmpty()) { return ImmutableArray<DocumentAnalysisResults>.Empty; } var tasks = documents.Select(document => Task.Run(() => GetDocumentAnalysisAsync(oldSolution, document.oldDocument, document.newDocument, activeStatementSpanProvider, capabilities, cancellationToken).AsTask(), cancellationToken)); var allResults = await Task.WhenAll(tasks).ConfigureAwait(false); return allResults.ToImmutableArray(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Returns a document analysis or kicks off a new one if one is not available for the specified document snapshot. /// </summary> /// <param name="oldSolution">Committed solution.</param> /// <param name="newDocument">Document snapshot to analyze.</param> /// <param name="activeStatementSpanProvider">Provider of active statement spans tracked by the editor for the solution snapshot of the <paramref name="newDocument"/>.</param> public async ValueTask<DocumentAnalysisResults> GetDocumentAnalysisAsync(CommittedSolution oldSolution, Document? oldDocument, Document newDocument, ActiveStatementSpanProvider activeStatementSpanProvider, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { try { var unmappedActiveStatementSpans = await GetLatestUnmappedActiveStatementSpansAsync(oldDocument, newDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); // The base project may have been updated as documents were brought up-to-date in the committed solution. // Get the latest available snapshot of the base project from the committed solution and use it for analyses of all documents, // so that we use a single compilation for the base project (for efficiency). // Note that some other request might be updating documents in the committed solution that were not changed (not in changedOrAddedDocuments) // but are not up-to-date. These documents do not have impact on the analysis unless we read semantic information // from the project compilation. When reading such information we need to be aware of its potential incompleteness // and consult the compiler output binary (see https://github.com/dotnet/roslyn/issues/51261). var oldProject = oldDocument?.Project ?? oldSolution.GetRequiredProject(newDocument.Project.Id); AsyncLazy<DocumentAnalysisResults> lazyResults; lock (_guard) { lazyResults = GetDocumentAnalysisNoLock(oldProject, newDocument, unmappedActiveStatementSpans, capabilities); } return await lazyResults.GetValueAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Calculates unmapped active statement spans in the <paramref name="newDocument"/> from spans provided by <paramref name="newActiveStatementSpanProvider"/>. /// </summary> private async Task<ImmutableArray<LinePositionSpan>> GetLatestUnmappedActiveStatementSpansAsync(Document? oldDocument, Document newDocument, ActiveStatementSpanProvider newActiveStatementSpanProvider, CancellationToken cancellationToken) { if (oldDocument == null) { // document has been deleted or is out-of-sync return ImmutableArray<LinePositionSpan>.Empty; } if (newDocument.FilePath == null) { // document has been added, or doesn't have a file path - we do not have tracking spans for it return ImmutableArray<LinePositionSpan>.Empty; } var newTree = await newDocument.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var newLineMappings = newTree.GetLineMappings(cancellationToken); // No #line directives -- retrieve the current location of tracking spans directly for this document: if (!newLineMappings.Any()) { var newMappedDocumentSpans = await newActiveStatementSpanProvider(newDocument.Id, newDocument.FilePath, cancellationToken).ConfigureAwait(false); return newMappedDocumentSpans.SelectAsArray(s => s.LineSpan); } // The document has #line directives. In order to determine all active statement spans in the document // we need to find all documents that #line directives in this document map to. // We retrieve the tracking spans for all such documents and then map them back to this document. using var _1 = PooledDictionary<string, ImmutableArray<ActiveStatementSpan>>.GetInstance(out var mappedSpansByDocumentPath); using var _2 = ArrayBuilder<LinePositionSpan>.GetInstance(out var activeStatementSpansBuilder); var baseActiveStatements = await _baseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); foreach (var oldActiveStatement in oldActiveStatements) { var mappedFilePath = oldActiveStatement.Statement.FileSpan.Path; if (!mappedSpansByDocumentPath.TryGetValue(mappedFilePath, out var newMappedDocumentSpans)) { newMappedDocumentSpans = await newActiveStatementSpanProvider((newDocument.FilePath == mappedFilePath) ? newDocument.Id : null, mappedFilePath, cancellationToken).ConfigureAwait(false); mappedSpansByDocumentPath.Add(mappedFilePath, newMappedDocumentSpans); } // Spans not tracked in the document (e.g. the document has been closed): if (newMappedDocumentSpans.IsEmpty) { continue; } // all baseline spans are being tracked in their corresponding mapped documents (if a span is deleted it's still tracked as empty): var newMappedDocumentActiveSpan = newMappedDocumentSpans.GetStatement(oldActiveStatement.Statement.Ordinal); Debug.Assert(newMappedDocumentActiveSpan.UnmappedDocumentId == null || newMappedDocumentActiveSpan.UnmappedDocumentId == newDocument.Id); // TODO: optimize var newLineMappingContainingActiveSpan = newLineMappings.FirstOrDefault(mapping => mapping.MappedSpan.Span.Contains(newMappedDocumentActiveSpan.LineSpan)); var unmappedSpan = newLineMappingContainingActiveSpan.MappedSpan.IsValid ? newLineMappingContainingActiveSpan.Span : default; activeStatementSpansBuilder.Add(unmappedSpan); } return activeStatementSpansBuilder.ToImmutable(); } private AsyncLazy<DocumentAnalysisResults> GetDocumentAnalysisNoLock(Project baseProject, Document document, ImmutableArray<LinePositionSpan> activeStatementSpans, EditAndContinueCapabilities capabilities) { // Do not reuse an analysis of the document unless its snasphot is exactly the same as was used to calculate the results. // Note that comparing document snapshots in effect compares the entire solution snapshots (when another document is changed a new solution snapshot is created // that creates new document snapshots for all queried documents). // Also check the base project snapshot since the analysis uses semantic information from the base project as well. // // It would be possible to reuse analysis results of documents whose content does not change in between two solution snapshots. // However, we'd need rather sophisticated caching logic. The smantic analysis gathers information from other documents when // calculating results for a specific document. In some cases it's easy to record the set of documents the analysis depends on. // For example, when analyzing a partial class we can record all documents its declaration spans. However, in other cases the analysis // checks for absence of a top-level type symbol. Adding a symbol to any document thus invalidates such analysis. It'd be possible // to keep track of which type symbols an analysis is conditional upon, if it was worth the extra complexity. if (_analyses.TryGetValue(document.Id, out var analysis) && analysis.baseProject == baseProject && analysis.document == document && analysis.activeStatementSpans.SequenceEqual(activeStatementSpans) && analysis.capabilities == capabilities) { return analysis.results; } var lazyResults = new AsyncLazy<DocumentAnalysisResults>( asynchronousComputeFunction: async cancellationToken => { try { var analyzer = document.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var baseActiveStatements = await _baseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); return await analyzer.AnalyzeDocumentAsync(baseProject, baseActiveStatements, document, activeStatementSpans, capabilities, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } }, cacheResult: true); // Previous results for this document id are discarded as they are no longer relevant. // The only relevant analysis is for the latest base and document snapshots. // Note that the base snapshot may evolve if documents are dicovered that were previously // out-of-sync with the compiled outputs and are now up-to-date. _analyses[document.Id] = (lazyResults, baseProject, document, activeStatementSpans, capabilities); return lazyResults; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Calculates and caches results of changed documents analysis. /// The work is triggered by an incremental analyzer on idle or explicitly when "continue" operation is executed. /// Contains analyses of the latest observed document versions. /// </summary> internal sealed class EditAndContinueDocumentAnalysesCache { private readonly object _guard = new(); private readonly Dictionary<DocumentId, (AsyncLazy<DocumentAnalysisResults> results, Project baseProject, Document document, ImmutableArray<LinePositionSpan> activeStatementSpans, EditAndContinueCapabilities capabilities)> _analyses = new(); private readonly AsyncLazy<ActiveStatementsMap> _baseActiveStatements; public EditAndContinueDocumentAnalysesCache(AsyncLazy<ActiveStatementsMap> baseActiveStatements) { _baseActiveStatements = baseActiveStatements; } public async ValueTask<ImmutableArray<DocumentAnalysisResults>> GetDocumentAnalysesAsync(CommittedSolution oldSolution, IReadOnlyList<(Document? oldDocument, Document newDocument)> documents, ActiveStatementSpanProvider activeStatementSpanProvider, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { try { if (documents.IsEmpty()) { return ImmutableArray<DocumentAnalysisResults>.Empty; } var tasks = documents.Select(document => Task.Run(() => GetDocumentAnalysisAsync(oldSolution, document.oldDocument, document.newDocument, activeStatementSpanProvider, capabilities, cancellationToken).AsTask(), cancellationToken)); var allResults = await Task.WhenAll(tasks).ConfigureAwait(false); return allResults.ToImmutableArray(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Returns a document analysis or kicks off a new one if one is not available for the specified document snapshot. /// </summary> /// <param name="oldSolution">Committed solution.</param> /// <param name="newDocument">Document snapshot to analyze.</param> /// <param name="activeStatementSpanProvider">Provider of active statement spans tracked by the editor for the solution snapshot of the <paramref name="newDocument"/>.</param> public async ValueTask<DocumentAnalysisResults> GetDocumentAnalysisAsync(CommittedSolution oldSolution, Document? oldDocument, Document newDocument, ActiveStatementSpanProvider activeStatementSpanProvider, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { try { var unmappedActiveStatementSpans = await GetLatestUnmappedActiveStatementSpansAsync(oldDocument, newDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); // The base project may have been updated as documents were brought up-to-date in the committed solution. // Get the latest available snapshot of the base project from the committed solution and use it for analyses of all documents, // so that we use a single compilation for the base project (for efficiency). // Note that some other request might be updating documents in the committed solution that were not changed (not in changedOrAddedDocuments) // but are not up-to-date. These documents do not have impact on the analysis unless we read semantic information // from the project compilation. When reading such information we need to be aware of its potential incompleteness // and consult the compiler output binary (see https://github.com/dotnet/roslyn/issues/51261). var oldProject = oldDocument?.Project ?? oldSolution.GetRequiredProject(newDocument.Project.Id); AsyncLazy<DocumentAnalysisResults> lazyResults; lock (_guard) { lazyResults = GetDocumentAnalysisNoLock(oldProject, newDocument, unmappedActiveStatementSpans, capabilities); } return await lazyResults.GetValueAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Calculates unmapped active statement spans in the <paramref name="newDocument"/> from spans provided by <paramref name="newActiveStatementSpanProvider"/>. /// </summary> private async Task<ImmutableArray<LinePositionSpan>> GetLatestUnmappedActiveStatementSpansAsync(Document? oldDocument, Document newDocument, ActiveStatementSpanProvider newActiveStatementSpanProvider, CancellationToken cancellationToken) { if (oldDocument == null) { // document has been deleted or is out-of-sync return ImmutableArray<LinePositionSpan>.Empty; } if (newDocument.FilePath == null) { // document has been added, or doesn't have a file path - we do not have tracking spans for it return ImmutableArray<LinePositionSpan>.Empty; } var newTree = await newDocument.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var newLineMappings = newTree.GetLineMappings(cancellationToken); // No #line directives -- retrieve the current location of tracking spans directly for this document: if (!newLineMappings.Any()) { var newMappedDocumentSpans = await newActiveStatementSpanProvider(newDocument.Id, newDocument.FilePath, cancellationToken).ConfigureAwait(false); return newMappedDocumentSpans.SelectAsArray(s => s.LineSpan); } // The document has #line directives. In order to determine all active statement spans in the document // we need to find all documents that #line directives in this document map to. // We retrieve the tracking spans for all such documents and then map them back to this document. using var _1 = PooledDictionary<string, ImmutableArray<ActiveStatementSpan>>.GetInstance(out var mappedSpansByDocumentPath); using var _2 = ArrayBuilder<LinePositionSpan>.GetInstance(out var activeStatementSpansBuilder); var baseActiveStatements = await _baseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); foreach (var oldActiveStatement in oldActiveStatements) { var mappedFilePath = oldActiveStatement.Statement.FileSpan.Path; if (!mappedSpansByDocumentPath.TryGetValue(mappedFilePath, out var newMappedDocumentSpans)) { newMappedDocumentSpans = await newActiveStatementSpanProvider((newDocument.FilePath == mappedFilePath) ? newDocument.Id : null, mappedFilePath, cancellationToken).ConfigureAwait(false); mappedSpansByDocumentPath.Add(mappedFilePath, newMappedDocumentSpans); } // Spans not tracked in the document (e.g. the document has been closed): if (newMappedDocumentSpans.IsEmpty) { continue; } // all baseline spans are being tracked in their corresponding mapped documents (if a span is deleted it's still tracked as empty): var newMappedDocumentActiveSpan = newMappedDocumentSpans.GetStatement(oldActiveStatement.Statement.Ordinal); Debug.Assert(newMappedDocumentActiveSpan.UnmappedDocumentId == null || newMappedDocumentActiveSpan.UnmappedDocumentId == newDocument.Id); // TODO: optimize var newLineMappingContainingActiveSpan = newLineMappings.FirstOrDefault(mapping => mapping.MappedSpan.Span.Contains(newMappedDocumentActiveSpan.LineSpan)); var unmappedSpan = newLineMappingContainingActiveSpan.MappedSpan.IsValid ? newLineMappingContainingActiveSpan.Span : default; activeStatementSpansBuilder.Add(unmappedSpan); } return activeStatementSpansBuilder.ToImmutable(); } private AsyncLazy<DocumentAnalysisResults> GetDocumentAnalysisNoLock(Project baseProject, Document document, ImmutableArray<LinePositionSpan> activeStatementSpans, EditAndContinueCapabilities capabilities) { // Do not reuse an analysis of the document unless its snasphot is exactly the same as was used to calculate the results. // Note that comparing document snapshots in effect compares the entire solution snapshots (when another document is changed a new solution snapshot is created // that creates new document snapshots for all queried documents). // Also check the base project snapshot since the analysis uses semantic information from the base project as well. // // It would be possible to reuse analysis results of documents whose content does not change in between two solution snapshots. // However, we'd need rather sophisticated caching logic. The smantic analysis gathers information from other documents when // calculating results for a specific document. In some cases it's easy to record the set of documents the analysis depends on. // For example, when analyzing a partial class we can record all documents its declaration spans. However, in other cases the analysis // checks for absence of a top-level type symbol. Adding a symbol to any document thus invalidates such analysis. It'd be possible // to keep track of which type symbols an analysis is conditional upon, if it was worth the extra complexity. if (_analyses.TryGetValue(document.Id, out var analysis) && analysis.baseProject == baseProject && analysis.document == document && analysis.activeStatementSpans.SequenceEqual(activeStatementSpans) && analysis.capabilities == capabilities) { return analysis.results; } var lazyResults = new AsyncLazy<DocumentAnalysisResults>( asynchronousComputeFunction: async cancellationToken => { try { var analyzer = document.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var baseActiveStatements = await _baseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); return await analyzer.AnalyzeDocumentAsync(baseProject, baseActiveStatements, document, activeStatementSpans, capabilities, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } }, cacheResult: true); // Previous results for this document id are discarded as they are no longer relevant. // The only relevant analysis is for the latest base and document snapshots. // Note that the base snapshot may evolve if documents are dicovered that were previously // out-of-sync with the compiled outputs and are now up-to-date. _analyses[document.Id] = (lazyResults, baseProject, document, activeStatementSpans, capabilities); return lazyResults; } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/Core/Portable/InternalUtilities/Index.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #if !NETCOREAPP using System.Runtime.CompilerServices; namespace System { /// <summary>Represent a type can be used to index a collection either from the start or the end.</summary> /// <remarks> /// Index is used by the C# compiler to support the new index syntax /// <code> /// int[] someArray = new int[5] { 1, 2, 3, 4, 5 } ; /// int lastElement = someArray[^1]; // lastElement = 5 /// </code> /// </remarks> internal readonly struct Index : IEquatable<Index> { private readonly int _value; /// <summary>Construct an Index using a value and indicating if the index is from the start or from the end.</summary> /// <param name="value">The index value. it has to be zero or positive number.</param> /// <param name="fromEnd">Indicating if the index is from the start or from the end.</param> /// <remarks> /// If the Index constructed from the end, index value 1 means pointing at the last element and index value 0 means pointing at beyond last element. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Index(int value, bool fromEnd = false) { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), value, "Non-negative number required."); } if (fromEnd) _value = ~value; else _value = value; } // The following private constructors mainly created for perf reason to avoid the checks private Index(int value) { _value = value; } /// <summary>Create an Index pointing at first element.</summary> public static Index Start => new Index(0); /// <summary>Create an Index pointing at beyond last element.</summary> public static Index End => new Index(~0); /// <summary>Create an Index from the start at the position indicated by the value.</summary> /// <param name="value">The index value from the start.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Index FromStart(int value) { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), value, "Non-negative number required."); } return new Index(value); } /// <summary>Create an Index from the end at the position indicated by the value.</summary> /// <param name="value">The index value from the end.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Index FromEnd(int value) { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), value, "Non-negative number required."); } return new Index(~value); } /// <summary>Returns the index value.</summary> public int Value { get { if (_value < 0) return ~_value; else return _value; } } /// <summary>Indicates whether the index is from the start or the end.</summary> public bool IsFromEnd => _value < 0; /// <summary>Calculate the offset from the start using the giving collection length.</summary> /// <param name="length">The length of the collection that the Index will be used with. length has to be a positive value</param> /// <remarks> /// For performance reason, we don't validate the input length parameter and the returned offset value against negative values. /// we don't validate either the returned offset is greater than the input length. /// It is expected Index will be used with collections which always have non negative length/count. If the returned offset is negative and /// then used to index a collection will get out of range exception which will be same affect as the validation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetOffset(int length) { int offset = _value; if (IsFromEnd) { // offset = length - (~value) // offset = length + (~(~value) + 1) // offset = length + value + 1 offset += length + 1; } return offset; } /// <summary>Indicates whether the current Index object is equal to another object of the same type.</summary> /// <param name="value">An object to compare with this object</param> public override bool Equals(object? value) => value is Index && _value == ((Index)value)._value; /// <summary>Indicates whether the current Index object is equal to another Index object.</summary> /// <param name="other">An object to compare with this object</param> public bool Equals(Index other) => _value == other._value; /// <summary>Returns the hash code for this instance.</summary> public override int GetHashCode() => _value; /// <summary>Converts integer number to an Index.</summary> public static implicit operator Index(int value) => FromStart(value); /// <summary>Converts the value of the current Index object to its equivalent string representation.</summary> public override string ToString() { if (IsFromEnd) return $"^{((uint)Value).ToString()}"; return ((uint)Value).ToString(); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #if !NETCOREAPP using System.Runtime.CompilerServices; namespace System { /// <summary>Represent a type can be used to index a collection either from the start or the end.</summary> /// <remarks> /// Index is used by the C# compiler to support the new index syntax /// <code> /// int[] someArray = new int[5] { 1, 2, 3, 4, 5 } ; /// int lastElement = someArray[^1]; // lastElement = 5 /// </code> /// </remarks> internal readonly struct Index : IEquatable<Index> { private readonly int _value; /// <summary>Construct an Index using a value and indicating if the index is from the start or from the end.</summary> /// <param name="value">The index value. it has to be zero or positive number.</param> /// <param name="fromEnd">Indicating if the index is from the start or from the end.</param> /// <remarks> /// If the Index constructed from the end, index value 1 means pointing at the last element and index value 0 means pointing at beyond last element. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Index(int value, bool fromEnd = false) { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), value, "Non-negative number required."); } if (fromEnd) _value = ~value; else _value = value; } // The following private constructors mainly created for perf reason to avoid the checks private Index(int value) { _value = value; } /// <summary>Create an Index pointing at first element.</summary> public static Index Start => new Index(0); /// <summary>Create an Index pointing at beyond last element.</summary> public static Index End => new Index(~0); /// <summary>Create an Index from the start at the position indicated by the value.</summary> /// <param name="value">The index value from the start.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Index FromStart(int value) { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), value, "Non-negative number required."); } return new Index(value); } /// <summary>Create an Index from the end at the position indicated by the value.</summary> /// <param name="value">The index value from the end.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Index FromEnd(int value) { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), value, "Non-negative number required."); } return new Index(~value); } /// <summary>Returns the index value.</summary> public int Value { get { if (_value < 0) return ~_value; else return _value; } } /// <summary>Indicates whether the index is from the start or the end.</summary> public bool IsFromEnd => _value < 0; /// <summary>Calculate the offset from the start using the giving collection length.</summary> /// <param name="length">The length of the collection that the Index will be used with. length has to be a positive value</param> /// <remarks> /// For performance reason, we don't validate the input length parameter and the returned offset value against negative values. /// we don't validate either the returned offset is greater than the input length. /// It is expected Index will be used with collections which always have non negative length/count. If the returned offset is negative and /// then used to index a collection will get out of range exception which will be same affect as the validation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetOffset(int length) { int offset = _value; if (IsFromEnd) { // offset = length - (~value) // offset = length + (~(~value) + 1) // offset = length + value + 1 offset += length + 1; } return offset; } /// <summary>Indicates whether the current Index object is equal to another object of the same type.</summary> /// <param name="value">An object to compare with this object</param> public override bool Equals(object? value) => value is Index && _value == ((Index)value)._value; /// <summary>Indicates whether the current Index object is equal to another Index object.</summary> /// <param name="other">An object to compare with this object</param> public bool Equals(Index other) => _value == other._value; /// <summary>Returns the hash code for this instance.</summary> public override int GetHashCode() => _value; /// <summary>Converts integer number to an Index.</summary> public static implicit operator Index(int value) => FromStart(value); /// <summary>Converts the value of the current Index object to its equivalent string representation.</summary> public override string ToString() { if (IsFromEnd) return $"^{((uint)Value).ToString()}"; return ((uint)Value).ToString(); } } } #endif
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Features/Core/Portable/SplitOrMergeIfStatements/AbstractSplitIfStatementCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.SplitOrMergeIfStatements { internal abstract class AbstractSplitIfStatementCodeRefactoringProvider : CodeRefactoringProvider { protected abstract int GetLogicalExpressionKind(ISyntaxKindsService syntaxKinds); protected abstract CodeAction CreateCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, string ifKeywordText); protected abstract Task<SyntaxNode> GetChangedRootAsync( Document document, SyntaxNode root, SyntaxNode ifOrElseIf, SyntaxNode leftCondition, SyntaxNode rightCondition, CancellationToken cancellationToken); public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(textSpan.Start); if (textSpan.Length > 0 && textSpan != token.Span) { return; } var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var syntaxKinds = document.GetLanguageService<ISyntaxKindsService>(); var ifGenerator = document.GetLanguageService<IIfLikeStatementGenerator>(); if (IsPartOfBinaryExpressionChain(token, GetLogicalExpressionKind(syntaxKinds), out var rootExpression) && ifGenerator.IsCondition(rootExpression, out var ifOrElseIf)) { context.RegisterRefactoring( CreateCodeAction( c => RefactorAsync(document, token.Span, ifOrElseIf.Span, c), syntaxFacts.GetText(syntaxKinds.IfKeyword)), ifOrElseIf.Span); } } private async Task<Document> RefactorAsync(Document document, TextSpan tokenSpan, TextSpan ifOrElseIfSpan, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var ifGenerator = document.GetLanguageService<IIfLikeStatementGenerator>(); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(tokenSpan.Start); var ifOrElseIf = root.FindNode(ifOrElseIfSpan); Debug.Assert(ifGenerator.IsIfOrElseIf(ifOrElseIf)); var (left, right) = SplitBinaryExpressionChain(token, ifGenerator.GetCondition(ifOrElseIf), syntaxFacts); var newRoot = await GetChangedRootAsync(document, root, ifOrElseIf, left, right, cancellationToken).ConfigureAwait(false); return document.WithSyntaxRoot(newRoot); } private static bool IsPartOfBinaryExpressionChain(SyntaxToken token, int syntaxKind, out SyntaxNode rootExpression) { // Check whether the token is part of a binary expression, and if so, // return the topmost binary expression in the chain (e.g. `a && b && c`). SyntaxNodeOrToken current = token; while (current.Parent?.RawKind == syntaxKind) { current = current.Parent; } rootExpression = current.AsNode(); return current.IsNode; } private static (SyntaxNode left, SyntaxNode right) SplitBinaryExpressionChain( SyntaxToken token, SyntaxNode rootExpression, ISyntaxFactsService syntaxFacts) { // We have a left-associative binary expression chain, e.g. `a && b && c && d`. // Let's say our token is the second `&&` token, between b and c. We'd like to split the chain at this point // and build new expressions for the left side and the right side of this token. This will // effectively change the associativity from `((a && b) && c) && d` to `(a && b) && (c && d)`. // The left side is in the proper shape already and we can build the right side by getting the // topmost expression and replacing our parent with our right side. In the example: `(a && b) && c` to `c`. syntaxFacts.GetPartsOfBinaryExpression(token.Parent, out var parentLeft, out _, out var parentRight); var left = parentLeft; var right = rootExpression.ReplaceNode(token.Parent, parentRight); return (left, right); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.SplitOrMergeIfStatements { internal abstract class AbstractSplitIfStatementCodeRefactoringProvider : CodeRefactoringProvider { protected abstract int GetLogicalExpressionKind(ISyntaxKindsService syntaxKinds); protected abstract CodeAction CreateCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, string ifKeywordText); protected abstract Task<SyntaxNode> GetChangedRootAsync( Document document, SyntaxNode root, SyntaxNode ifOrElseIf, SyntaxNode leftCondition, SyntaxNode rightCondition, CancellationToken cancellationToken); public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(textSpan.Start); if (textSpan.Length > 0 && textSpan != token.Span) { return; } var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var syntaxKinds = document.GetLanguageService<ISyntaxKindsService>(); var ifGenerator = document.GetLanguageService<IIfLikeStatementGenerator>(); if (IsPartOfBinaryExpressionChain(token, GetLogicalExpressionKind(syntaxKinds), out var rootExpression) && ifGenerator.IsCondition(rootExpression, out var ifOrElseIf)) { context.RegisterRefactoring( CreateCodeAction( c => RefactorAsync(document, token.Span, ifOrElseIf.Span, c), syntaxFacts.GetText(syntaxKinds.IfKeyword)), ifOrElseIf.Span); } } private async Task<Document> RefactorAsync(Document document, TextSpan tokenSpan, TextSpan ifOrElseIfSpan, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var ifGenerator = document.GetLanguageService<IIfLikeStatementGenerator>(); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(tokenSpan.Start); var ifOrElseIf = root.FindNode(ifOrElseIfSpan); Debug.Assert(ifGenerator.IsIfOrElseIf(ifOrElseIf)); var (left, right) = SplitBinaryExpressionChain(token, ifGenerator.GetCondition(ifOrElseIf), syntaxFacts); var newRoot = await GetChangedRootAsync(document, root, ifOrElseIf, left, right, cancellationToken).ConfigureAwait(false); return document.WithSyntaxRoot(newRoot); } private static bool IsPartOfBinaryExpressionChain(SyntaxToken token, int syntaxKind, out SyntaxNode rootExpression) { // Check whether the token is part of a binary expression, and if so, // return the topmost binary expression in the chain (e.g. `a && b && c`). SyntaxNodeOrToken current = token; while (current.Parent?.RawKind == syntaxKind) { current = current.Parent; } rootExpression = current.AsNode(); return current.IsNode; } private static (SyntaxNode left, SyntaxNode right) SplitBinaryExpressionChain( SyntaxToken token, SyntaxNode rootExpression, ISyntaxFactsService syntaxFacts) { // We have a left-associative binary expression chain, e.g. `a && b && c && d`. // Let's say our token is the second `&&` token, between b and c. We'd like to split the chain at this point // and build new expressions for the left side and the right side of this token. This will // effectively change the associativity from `((a && b) && c) && d` to `(a && b) && (c && d)`. // The left side is in the proper shape already and we can build the right side by getting the // topmost expression and replacing our parent with our right side. In the example: `(a && b) && c` to `c`. syntaxFacts.GetPartsOfBinaryExpression(token.Parent, out var parentLeft, out _, out var parentRight); var left = parentLeft; var right = rootExpression.ReplaceNode(token.Parent, parentRight); return (left, right); } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseIndexOperatorDiagnosticAnalyzer.InfoCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Concurrent; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator { using static Helpers; internal partial class CSharpUseIndexOperatorDiagnosticAnalyzer { /// <summary> /// Helper type to cache information about types while analyzing the compilation. /// </summary> private class InfoCache { /// <summary> /// The <see cref="T:System.Index"/> type. Needed so that we only fixup code if we see the type /// we're using has an indexer that takes an <see cref="T:System.Index"/>. /// </summary> [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "Required to avoid ambiguous reference warnings.")] public readonly INamedTypeSymbol IndexType; /// <summary> /// Mapping from a method like <c>MyType.Get(int)</c> to the <c>Length</c>/<c>Count</c> property for /// <c>MyType</c> as well as the optional <c>MyType.Get(System.Index)</c> member if it exists. /// </summary> private readonly ConcurrentDictionary<IMethodSymbol, MemberInfo> _methodToMemberInfo = new(); public InfoCache(Compilation compilation) => IndexType = compilation.GetBestTypeByMetadataName("System.Index"); public bool TryGetMemberInfo(IMethodSymbol methodSymbol, out MemberInfo memberInfo) { memberInfo = default; if (IsIntIndexingMethod(methodSymbol)) { memberInfo = _methodToMemberInfo.GetOrAdd(methodSymbol, m => ComputeMemberInfo(m)); } return memberInfo.LengthLikeProperty != null; } private MemberInfo ComputeMemberInfo(IMethodSymbol method) { Debug.Assert(IsIntIndexingMethod(method)); // Check that the type has an int32 'Length' or 'Count' property. If not, we don't // consider it something indexable. var containingType = method.ContainingType; var lengthLikeProperty = TryGetLengthOrCountProperty(containingType); if (lengthLikeProperty == null) { return default; } if (method.MethodKind == MethodKind.PropertyGet) { // this is the getter for an indexer. i.e. the user is calling something // like s[...]. // // These can always be converted to use a System.Index. Either because the // type itself has a System.Index-based indexer, or because the language just // allows types to implicitly seem like they support this through: // // https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#implicit-index-support return new MemberInfo(lengthLikeProperty, overloadedMethodOpt: null); } else { Debug.Assert(method.MethodKind == MethodKind.Ordinary); // it's a method like: `SomeType MyType.Get(int index)`. Look // for an overload like: `SomeType MyType.Get(Range)` var overloadedIndexMethod = GetOverload(method, IndexType); if (overloadedIndexMethod != null) { return new MemberInfo(lengthLikeProperty, overloadedIndexMethod); } } // A index-like method that we can't convert. return default; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Concurrent; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator { using static Helpers; internal partial class CSharpUseIndexOperatorDiagnosticAnalyzer { /// <summary> /// Helper type to cache information about types while analyzing the compilation. /// </summary> private class InfoCache { /// <summary> /// The <see cref="T:System.Index"/> type. Needed so that we only fixup code if we see the type /// we're using has an indexer that takes an <see cref="T:System.Index"/>. /// </summary> [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "Required to avoid ambiguous reference warnings.")] public readonly INamedTypeSymbol IndexType; /// <summary> /// Mapping from a method like <c>MyType.Get(int)</c> to the <c>Length</c>/<c>Count</c> property for /// <c>MyType</c> as well as the optional <c>MyType.Get(System.Index)</c> member if it exists. /// </summary> private readonly ConcurrentDictionary<IMethodSymbol, MemberInfo> _methodToMemberInfo = new(); public InfoCache(Compilation compilation) => IndexType = compilation.GetBestTypeByMetadataName("System.Index"); public bool TryGetMemberInfo(IMethodSymbol methodSymbol, out MemberInfo memberInfo) { memberInfo = default; if (IsIntIndexingMethod(methodSymbol)) { memberInfo = _methodToMemberInfo.GetOrAdd(methodSymbol, m => ComputeMemberInfo(m)); } return memberInfo.LengthLikeProperty != null; } private MemberInfo ComputeMemberInfo(IMethodSymbol method) { Debug.Assert(IsIntIndexingMethod(method)); // Check that the type has an int32 'Length' or 'Count' property. If not, we don't // consider it something indexable. var containingType = method.ContainingType; var lengthLikeProperty = TryGetLengthOrCountProperty(containingType); if (lengthLikeProperty == null) { return default; } if (method.MethodKind == MethodKind.PropertyGet) { // this is the getter for an indexer. i.e. the user is calling something // like s[...]. // // These can always be converted to use a System.Index. Either because the // type itself has a System.Index-based indexer, or because the language just // allows types to implicitly seem like they support this through: // // https://github.com/dotnet/csharplang/blob/main/proposals/csharp-8.0/ranges.md#implicit-index-support return new MemberInfo(lengthLikeProperty, overloadedMethodOpt: null); } else { Debug.Assert(method.MethodKind == MethodKind.Ordinary); // it's a method like: `SomeType MyType.Get(int index)`. Look // for an overload like: `SomeType MyType.Get(Range)` var overloadedIndexMethod = GetOverload(method, IndexType); if (overloadedIndexMethod != null) { return new MemberInfo(lengthLikeProperty, overloadedIndexMethod); } } // A index-like method that we can't convert. return default; } } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Analyzers/Core/Analyzers/RemoveUnnecessarySuppressions/AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeQuality; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions { internal abstract class AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer : AbstractCodeQualityDiagnosticAnalyzer { internal const string DocCommentIdKey = nameof(DocCommentIdKey); private static readonly LocalizableResourceString s_localizableTitle = new( nameof(AnalyzersResources.Invalid_global_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableInvalidScopeMessage = new( nameof(AnalyzersResources.Invalid_scope_for_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableInvalidOrMissingTargetMessage = new( nameof(AnalyzersResources.Invalid_or_missing_target_for_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly DiagnosticDescriptor s_invalidScopeDescriptor = CreateDescriptor( IDEDiagnosticIds.InvalidSuppressMessageAttributeDiagnosticId, EnforceOnBuildValues.InvalidSuppressMessageAttribute, s_localizableTitle, s_localizableInvalidScopeMessage, isUnnecessary: true); private static readonly DiagnosticDescriptor s_invalidOrMissingTargetDescriptor = CreateDescriptor( IDEDiagnosticIds.InvalidSuppressMessageAttributeDiagnosticId, EnforceOnBuildValues.InvalidSuppressMessageAttribute, s_localizableTitle, s_localizableInvalidOrMissingTargetMessage, isUnnecessary: true); private static readonly LocalizableResourceString s_localizableLegacyFormatTitle = new( nameof(AnalyzersResources.Avoid_legacy_format_target_in_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableLegacyFormatMessage = new( nameof(AnalyzersResources.Avoid_legacy_format_target_0_in_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); internal static readonly DiagnosticDescriptor LegacyFormatTargetDescriptor = CreateDescriptor( IDEDiagnosticIds.LegacyFormatSuppressMessageAttributeDiagnosticId, EnforceOnBuildValues.LegacyFormatSuppressMessageAttribute, s_localizableLegacyFormatTitle, s_localizableLegacyFormatMessage, isUnnecessary: false); protected AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer() : base(ImmutableArray.Create(s_invalidScopeDescriptor, s_invalidOrMissingTargetDescriptor, LegacyFormatTargetDescriptor), GeneratedCodeAnalysisFlags.None) { } protected abstract void RegisterAttributeSyntaxAction(CompilationStartAnalysisContext context, CompilationAnalyzer compilationAnalyzer); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(context => { var suppressMessageAttributeType = context.Compilation.SuppressMessageAttributeType(); if (suppressMessageAttributeType == null) { return; } RegisterAttributeSyntaxAction(context, new CompilationAnalyzer(context.Compilation, suppressMessageAttributeType)); }); } protected sealed class CompilationAnalyzer { private readonly SuppressMessageAttributeState _state; public CompilationAnalyzer(Compilation compilation, INamedTypeSymbol suppressMessageAttributeType) { _state = new SuppressMessageAttributeState(compilation, suppressMessageAttributeType); } public void AnalyzeAssemblyOrModuleAttribute(SyntaxNode attributeSyntax, SemanticModel model, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken) { if (!_state.IsSuppressMessageAttributeWithNamedArguments(attributeSyntax, model, cancellationToken, out var namedAttributeArguments)) { return; } if (!SuppressMessageAttributeState.HasValidScope(namedAttributeArguments, out var targetScope)) { reportDiagnostic(Diagnostic.Create(s_invalidScopeDescriptor, attributeSyntax.GetLocation())); return; } if (!_state.HasValidTarget(namedAttributeArguments, targetScope, out var targetHasDocCommentIdFormat, out var targetSymbolString, out var targetValueOperation, out var resolvedSymbols)) { reportDiagnostic(Diagnostic.Create(s_invalidOrMissingTargetDescriptor, attributeSyntax.GetLocation())); return; } // We want to flag valid target which uses legacy format to update to Roslyn based DocCommentId format. if (resolvedSymbols.Length > 0 && !targetHasDocCommentIdFormat) { RoslynDebug.Assert(!string.IsNullOrEmpty(targetSymbolString)); RoslynDebug.Assert(targetValueOperation != null); var properties = ImmutableDictionary<string, string?>.Empty; if (resolvedSymbols.Length == 1) { // We provide a code fix for the case where the target resolved to a single symbol. var docCommentId = DocumentationCommentId.CreateDeclarationId(resolvedSymbols[0]); if (!string.IsNullOrEmpty(docCommentId)) { // Suppression target has an optional "~" prefix to distinguish it from legacy FxCop suppressions. // IDE suppression code fixes emit this prefix, so we we also add this prefix to new suppression target string. properties = properties.Add(DocCommentIdKey, "~" + docCommentId); } } reportDiagnostic(Diagnostic.Create(LegacyFormatTargetDescriptor, targetValueOperation.Syntax.GetLocation(), properties!, targetSymbolString)); return; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeQuality; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions { internal abstract class AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer : AbstractCodeQualityDiagnosticAnalyzer { internal const string DocCommentIdKey = nameof(DocCommentIdKey); private static readonly LocalizableResourceString s_localizableTitle = new( nameof(AnalyzersResources.Invalid_global_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableInvalidScopeMessage = new( nameof(AnalyzersResources.Invalid_scope_for_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableInvalidOrMissingTargetMessage = new( nameof(AnalyzersResources.Invalid_or_missing_target_for_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly DiagnosticDescriptor s_invalidScopeDescriptor = CreateDescriptor( IDEDiagnosticIds.InvalidSuppressMessageAttributeDiagnosticId, EnforceOnBuildValues.InvalidSuppressMessageAttribute, s_localizableTitle, s_localizableInvalidScopeMessage, isUnnecessary: true); private static readonly DiagnosticDescriptor s_invalidOrMissingTargetDescriptor = CreateDescriptor( IDEDiagnosticIds.InvalidSuppressMessageAttributeDiagnosticId, EnforceOnBuildValues.InvalidSuppressMessageAttribute, s_localizableTitle, s_localizableInvalidOrMissingTargetMessage, isUnnecessary: true); private static readonly LocalizableResourceString s_localizableLegacyFormatTitle = new( nameof(AnalyzersResources.Avoid_legacy_format_target_in_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableLegacyFormatMessage = new( nameof(AnalyzersResources.Avoid_legacy_format_target_0_in_SuppressMessageAttribute), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); internal static readonly DiagnosticDescriptor LegacyFormatTargetDescriptor = CreateDescriptor( IDEDiagnosticIds.LegacyFormatSuppressMessageAttributeDiagnosticId, EnforceOnBuildValues.LegacyFormatSuppressMessageAttribute, s_localizableLegacyFormatTitle, s_localizableLegacyFormatMessage, isUnnecessary: false); protected AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer() : base(ImmutableArray.Create(s_invalidScopeDescriptor, s_invalidOrMissingTargetDescriptor, LegacyFormatTargetDescriptor), GeneratedCodeAnalysisFlags.None) { } protected abstract void RegisterAttributeSyntaxAction(CompilationStartAnalysisContext context, CompilationAnalyzer compilationAnalyzer); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(context => { var suppressMessageAttributeType = context.Compilation.SuppressMessageAttributeType(); if (suppressMessageAttributeType == null) { return; } RegisterAttributeSyntaxAction(context, new CompilationAnalyzer(context.Compilation, suppressMessageAttributeType)); }); } protected sealed class CompilationAnalyzer { private readonly SuppressMessageAttributeState _state; public CompilationAnalyzer(Compilation compilation, INamedTypeSymbol suppressMessageAttributeType) { _state = new SuppressMessageAttributeState(compilation, suppressMessageAttributeType); } public void AnalyzeAssemblyOrModuleAttribute(SyntaxNode attributeSyntax, SemanticModel model, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken) { if (!_state.IsSuppressMessageAttributeWithNamedArguments(attributeSyntax, model, cancellationToken, out var namedAttributeArguments)) { return; } if (!SuppressMessageAttributeState.HasValidScope(namedAttributeArguments, out var targetScope)) { reportDiagnostic(Diagnostic.Create(s_invalidScopeDescriptor, attributeSyntax.GetLocation())); return; } if (!_state.HasValidTarget(namedAttributeArguments, targetScope, out var targetHasDocCommentIdFormat, out var targetSymbolString, out var targetValueOperation, out var resolvedSymbols)) { reportDiagnostic(Diagnostic.Create(s_invalidOrMissingTargetDescriptor, attributeSyntax.GetLocation())); return; } // We want to flag valid target which uses legacy format to update to Roslyn based DocCommentId format. if (resolvedSymbols.Length > 0 && !targetHasDocCommentIdFormat) { RoslynDebug.Assert(!string.IsNullOrEmpty(targetSymbolString)); RoslynDebug.Assert(targetValueOperation != null); var properties = ImmutableDictionary<string, string?>.Empty; if (resolvedSymbols.Length == 1) { // We provide a code fix for the case where the target resolved to a single symbol. var docCommentId = DocumentationCommentId.CreateDeclarationId(resolvedSymbols[0]); if (!string.IsNullOrEmpty(docCommentId)) { // Suppression target has an optional "~" prefix to distinguish it from legacy FxCop suppressions. // IDE suppression code fixes emit this prefix, so we we also add this prefix to new suppression target string. properties = properties.Add(DocCommentIdKey, "~" + docCommentId); } } reportDiagnostic(Diagnostic.Create(LegacyFormatTargetDescriptor, targetValueOperation.Syntax.GetLocation(), properties!, targetSymbolString)); return; } } } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.fr.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../WorkspaceMSBuildResources.resx"> <body> <trans-unit id="Failed_to_load_solution_filter_0"> <source>Failed to load solution filter: '{0}'</source> <target state="translated">Échec du chargement du filtre de solution : '{0}'</target> <note /> </trans-unit> <trans-unit id="Found_project_reference_without_a_matching_metadata_reference_0"> <source>Found project reference without a matching metadata reference: {0}</source> <target state="translated">Référence de projet sans référence de métadonnées correspondante : {0}</target> <note /> </trans-unit> <trans-unit id="Invalid_0_specified_1"> <source>Invalid {0} specified: {1}</source> <target state="translated">{0} non valide spécifié : {1}</target> <note /> </trans-unit> <trans-unit id="Msbuild_failed_when_processing_the_file_0"> <source>Msbuild failed when processing the file '{0}'</source> <target state="translated">Échec de Msbuild pendant le traitement du fichier '{0}'</target> <note /> </trans-unit> <trans-unit id="Msbuild_failed_when_processing_the_file_0_with_message_1"> <source>Msbuild failed when processing the file '{0}' with message: {1}</source> <target state="translated">MSBuild a échoué pendant le traitement du fichier '{0}' avec le message : {1}</target> <note /> </trans-unit> <trans-unit id="Parameter_cannot_be_null_empty_or_contain_whitespace"> <source>Parameter cannot be null, empty, or contain whitespace.</source> <target state="translated">Le paramètre ne peut pas être null, vide ou contenir d’espaces.</target> <note /> </trans-unit> <trans-unit id="Path_for_additional_document_0_was_null"> <source>Path for additional document '{0}' was null}</source> <target state="translated">Chemin d’accès pour le document supplémentaire « {0} » était nul}</target> <note /> </trans-unit> <trans-unit id="Path_for_document_0_was_null"> <source>Path for document '{0}' was null</source> <target state="translated">Chemin d’accès du document '{0}' était null</target> <note /> </trans-unit> <trans-unit id="Project_already_added"> <source>Project already added.</source> <target state="translated">Le projet existe déjà.</target> <note /> </trans-unit> <trans-unit id="Project_does_not_contain_0_target"> <source>Project does not contain '{0}' target.</source> <target state="translated">Le projet ne contient pas la cible '{0}'.</target> <note /> </trans-unit> <trans-unit id="Found_project_with_the_same_file_path_and_output_path_as_another_project_0"> <source>Found project with the same file path and output path as another project: {0}</source> <target state="translated">Projet avec les mêmes chemin de fichier et chemin de sortie que ceux d'un autre projet : {0}</target> <note /> </trans-unit> <trans-unit id="Duplicate_project_discovered_and_skipped_0"> <source>Duplicate project discovered and skipped: {0}</source> <target state="translated">Projet dupliqué découvert et ignoré : {0}</target> <note /> </trans-unit> <trans-unit id="Project_does_not_have_a_path"> <source>Project does not have a path.</source> <target state="translated">Le projet n’a pas de chemin d’accès.</target> <note /> </trans-unit> <trans-unit id="Project_path_for_0_was_null"> <source>Project path for '{0}' was null</source> <target state="translated">Le chemin d’accès du projet pour '{0}' était null</target> <note /> </trans-unit> <trans-unit id="Unable_to_add_metadata_reference_0"> <source>Unable to add metadata reference '{0}'</source> <target state="translated">Impossible d’ajouter une référence de métadonnées '{0}'</target> <note /> </trans-unit> <trans-unit id="Unable_to_find_0"> <source>Unable to find '{0}'</source> <target state="translated">'{0}' est introuvable</target> <note /> </trans-unit> <trans-unit id="Unable_to_find_a_0_for_1"> <source>Unable to find a '{0}' for '{1}'</source> <target state="translated">Impossible de trouver un '{0}' pour '{1}'</target> <note /> </trans-unit> <trans-unit id="Unable_to_remove_metadata_reference_0"> <source>Unable to remove metadata reference '{0}'</source> <target state="translated">Impossible de supprimer la référence de métadonnées '{0}'</target> <note /> </trans-unit> <trans-unit id="Unresolved_metadata_reference_removed_from_project_0"> <source>Unresolved metadata reference removed from project: {0}</source> <target state="translated">Référence de métadonnées non résolues supprimées du projet : {0}</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../WorkspaceMSBuildResources.resx"> <body> <trans-unit id="Failed_to_load_solution_filter_0"> <source>Failed to load solution filter: '{0}'</source> <target state="translated">Échec du chargement du filtre de solution : '{0}'</target> <note /> </trans-unit> <trans-unit id="Found_project_reference_without_a_matching_metadata_reference_0"> <source>Found project reference without a matching metadata reference: {0}</source> <target state="translated">Référence de projet sans référence de métadonnées correspondante : {0}</target> <note /> </trans-unit> <trans-unit id="Invalid_0_specified_1"> <source>Invalid {0} specified: {1}</source> <target state="translated">{0} non valide spécifié : {1}</target> <note /> </trans-unit> <trans-unit id="Msbuild_failed_when_processing_the_file_0"> <source>Msbuild failed when processing the file '{0}'</source> <target state="translated">Échec de Msbuild pendant le traitement du fichier '{0}'</target> <note /> </trans-unit> <trans-unit id="Msbuild_failed_when_processing_the_file_0_with_message_1"> <source>Msbuild failed when processing the file '{0}' with message: {1}</source> <target state="translated">MSBuild a échoué pendant le traitement du fichier '{0}' avec le message : {1}</target> <note /> </trans-unit> <trans-unit id="Parameter_cannot_be_null_empty_or_contain_whitespace"> <source>Parameter cannot be null, empty, or contain whitespace.</source> <target state="translated">Le paramètre ne peut pas être null, vide ou contenir d’espaces.</target> <note /> </trans-unit> <trans-unit id="Path_for_additional_document_0_was_null"> <source>Path for additional document '{0}' was null}</source> <target state="translated">Chemin d’accès pour le document supplémentaire « {0} » était nul}</target> <note /> </trans-unit> <trans-unit id="Path_for_document_0_was_null"> <source>Path for document '{0}' was null</source> <target state="translated">Chemin d’accès du document '{0}' était null</target> <note /> </trans-unit> <trans-unit id="Project_already_added"> <source>Project already added.</source> <target state="translated">Le projet existe déjà.</target> <note /> </trans-unit> <trans-unit id="Project_does_not_contain_0_target"> <source>Project does not contain '{0}' target.</source> <target state="translated">Le projet ne contient pas la cible '{0}'.</target> <note /> </trans-unit> <trans-unit id="Found_project_with_the_same_file_path_and_output_path_as_another_project_0"> <source>Found project with the same file path and output path as another project: {0}</source> <target state="translated">Projet avec les mêmes chemin de fichier et chemin de sortie que ceux d'un autre projet : {0}</target> <note /> </trans-unit> <trans-unit id="Duplicate_project_discovered_and_skipped_0"> <source>Duplicate project discovered and skipped: {0}</source> <target state="translated">Projet dupliqué découvert et ignoré : {0}</target> <note /> </trans-unit> <trans-unit id="Project_does_not_have_a_path"> <source>Project does not have a path.</source> <target state="translated">Le projet n’a pas de chemin d’accès.</target> <note /> </trans-unit> <trans-unit id="Project_path_for_0_was_null"> <source>Project path for '{0}' was null</source> <target state="translated">Le chemin d’accès du projet pour '{0}' était null</target> <note /> </trans-unit> <trans-unit id="Unable_to_add_metadata_reference_0"> <source>Unable to add metadata reference '{0}'</source> <target state="translated">Impossible d’ajouter une référence de métadonnées '{0}'</target> <note /> </trans-unit> <trans-unit id="Unable_to_find_0"> <source>Unable to find '{0}'</source> <target state="translated">'{0}' est introuvable</target> <note /> </trans-unit> <trans-unit id="Unable_to_find_a_0_for_1"> <source>Unable to find a '{0}' for '{1}'</source> <target state="translated">Impossible de trouver un '{0}' pour '{1}'</target> <note /> </trans-unit> <trans-unit id="Unable_to_remove_metadata_reference_0"> <source>Unable to remove metadata reference '{0}'</source> <target state="translated">Impossible de supprimer la référence de métadonnées '{0}'</target> <note /> </trans-unit> <trans-unit id="Unresolved_metadata_reference_removed_from_project_0"> <source>Unresolved metadata reference removed from project: {0}</source> <target state="translated">Référence de métadonnées non résolues supprimées du projet : {0}</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/VisualStudio/Core/Test/CodeModel/AbstractCodeModelObjectTests.ClassData.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Partial Public MustInherit Class AbstractCodeModelObjectTests(Of TCodeModelObject As Class) Protected Class ClassData Public Property Name As String Public Property Position As Object = 0 Public Property Bases As Object Public Property ImplementedInterfaces As Object Public Property Access As EnvDTE.vsCMAccess = EnvDTE.vsCMAccess.vsCMAccessDefault End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Partial Public MustInherit Class AbstractCodeModelObjectTests(Of TCodeModelObject As Class) Protected Class ClassData Public Property Name As String Public Property Position As Object = 0 Public Property Bases As Object Public Property ImplementedInterfaces As Object Public Property Access As EnvDTE.vsCMAccess = EnvDTE.vsCMAccess.vsCMAccessDefault End Class End Class End Namespace
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/Core/Portable/SourceGeneration/Nodes/IIncrementalGeneratorNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a node in the execution pipeline of an incremental generator /// </summary> /// <typeparam name="T">The type of value this step operates on</typeparam> internal interface IIncrementalGeneratorNode<T> { NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken); IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer); void RegisterOutput(IIncrementalGeneratorOutputNode output); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a node in the execution pipeline of an incremental generator /// </summary> /// <typeparam name="T">The type of value this step operates on</typeparam> internal interface IIncrementalGeneratorNode<T> { NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken); IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer); void RegisterOutput(IIncrementalGeneratorOutputNode output); } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/VisualStudio/TestUtilities2/ProjectSystemShim/Framework/ExtensionMethods.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Friend Module ExtensionMethods <Extension> Public Function HasMetadataReference(project As Project, path As String) As Boolean Return project.MetadataReferences.Cast(Of PortableExecutableReference).Any(Function(vsReference) String.Equals(vsReference.FilePath, path, StringComparison.OrdinalIgnoreCase)) End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Friend Module ExtensionMethods <Extension> Public Function HasMetadataReference(project As Project, path As String) As Boolean Return project.MetadataReferences.Cast(Of PortableExecutableReference).Any(Function(vsReference) String.Equals(vsReference.FilePath, path, StringComparison.OrdinalIgnoreCase)) End Function End Module End Namespace
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/CSharp/Test/Syntax/IncrementalParsing/CompoundAssignment.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.IncrementalParsing { // These tests test changes between different compound assignment expressions public class CompoundAssignment { [Fact] public void AssignToPlus() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.AddAssignmentExpression); } [Fact] public void AssignToSubtract() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.SubtractAssignmentExpression); } [Fact] public void AssignToMultiply() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.MultiplyAssignmentExpression); } [Fact] public void AssignToDivide() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.DivideAssignmentExpression); } [Fact] public void AssignToModule() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.ModuloAssignmentExpression); } [Fact] public void AssignToExclusiveOr() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.ExclusiveOrAssignmentExpression); } [Fact] public void AssignToLeftShift() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.LeftShiftAssignmentExpression); } [Fact] public void AssignToRightShift() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.RightShiftAssignmentExpression); } [Fact] public void AssignToAnd() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.AndAssignmentExpression); } [Fact] public void AssignToOr() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.OrAssignmentExpression); } #region Helper Methods private static void MakeAssignmentChange(SyntaxKind oldStyle, SyntaxKind newStyle) { MakeAssignmentChanges(oldStyle, newStyle); MakeAssignmentChanges(oldStyle, newStyle, options: TestOptions.Script); MakeAssignmentChanges(oldStyle, newStyle, topLevel: true, options: TestOptions.Script); } private static void MakeAssignmentChanges(SyntaxKind oldSyntaxKind, SyntaxKind newSyntaxKind, bool topLevel = false, CSharpParseOptions options = null) { string oldName = GetExpressionString(oldSyntaxKind); string newName = GetExpressionString(newSyntaxKind); string topLevelStatement = "x " + oldName + " y"; var code = @"class C { void m() { " + topLevelStatement + @"; }}"; var oldTree = SyntaxFactory.ParseSyntaxTree(topLevel ? topLevelStatement : code, options: options); // Make the change to the node var newTree = oldTree.WithReplaceFirst(oldName, newName); var binNode = topLevel ? GetGlobalStatementSyntaxChange(newTree) : GetExpressionSyntaxChange(newTree); Assert.Equal(binNode.Kind(), newSyntaxKind); } private static string GetExpressionString(SyntaxKind oldStyle) { switch (oldStyle) { case SyntaxKind.SimpleAssignmentExpression: return "="; case SyntaxKind.AddAssignmentExpression: return "+="; case SyntaxKind.SubtractAssignmentExpression: return "-="; case SyntaxKind.MultiplyAssignmentExpression: return "*="; case SyntaxKind.DivideAssignmentExpression: return "/="; case SyntaxKind.ModuloAssignmentExpression: return "%="; case SyntaxKind.AndAssignmentExpression: return "&="; case SyntaxKind.ExclusiveOrAssignmentExpression: return "^="; case SyntaxKind.OrAssignmentExpression: return "|="; case SyntaxKind.LeftShiftAssignmentExpression: return "<<="; case SyntaxKind.RightShiftAssignmentExpression: return ">>="; default: throw new Exception("No operator found"); } } private static AssignmentExpressionSyntax GetExpressionSyntaxChange(SyntaxTree newTree) { var classType = newTree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; var method = classType.Members[0] as MethodDeclarationSyntax; var block = method.Body; var statement = block.Statements[0] as ExpressionStatementSyntax; var expression = statement.Expression as AssignmentExpressionSyntax; return expression; } private static AssignmentExpressionSyntax GetGlobalStatementSyntaxChange(SyntaxTree newTree) { var statementType = newTree.GetCompilationUnitRoot().Members[0] as GlobalStatementSyntax; Assert.True(statementType.AttributeLists.Count == 0); Assert.True(statementType.Modifiers.Count == 0); var statement = statementType.Statement as ExpressionStatementSyntax; var expression = statement.Expression as AssignmentExpressionSyntax; return expression; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.IncrementalParsing { // These tests test changes between different compound assignment expressions public class CompoundAssignment { [Fact] public void AssignToPlus() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.AddAssignmentExpression); } [Fact] public void AssignToSubtract() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.SubtractAssignmentExpression); } [Fact] public void AssignToMultiply() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.MultiplyAssignmentExpression); } [Fact] public void AssignToDivide() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.DivideAssignmentExpression); } [Fact] public void AssignToModule() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.ModuloAssignmentExpression); } [Fact] public void AssignToExclusiveOr() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.ExclusiveOrAssignmentExpression); } [Fact] public void AssignToLeftShift() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.LeftShiftAssignmentExpression); } [Fact] public void AssignToRightShift() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.RightShiftAssignmentExpression); } [Fact] public void AssignToAnd() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.AndAssignmentExpression); } [Fact] public void AssignToOr() { MakeAssignmentChange(SyntaxKind.SimpleAssignmentExpression, SyntaxKind.OrAssignmentExpression); } #region Helper Methods private static void MakeAssignmentChange(SyntaxKind oldStyle, SyntaxKind newStyle) { MakeAssignmentChanges(oldStyle, newStyle); MakeAssignmentChanges(oldStyle, newStyle, options: TestOptions.Script); MakeAssignmentChanges(oldStyle, newStyle, topLevel: true, options: TestOptions.Script); } private static void MakeAssignmentChanges(SyntaxKind oldSyntaxKind, SyntaxKind newSyntaxKind, bool topLevel = false, CSharpParseOptions options = null) { string oldName = GetExpressionString(oldSyntaxKind); string newName = GetExpressionString(newSyntaxKind); string topLevelStatement = "x " + oldName + " y"; var code = @"class C { void m() { " + topLevelStatement + @"; }}"; var oldTree = SyntaxFactory.ParseSyntaxTree(topLevel ? topLevelStatement : code, options: options); // Make the change to the node var newTree = oldTree.WithReplaceFirst(oldName, newName); var binNode = topLevel ? GetGlobalStatementSyntaxChange(newTree) : GetExpressionSyntaxChange(newTree); Assert.Equal(binNode.Kind(), newSyntaxKind); } private static string GetExpressionString(SyntaxKind oldStyle) { switch (oldStyle) { case SyntaxKind.SimpleAssignmentExpression: return "="; case SyntaxKind.AddAssignmentExpression: return "+="; case SyntaxKind.SubtractAssignmentExpression: return "-="; case SyntaxKind.MultiplyAssignmentExpression: return "*="; case SyntaxKind.DivideAssignmentExpression: return "/="; case SyntaxKind.ModuloAssignmentExpression: return "%="; case SyntaxKind.AndAssignmentExpression: return "&="; case SyntaxKind.ExclusiveOrAssignmentExpression: return "^="; case SyntaxKind.OrAssignmentExpression: return "|="; case SyntaxKind.LeftShiftAssignmentExpression: return "<<="; case SyntaxKind.RightShiftAssignmentExpression: return ">>="; default: throw new Exception("No operator found"); } } private static AssignmentExpressionSyntax GetExpressionSyntaxChange(SyntaxTree newTree) { var classType = newTree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax; var method = classType.Members[0] as MethodDeclarationSyntax; var block = method.Body; var statement = block.Statements[0] as ExpressionStatementSyntax; var expression = statement.Expression as AssignmentExpressionSyntax; return expression; } private static AssignmentExpressionSyntax GetGlobalStatementSyntaxChange(SyntaxTree newTree) { var statementType = newTree.GetCompilationUnitRoot().Members[0] as GlobalStatementSyntax; Assert.True(statementType.AttributeLists.Count == 0); Assert.True(statementType.Modifiers.Count == 0); var statement = statementType.Statement as ExpressionStatementSyntax; var expression = statement.Expression as AssignmentExpressionSyntax; return expression; } #endregion } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/Test/Resources/Core/SymbolsTests/Metadata/AttributeInterop02.dll
MZ@ !L!This program cannot be run in DOS mode. $PELjM! >/ @@ @.K@`  H.textD  `.rsrc@@@.reloc `@B /Hd  * * *( *BSJB v4.0.30319l|#~#Strings #US #GUID #BlobW %3 0 qRRR *FaRRRRRR!R1RFRafRzR!)1)?) G) ]) s) ))  1ր9V>VBVF        $& 2& P C S ] V w Y  , 2:,@:,I :%T&Z'`(f)n*v.LLOLLOLLLOLO 'CA I Q Y aiq y  ' Q    T  }   s6'.Kq.Ch@s?Ck-CcC[`sHcYcckdZ[k!##[*$+3; <Module>AttributeInterop02.dllIEventsEventNSIEvents_EventNetImplOnEvent01EventHandlerOnEvent02EventHandlerOnEvent03EventHandlerIOptionalMyEnummscorlibSystemObjectMulticastDelegateEnumOnEvent01OnEvent02OnEvent03add_OnEvent01remove_OnEvent01add_OnEvent02remove_OnEvent02add_OnEvent03remove_OnEvent03EventNS.IEvents.OnEvent01EventNS.IEvents.OnEvent02EventNS.IEvents.OnEvent03.ctorInvokeIAsyncResultAsyncCallbackBeginInvokeEndInvokeMethodRefMethodRef1MethodRef2MethodRef3NandOMethod6DateTimeDecimalMethodWithConstantValuesvalue__zeroonetwothreei1i2System.Runtime.InteropServicesOptionalAttributeSystem.Runtime.CompilerServicesIUnknownConstantAttributebvalueobjectmethodcallbackresultvInAttributeOutAttributev1v2v3v4p1DateTimeConstantAttributep2DecimalConstantAttributep3IDispatchConstantAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeAttributeInterop02ComImportAttributeGuidAttributeInterfaceTypeAttributeComInterfaceTypeTypeLibTypeAttributeTypeLibTypeFlagsDispIdAttributePreserveSigAttributeComEventInterfaceAttributeTypeComVisibleAttributeComSourceInterfacesAttributeFlagsAttributeNonSerializedAttributeObsoleteAttributeSystem.SecurityUnverifiableCodeAttribute aBWE UOz\V4                 $$   $XcRef   @ ddd  )$904458F3-005B-4DFD-8581-E9832D7FA407 Q Y@efg iinEventNS.IEventsYSystem.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089  iEventNS.IEvents)$01230DD5-2448-447A-B786-64682CBEFEEE)$31230DD5-2448-447A-B786-64682CBEFEEE  messageTWrapNonExceptionThrows/./ /_CorDllMainmscoree.dll% @0HX@tt4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0PInternalNameAttributeInterop02.dll(LegalCopyright XOriginalFilenameAttributeInterop02.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 @?
MZ@ !L!This program cannot be run in DOS mode. $PELjM! >/ @@ @.K@`  H.textD  `.rsrc@@@.reloc `@B /Hd  * * *( *BSJB v4.0.30319l|#~#Strings #US #GUID #BlobW %3 0 qRRR *FaRRRRRR!R1RFRafRzR!)1)?) G) ]) s) ))  1ր9V>VBVF        $& 2& P C S ] V w Y  , 2:,@:,I :%T&Z'`(f)n*v.LLOLLOLLLOLO 'CA I Q Y aiq y  ' Q    T  }   s6'.Kq.Ch@s?Ck-CcC[`sHcYcckdZ[k!##[*$+3; <Module>AttributeInterop02.dllIEventsEventNSIEvents_EventNetImplOnEvent01EventHandlerOnEvent02EventHandlerOnEvent03EventHandlerIOptionalMyEnummscorlibSystemObjectMulticastDelegateEnumOnEvent01OnEvent02OnEvent03add_OnEvent01remove_OnEvent01add_OnEvent02remove_OnEvent02add_OnEvent03remove_OnEvent03EventNS.IEvents.OnEvent01EventNS.IEvents.OnEvent02EventNS.IEvents.OnEvent03.ctorInvokeIAsyncResultAsyncCallbackBeginInvokeEndInvokeMethodRefMethodRef1MethodRef2MethodRef3NandOMethod6DateTimeDecimalMethodWithConstantValuesvalue__zeroonetwothreei1i2System.Runtime.InteropServicesOptionalAttributeSystem.Runtime.CompilerServicesIUnknownConstantAttributebvalueobjectmethodcallbackresultvInAttributeOutAttributev1v2v3v4p1DateTimeConstantAttributep2DecimalConstantAttributep3IDispatchConstantAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeAttributeInterop02ComImportAttributeGuidAttributeInterfaceTypeAttributeComInterfaceTypeTypeLibTypeAttributeTypeLibTypeFlagsDispIdAttributePreserveSigAttributeComEventInterfaceAttributeTypeComVisibleAttributeComSourceInterfacesAttributeFlagsAttributeNonSerializedAttributeObsoleteAttributeSystem.SecurityUnverifiableCodeAttribute aBWE UOz\V4                 $$   $XcRef   @ ddd  )$904458F3-005B-4DFD-8581-E9832D7FA407 Q Y@efg iinEventNS.IEventsYSystem.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089  iEventNS.IEvents)$01230DD5-2448-447A-B786-64682CBEFEEE)$31230DD5-2448-447A-B786-64682CBEFEEE  messageTWrapNonExceptionThrows/./ /_CorDllMainmscoree.dll% @0HX@tt4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0PInternalNameAttributeInterop02.dll(LegalCopyright XOriginalFilenameAttributeInterop02.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 @?
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/Test/Core/Assert/TestExceptionUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Test.Utilities { public static class TestExceptionUtilities { public static InvalidOperationException UnexpectedValue(object o) { string output = string.Format("Unexpected value '{0}' of type '{1}'", o, (o != null) ? o.GetType().FullName : "<unknown>"); System.Diagnostics.Debug.Fail(output); return new InvalidOperationException(output); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Test.Utilities { public static class TestExceptionUtilities { public static InvalidOperationException UnexpectedValue(object o) { string output = string.Format("Unexpected value '{0}' of type '{1}'", o, (o != null) ? o.GetType().FullName : "<unknown>"); System.Diagnostics.Debug.Fail(output); return new InvalidOperationException(output); } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; #pragma warning disable CS0660 namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A TypeSymbol is a base class for all the symbols that represent a type /// in C#. /// </summary> internal abstract partial class TypeSymbol : NamespaceOrTypeSymbol, ITypeSymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO (tomat): Consider changing this to an empty name. This name shouldn't ever leak to the user in error messages. internal const string ImplicitTypeName = "<invalid-global-code>"; // InterfaceInfo for a common case of a type not implementing anything directly or indirectly. private static readonly InterfaceInfo s_noInterfaces = new InterfaceInfo(); private ImmutableHashSet<Symbol> _lazyAbstractMembers; private InterfaceInfo _lazyInterfaceInfo; private class InterfaceInfo { // all directly implemented interfaces, their bases and all interfaces to the bases of the type recursively internal ImmutableArray<NamedTypeSymbol> allInterfaces; /// <summary> /// <see cref="TypeSymbol.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics"/> /// </summary> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> interfacesAndTheirBaseInterfaces; internal static readonly MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> EmptyInterfacesAndTheirBaseInterfaces = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(0, SymbolEqualityComparer.CLRSignature); // Key is implemented member (method, property, or event), value is implementing member (from the // perspective of this type). Don't allocate until someone needs it. private ConcurrentDictionary<Symbol, SymbolAndDiagnostics> _implementationForInterfaceMemberMap; public ConcurrentDictionary<Symbol, SymbolAndDiagnostics> ImplementationForInterfaceMemberMap { get { var map = _implementationForInterfaceMemberMap; if (map != null) { return map; } // PERF: Avoid over-allocation. In many cases, there's only 1 entry and we don't expect concurrent updates. map = new ConcurrentDictionary<Symbol, SymbolAndDiagnostics>(concurrencyLevel: 1, capacity: 1, comparer: SymbolEqualityComparer.ConsiderEverything); return Interlocked.CompareExchange(ref _implementationForInterfaceMemberMap, map, null) ?? map; } } /// <summary> /// key = interface method/property/event compared using <see cref="ExplicitInterfaceImplementationTargetMemberEqualityComparer"/>, /// value = explicitly implementing methods/properties/events declared on this type (normally a single value, multiple in case of /// an error). /// </summary> internal MultiDictionary<Symbol, Symbol> explicitInterfaceImplementationMap; #nullable enable internal ImmutableDictionary<MethodSymbol, MethodSymbol>? synthesizedMethodImplMap; #nullable disable internal bool IsDefaultValue() { return allInterfaces.IsDefault && interfacesAndTheirBaseInterfaces == null && _implementationForInterfaceMemberMap == null && explicitInterfaceImplementationMap == null && synthesizedMethodImplMap == null; } } private InterfaceInfo GetInterfaceInfo() { var info = _lazyInterfaceInfo; if (info != null) { Debug.Assert(info != s_noInterfaces || info.IsDefaultValue(), "default value was modified"); return info; } for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); if (!interfaces.IsEmpty) { // it looks like we or one of our bases implements something. info = new InterfaceInfo(); // NOTE: we are assigning lazyInterfaceInfo via interlocked not for correctness, // we just do not want to override an existing info that could be partially filled. return Interlocked.CompareExchange(ref _lazyInterfaceInfo, info, null) ?? info; } } // if we have got here it means neither we nor our bases implement anything _lazyInterfaceInfo = info = s_noInterfaces; return info; } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new TypeSymbol OriginalDefinition { get { return OriginalTypeSymbolDefinition; } } protected virtual TypeSymbol OriginalTypeSymbolDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalTypeSymbolDefinition; } } /// <summary> /// Gets the BaseType of this type. If the base type could not be determined, then /// an instance of ErrorType is returned. If this kind of type does not have a base type /// (for example, interfaces), null is returned. Also the special class System.Object /// always has a BaseType of null. /// </summary> internal abstract NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get; } internal NamedTypeSymbol BaseTypeWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } internal NamedTypeSymbol BaseTypeOriginalDefinition(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result = result.OriginalDefinition; result.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// Gets the set of interfaces that this type directly implements. This set does not include /// interfaces that are base interfaces of directly implemented interfaces. /// </summary> internal abstract ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null); /// <summary> /// The list of all interfaces of which this type is a declared subtype, excluding this type /// itself. This includes all declared base interfaces, all declared base interfaces of base /// types, and all declared base interfaces of those results (recursively). Each result /// appears exactly once in the list. This list is topologically sorted by the inheritance /// relationship: if interface type A extends interface type B, then A precedes B in the /// list. This is not quite the same as "all interfaces of which this type is a proper /// subtype" because it does not take into account variance: AllInterfaces for /// IEnumerable&lt;string&gt; will not include IEnumerable&lt;object&gt; /// </summary> internal ImmutableArray<NamedTypeSymbol> AllInterfacesNoUseSiteDiagnostics { get { return GetAllInterfaces(); } } internal ImmutableArray<NamedTypeSymbol> AllInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = AllInterfacesNoUseSiteDiagnostics; // Since bases affect content of AllInterfaces set, we need to make sure they all are good. var current = this; do { current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } while ((object)current != null); foreach (var iface in result) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// If this is a type parameter returns its effective base class, otherwise returns this type. /// </summary> internal TypeSymbol EffectiveTypeNoUseSiteDiagnostics { get { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClassNoUseSiteDiagnostics : this; } } internal TypeSymbol EffectiveType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClass(ref useSiteInfo) : this; } /// <summary> /// Returns true if this type derives from a given type. /// </summary> internal bool IsDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)type != null); Debug.Assert(!type.IsTypeParameter()); if ((object)this == (object)type) { return false; } var t = this.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)t != null) { if (type.Equals(t, comparison)) { return true; } t = t.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } /// <summary> /// Returns true if this type is equal or derives from a given type. /// </summary> internal bool IsEqualToOrDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.Equals(type, comparison) || this.IsDerivedFrom(type, comparison, ref useSiteInfo); } /// <summary> /// Determines if this type symbol represent the same type as another, according to the language /// semantics. /// </summary> /// <param name="t2">The other type.</param> /// <param name="compareKind"> /// What kind of comparison to use? /// You can ignore custom modifiers, ignore the distinction between object and dynamic, or ignore tuple element names differences. /// </param> /// <returns>True if the types are equivalent.</returns> internal virtual bool Equals(TypeSymbol t2, TypeCompareKind compareKind) { return ReferenceEquals(this, t2); } public sealed override bool Equals(Symbol other, TypeCompareKind compareKind) { var t2 = other as TypeSymbol; if (t2 is null) { return false; } return this.Equals(t2, compareKind); } /// <summary> /// We ignore custom modifiers, and the distinction between dynamic and object, when computing a type's hash code. /// </summary> /// <returns></returns> public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } protected virtual ImmutableArray<NamedTypeSymbol> GetAllInterfaces() { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return ImmutableArray<NamedTypeSymbol>.Empty; } if (info.allInterfaces.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref info.allInterfaces, MakeAllInterfaces()); } return info.allInterfaces; } /// Produce all implemented interfaces in topologically sorted order. We use /// TypeSymbol.Interfaces as the source of edge data, which has had cycles and infinitely /// long dependency cycles removed. Consequently, it is possible (and we do) use the /// simplest version of Tarjan's topological sorting algorithm. protected virtual ImmutableArray<NamedTypeSymbol> MakeAllInterfaces() { var result = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var visited = new HashSet<NamedTypeSymbol>(SymbolEqualityComparer.ConsiderEverything); for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); for (int i = interfaces.Length - 1; i >= 0; i--) { addAllInterfaces(interfaces[i], visited, result); } } result.ReverseContents(); return result.ToImmutableAndFree(); static void addAllInterfaces(NamedTypeSymbol @interface, HashSet<NamedTypeSymbol> visited, ArrayBuilder<NamedTypeSymbol> result) { if (visited.Add(@interface)) { ImmutableArray<NamedTypeSymbol> baseInterfaces = @interface.InterfacesNoUseSiteDiagnostics(); for (int i = baseInterfaces.Length - 1; i >= 0; i--) { var baseInterface = baseInterfaces[i]; addAllInterfaces(baseInterface, visited, result); } result.Add(@interface); } } } /// <summary> /// Gets the set of interfaces that this type directly implements, plus the base interfaces /// of all such types. Keys are compared using <see cref="SymbolEqualityComparer.CLRSignature"/>, /// values are distinct interfaces corresponding to the key, according to <see cref="TypeCompareKind.ConsiderEverything"/> rules. /// </summary> /// <remarks> /// CONSIDER: it probably isn't truly necessary to cache this. If space gets tight, consider /// alternative approaches (recompute every time, cache on the side, only store on some types, /// etc). /// </remarks> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics { get { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { Debug.Assert(InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces.IsEmpty); return InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces; } if (info.interfacesAndTheirBaseInterfaces == null) { Interlocked.CompareExchange(ref info.interfacesAndTheirBaseInterfaces, MakeInterfacesAndTheirBaseInterfaces(this.InterfacesNoUseSiteDiagnostics()), null); } return info.interfacesAndTheirBaseInterfaces; } } internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics; foreach (var iface in result.Keys) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } // Note: Unlike MakeAllInterfaces, this doesn't need to be virtual. It depends on // AllInterfaces for its implementation, so it will pick up all changes to MakeAllInterfaces // indirectly. private static MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> MakeInterfacesAndTheirBaseInterfaces(ImmutableArray<NamedTypeSymbol> declaredInterfaces) { var resultBuilder = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(declaredInterfaces.Length, SymbolEqualityComparer.CLRSignature, SymbolEqualityComparer.ConsiderEverything); foreach (var @interface in declaredInterfaces) { if (resultBuilder.Add(@interface, @interface)) { foreach (var baseInterface in @interface.AllInterfacesNoUseSiteDiagnostics) { resultBuilder.Add(baseInterface, baseInterface); } } } return resultBuilder; } /// <summary> /// Returns the corresponding symbol in this type or a base type that implements /// interfaceMember (either implicitly or explicitly), or null if no such symbol exists /// (which might be either because this type doesn't implement the container of /// interfaceMember, or this type doesn't supply a member that successfully implements /// interfaceMember). /// </summary> /// <param name="interfaceMember"> /// Must be a non-null interface property, method, or event. /// </param> public Symbol FindImplementationForInterfaceMember(Symbol interfaceMember) { if ((object)interfaceMember == null) { throw new ArgumentNullException(nameof(interfaceMember)); } if (!interfaceMember.IsImplementableInterfaceMember()) { return null; } if (this.IsInterfaceType()) { if (interfaceMember.IsStatic) { return null; } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return FindMostSpecificImplementation(interfaceMember, (NamedTypeSymbol)this, ref discardedUseSiteInfo); } return FindImplementationForInterfaceMemberInNonInterface(interfaceMember); } /// <summary> /// Returns true if this type is known to be a reference type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsReferenceType { get; } /// <summary> /// Returns true if this type is known to be a value type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsValueType { get; } // Only the compiler can create TypeSymbols. internal TypeSymbol() { } /// <summary> /// Gets the kind of this type. /// </summary> public abstract TypeKind TypeKind { get; } /// <summary> /// Gets corresponding special TypeId of this type. /// </summary> /// <remarks> /// Not preserved in types constructed from this one. /// </remarks> public virtual SpecialType SpecialType { get { return SpecialType.None; } } /// <summary> /// Gets corresponding primitive type code for this type declaration. /// </summary> internal Microsoft.Cci.PrimitiveTypeCode PrimitiveTypeCode => TypeKind switch { TypeKind.Pointer => Microsoft.Cci.PrimitiveTypeCode.Pointer, TypeKind.FunctionPointer => Microsoft.Cci.PrimitiveTypeCode.FunctionPointer, _ => SpecialTypes.GetTypeCode(SpecialType) }; #region Use-Site Diagnostics /// <summary> /// Return error code that has highest priority while calculating use site error for this symbol. /// </summary> protected override int HighestPriorityUseSiteError { get { return (int)ErrorCode.ERR_BogusType; } } public sealed override bool HasUnsupportedMetadata { get { DiagnosticInfo info = GetUseSiteInfo().DiagnosticInfo; return (object)info != null && info.Code == (int)ErrorCode.ERR_BogusType; } } internal abstract bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes); #endregion /// <summary> /// Is this a symbol for an anonymous type (including delegate). /// </summary> public virtual bool IsAnonymousType { get { return false; } } /// <summary> /// Is this a symbol for a Tuple. /// </summary> public virtual bool IsTupleType => false; /// <summary> /// True if the type represents a native integer. In C#, the types represented /// by language keywords 'nint' and 'nuint'. /// </summary> internal virtual bool IsNativeIntegerType => false; /// <summary> /// Verify if the given type is a tuple of a given cardinality, or can be used to back a tuple type /// with the given cardinality. /// </summary> internal bool IsTupleTypeOfCardinality(int targetCardinality) { if (IsTupleType) { return TupleElementTypesWithAnnotations.Length == targetCardinality; } return false; } /// <summary> /// If this symbol represents a tuple type, get the types of the tuple's elements. /// </summary> public virtual ImmutableArray<TypeWithAnnotations> TupleElementTypesWithAnnotations => default(ImmutableArray<TypeWithAnnotations>); /// <summary> /// If this symbol represents a tuple type, get the names of the tuple's elements. /// </summary> public virtual ImmutableArray<string> TupleElementNames => default(ImmutableArray<string>); /// <summary> /// If this symbol represents a tuple type, get the fields for the tuple's elements. /// Otherwise, returns default. /// </summary> public virtual ImmutableArray<FieldSymbol> TupleElements => default(ImmutableArray<FieldSymbol>); #nullable enable /// <summary> /// Is this type a managed type (false for everything but enum, pointer, and /// some struct types). /// </summary> /// <remarks> /// See Type::computeManagedType. /// </remarks> internal bool IsManagedType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => GetManagedKind(ref useSiteInfo) == ManagedKind.Managed; internal bool IsManagedTypeNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return IsManagedType(ref discardedUseSiteInfo); } } /// <summary> /// Indicates whether a type is managed or not (i.e. you can take a pointer to it). /// Contains additional cases to help implement FeatureNotAvailable diagnostics. /// </summary> internal abstract ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal ManagedKind ManagedKindNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return GetManagedKind(ref discardedUseSiteInfo); } } #nullable disable internal bool NeedsNullableAttribute() { return TypeWithAnnotations.NeedsNullableAttribute(typeWithAnnotationsOpt: default, typeOpt: this); } internal abstract void AddNullableTransforms(ArrayBuilder<byte> transforms); internal abstract bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result); internal abstract TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform); internal TypeSymbol SetUnknownNullabilityForReferenceTypes() { return SetNullabilityForReferenceTypes(s_setUnknownNullability); } private static readonly Func<TypeWithAnnotations, TypeWithAnnotations> s_setUnknownNullability = (type) => type.SetUnknownNullabilityForReferenceTypes(); /// <summary> /// Merges features of the type with another type where there is an identity conversion between them. /// The features to be merged are /// object vs dynamic (dynamic wins), tuple names (dropped in case of conflict), and nullable /// annotations (e.g. in type arguments). /// </summary> internal abstract TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance); /// <summary> /// Returns true if the type may contain embedded references /// </summary> public abstract bool IsRefLikeType { get; } /// <summary> /// Returns true if the type is a readonly struct /// </summary> public abstract bool IsReadOnly { get; } public string ToDisplayString(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayString((ITypeSymbol)ISymbol, topLevelNullability, format); } public ImmutableArray<SymbolDisplayPart> ToDisplayParts(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, format); } public string ToMinimalDisplayString( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayString((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } #region Interface member checks /// <summary> /// Locate implementation of the <paramref name="interfaceMember"/> in context of the current type. /// The method is using cache to optimize subsequent calls for the same <paramref name="interfaceMember"/>. /// </summary> /// <param name="interfaceMember">Member for which an implementation should be found.</param> /// <param name="ignoreImplementationInInterfacesIfResultIsNotReady"> /// The process of looking up an implementation for an accessor can involve figuring out how corresponding event/property is implemented, /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. And the process of looking up an implementation for a property can /// involve figuring out how corresponding accessors are implemented, <see cref="FindMostSpecificImplementationInInterfaces"/>. This can /// lead to cycles, which could be avoided if we ignore the presence of implementations in interfaces for the purpose of /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. Fortunately, logic in it allows us to ignore the presence of /// implementations in interfaces and we use that. /// When the value of this parameter is true and the result that takes presence of implementations in interfaces into account is not /// available from the cache, the lookup will be performed ignoring the presence of implementations in interfaces. Otherwise, result from /// the cache is returned. /// When the value of the parameter is false, the result from the cache is returned, or calculated, taking presence of implementations /// in interfaces into account and then cached. /// This means that: /// - A symbol from an interface can still be returned even when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. /// A subsequent call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If symbol from a non-interface is returned when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. A subsequent /// call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If no symbol is returned for <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> true. A subsequent call with /// <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> might return a symbol, but that symbol guaranteed to be from an interface. /// - If the first request is done with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false. A subsequent call /// is guaranteed to return the same result regardless of <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> value. /// </param> internal SymbolAndDiagnostics FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { Debug.Assert((object)interfaceMember != null); Debug.Assert(!this.IsInterfaceType()); if (this.IsInterfaceType()) { return SymbolAndDiagnostics.Empty; } var interfaceType = interfaceMember.ContainingType; if ((object)interfaceType == null || !interfaceType.IsInterface) { return SymbolAndDiagnostics.Empty; } switch (interfaceMember.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return SymbolAndDiagnostics.Empty; } // PERF: Avoid delegate allocation by splitting GetOrAdd into TryGetValue+TryAdd var map = info.ImplementationForInterfaceMemberMap; SymbolAndDiagnostics result; if (map.TryGetValue(interfaceMember, out result)) { return result; } result = ComputeImplementationAndDiagnosticsForInterfaceMember(interfaceMember, ignoreImplementationInInterfaces: ignoreImplementationInInterfacesIfResultIsNotReady, out bool implementationInInterfacesMightChangeResult); Debug.Assert(ignoreImplementationInInterfacesIfResultIsNotReady || !implementationInInterfacesMightChangeResult); Debug.Assert(!implementationInInterfacesMightChangeResult || result.Symbol is null); if (!implementationInInterfacesMightChangeResult) { map.TryAdd(interfaceMember, result); } return result; default: return SymbolAndDiagnostics.Empty; } } internal Symbol FindImplementationForInterfaceMemberInNonInterface(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { return FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMember, ignoreImplementationInInterfacesIfResultIsNotReady).Symbol; } private SymbolAndDiagnostics ComputeImplementationAndDiagnosticsForInterfaceMember(Symbol interfaceMember, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: this.DeclaringCompilation is object); var implementingMember = ComputeImplementationForInterfaceMember(interfaceMember, this, diagnostics, ignoreImplementationInInterfaces, out implementationInInterfacesMightChangeResult); var implementingMemberAndDiagnostics = new SymbolAndDiagnostics(implementingMember, diagnostics.ToReadOnlyAndFree()); return implementingMemberAndDiagnostics; } /// <summary> /// Performs interface mapping (spec 13.4.4). /// </summary> /// <remarks> /// CONSIDER: we could probably do less work in the metadata and retargeting cases - we won't use the diagnostics. /// </remarks> /// <param name="interfaceMember">A non-null implementable member on an interface type.</param> /// <param name="implementingType">The type implementing the interface property (usually "this").</param> /// <param name="diagnostics">Bag to which to add diagnostics.</param> /// <param name="ignoreImplementationInInterfaces">Do not consider implementation in an interface as a valid candidate for the purpose of this computation.</param> /// <param name="implementationInInterfacesMightChangeResult"> /// Returns true when <paramref name="ignoreImplementationInInterfaces"/> is true, the method fails to locate an implementation and an implementation in /// an interface, if any (its presence is not checked), could potentially be a candidate. Returns false otherwise. /// When true is returned, a different call with <paramref name="ignoreImplementationInInterfaces"/> false might return a symbol. That symbol, if any, /// is guaranteed to be from an interface. /// This parameter is used to optimize caching in <see cref="FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics"/>. /// </param> /// <returns>The implementing property or null, if there isn't one.</returns> private static Symbol ComputeImplementationForInterfaceMember(Symbol interfaceMember, TypeSymbol implementingType, BindingDiagnosticBag diagnostics, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMember.Kind == SymbolKind.Method || interfaceMember.Kind == SymbolKind.Property || interfaceMember.Kind == SymbolKind.Event); Debug.Assert(interfaceMember.IsImplementableInterfaceMember()); NamedTypeSymbol interfaceType = interfaceMember.ContainingType; Debug.Assert((object)interfaceType != null && interfaceType.IsInterface); bool seenTypeDeclaringInterface = false; // NOTE: In other areas of the compiler, we check whether the member is from a specific compilation. // We could do the same thing here, but that would mean that callers of the public API would have // to pass in a Compilation object when asking about interface implementation. This extra cost eliminates // the small benefit of getting identical answers from "imported" symbols, regardless of whether they // are imported as source or metadata symbols. // // ACASEY: As of 2013/01/24, we are not aware of any cases where the source and metadata behaviors // disagree *in code that can be emitted*. (If there are any, they are likely to involved ambiguous // overrides, which typically arise through combinations of ref/out and generics.) In incorrect code, // the source behavior is somewhat more generous (e.g. accepting a method with the wrong return type), // but we do not guarantee that incorrect source will be treated in the same way as incorrect metadata. // // NOTE: The batch compiler is not affected by this discrepancy, since compilations don't call these // APIs on symbols from other compilations. bool implementingTypeIsFromSomeCompilation = false; Symbol implicitImpl = null; Symbol closestMismatch = null; bool canBeImplementedImplicitlyInCSharp9 = interfaceMember.DeclaredAccessibility == Accessibility.Public && !interfaceMember.IsEventOrPropertyWithImplementableNonPublicAccessor(); TypeSymbol implementingBaseOpt = null; // Calculated only if canBeImplementedImplicitly == false bool implementingTypeImplementsInterface = false; CSharpCompilation compilation = implementingType.DeclaringCompilation; var useSiteInfo = compilation is object ? new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, compilation.Assembly) : CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies; for (TypeSymbol currType = implementingType; (object)currType != null; currType = currType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { // NOTE: In the case of PE symbols, it is possible to see an explicit implementation // on a type that does not declare the corresponding interface (or one of its // subinterfaces). In such cases, we want to return the explicit implementation, // even if it doesn't participate in interface mapping according to the C# rules. // pass 1: check for explicit impls (can't assume name matches) MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = currType.GetExplicitImplementationForInterfaceMember(interfaceMember); if (explicitImpl.Count == 1) { implementationInInterfacesMightChangeResult = false; return explicitImpl.Single(); } else if (explicitImpl.Count > 1) { if ((object)currType == implementingType || implementingTypeImplementsInterface) { diagnostics.Add(ErrorCode.ERR_DuplicateExplicitImpl, implementingType.Locations[0], interfaceMember); } implementationInInterfacesMightChangeResult = false; return null; } bool checkPendingExplicitImplementations = ((object)currType != implementingType || !currType.IsDefinition); if (checkPendingExplicitImplementations && interfaceMember is MethodSymbol interfaceMethod && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceMethod); if (bodyOfSynthesizedMethodImpl is object) { implementationInInterfacesMightChangeResult = false; return bodyOfSynthesizedMethodImpl; } } if (IsExplicitlyImplementedViaAccessors(checkPendingExplicitImplementations, interfaceMember, currType, ref useSiteInfo, out Symbol currTypeExplicitImpl)) { // We are looking for a property or event implementation and found an explicit implementation // for its accessor(s) in this type. Stop the process and return event/property associated // with the accessor(s), if any. implementationInInterfacesMightChangeResult = false; // NOTE: may be null. return currTypeExplicitImpl; } if (!seenTypeDeclaringInterface || (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null)) { if (currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { if (!seenTypeDeclaringInterface) { implementingTypeIsFromSomeCompilation = currType.OriginalDefinition.ContainingModule is not PEModuleSymbol; seenTypeDeclaringInterface = true; } if ((object)currType == implementingType) { implementingTypeImplementsInterface = true; } else if (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null) { implementingBaseOpt = currType; } } } // We want the implementation from the most derived type at or above the first one to // include the interface (or a subinterface) in its interface list if (seenTypeDeclaringInterface && (!interfaceMember.IsStatic || implementingTypeIsFromSomeCompilation)) { //pass 2: check for implicit impls (name must match) Symbol currTypeImplicitImpl; Symbol currTypeCloseMismatch; FindPotentialImplicitImplementationMemberDeclaredInType( interfaceMember, implementingTypeIsFromSomeCompilation, currType, out currTypeImplicitImpl, out currTypeCloseMismatch); if ((object)currTypeImplicitImpl != null) { implicitImpl = currTypeImplicitImpl; break; } if ((object)closestMismatch == null) { closestMismatch = currTypeCloseMismatch; } } } Debug.Assert(!canBeImplementedImplicitlyInCSharp9 || (object)implementingBaseOpt == null); bool tryDefaultInterfaceImplementation = !interfaceMember.IsStatic; // Dev10 has some extra restrictions and extra wiggle room when finding implicit // implementations for interface accessors. Perform some extra checks and possibly // update the result (i.e. implicitImpl). if (interfaceMember.IsAccessor()) { Symbol originalImplicitImpl = implicitImpl; CheckForImplementationOfCorrespondingPropertyOrEvent((MethodSymbol)interfaceMember, implementingType, implementingTypeIsFromSomeCompilation, ref implicitImpl); // If we discarded the candidate, we don't want default interface implementation to take over later, since runtime might still use the discarded candidate. if (originalImplicitImpl is object && implicitImpl is null) { tryDefaultInterfaceImplementation = false; } } Symbol defaultImpl = null; if ((object)implicitImpl == null && seenTypeDeclaringInterface && tryDefaultInterfaceImplementation) { if (ignoreImplementationInInterfaces) { implementationInInterfacesMightChangeResult = true; } else { // Check for default interface implementations defaultImpl = FindMostSpecificImplementationInInterfaces(interfaceMember, implementingType, ref useSiteInfo, diagnostics); implementationInInterfacesMightChangeResult = false; } } else { implementationInInterfacesMightChangeResult = false; } diagnostics.Add( #if !DEBUG // Don't optimize in DEBUG for better coverage for the GetInterfaceLocation function. useSiteInfo.Diagnostics is null || !implementingTypeImplementsInterface ? Location.None : #endif GetInterfaceLocation(interfaceMember, implementingType), useSiteInfo); if (defaultImpl is object) { if (implementingTypeImplementsInterface) { ReportDefaultInterfaceImplementationMatchDiagnostics(interfaceMember, implementingType, defaultImpl, diagnostics); } return defaultImpl; } if (implementingTypeImplementsInterface) { if ((object)implicitImpl != null) { if (!canBeImplementedImplicitlyInCSharp9) { if (interfaceMember.Kind == SymbolKind.Method && (object)implementingBaseOpt == null) // Otherwise any approprite errors are going to be reported for the base. { LanguageVersion requiredVersion = MessageID.IDS_FeatureImplicitImplementationOfNonPublicMembers.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, GetInterfaceLocation(interfaceMember, implementingType), implementingType, interfaceMember, implicitImpl, availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } } } ReportImplicitImplementationMatchDiagnostics(interfaceMember, implementingType, implicitImpl, diagnostics); } else if ((object)closestMismatch != null) { ReportImplicitImplementationMismatchDiagnostics(interfaceMember, implementingType, closestMismatch, diagnostics); } } return implicitImpl; } private static Symbol FindMostSpecificImplementationInInterfaces(Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, BindingDiagnosticBag diagnostics) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(!interfaceMember.IsStatic); // If we are dealing with a property or event and an implementation of at least one accessor is not from an interface, it // wouldn't be right to say that the event/property is implemented in an interface because its accessor isn't. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (stopLookup(interfaceAccessor1, implementingType) || stopLookup(interfaceAccessor2, implementingType)) { return null; } Symbol defaultImpl = FindMostSpecificImplementationInBases(interfaceMember, implementingType, ref useSiteInfo, out Symbol conflict1, out Symbol conflict2); if ((object)conflict1 != null) { Debug.Assert((object)defaultImpl == null); Debug.Assert((object)conflict2 != null); diagnostics.Add(ErrorCode.ERR_MostSpecificImplementationIsNotFound, GetInterfaceLocation(interfaceMember, implementingType), interfaceMember, conflict1, conflict2); } else { Debug.Assert(((object)conflict2 == null)); } return defaultImpl; static bool stopLookup(MethodSymbol interfaceAccessor, TypeSymbol implementingType) { if (interfaceAccessor is null) { return false; } SymbolAndDiagnostics symbolAndDiagnostics = implementingType.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceAccessor); if (symbolAndDiagnostics.Symbol is object) { return !symbolAndDiagnostics.Symbol.ContainingType.IsInterface; } // It is still possible that we actually looked for the accessor in interfaces, but failed due to an ambiguity. // Let's try to look for a property to improve diagnostics in this scenario. return !symbolAndDiagnostics.Diagnostics.Diagnostics.Any(d => d.Code == (int)ErrorCode.ERR_MostSpecificImplementationIsNotFound); } } private static Symbol FindMostSpecificImplementation(Symbol interfaceMember, NamedTypeSymbol implementingInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 0: (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); // If interface actually implements an event or property accessor, but doesn't implement the event/property, // do not look for its implementation in bases. if ((interfaceAccessor1 is object && FindImplementationInInterface(interfaceAccessor1, implementingInterface).Count != 0) || (interfaceAccessor2 is object && FindImplementationInInterface(interfaceAccessor2, implementingInterface).Count != 0)) { return null; } return FindMostSpecificImplementationInBases(interfaceMember, implementingInterface, ref useSiteInfo, out var _, out var _); case 1: { Symbol result = implementingMember.Single(); if (result.IsAbstract) { return null; } return result; } default: return null; } } /// <summary> /// One implementation M1 is considered more specific than another implementation M2 /// if M1 is declared on interface T1, M2 is declared on interface T2, and /// T1 contains T2 among its direct or indirect interfaces. /// </summary> private static Symbol FindMostSpecificImplementationInBases( Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { ImmutableArray<NamedTypeSymbol> allInterfaces = implementingType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); if (allInterfaces.IsEmpty) { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } // Properties or events can be implemented in an unconventional manner, i.e. implementing accessors might not be tied to a property/event. // If we simply look for a more specific implementing property/event, we might find one with not most specific implementing accessors. // Returning a property/event like that would be incorrect because runtime will use most specific accessor, or it will fail because there will // be an ambiguity for the accessor implementation. // So, for events and properties we look for most specific implementation of corresponding accessors and then try to tie them back to // an event/property, if any. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (interfaceAccessor1 is null && interfaceAccessor2 is null) { return findMostSpecificImplementationInBases(interfaceMember, allInterfaces, ref useSiteInfo, out conflictingImplementation1, out conflictingImplementation2); } Symbol accessorImpl1 = findMostSpecificImplementationInBases(interfaceAccessor1 ?? interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation11, out Symbol conflictingAccessorImplementation12); if (accessorImpl1 is null && conflictingAccessorImplementation11 is null) // implementation of accessor is not found { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (interfaceAccessor1 is null || interfaceAccessor2 is null) { if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; } Symbol accessorImpl2 = findMostSpecificImplementationInBases(interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation21, out Symbol conflictingAccessorImplementation22); if ((accessorImpl2 is null && conflictingAccessorImplementation21 is null) || // implementation of accessor is not found (accessorImpl1 is null) != (accessorImpl2 is null)) // there is most specific implementation for one accessor and an ambiguous implementation for the other accessor. { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1, accessorImpl2); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11, conflictingAccessorImplementation21); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12, conflictingAccessorImplementation22); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { // One pair of conflicting accessors can be tied to an event/property, but the other cannot be tied to an event/property. // Dropping conflict information since it only affects diagnostic. conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; static Symbol findImplementationInInterface(Symbol interfaceMember, Symbol inplementingAccessor1, Symbol implementingAccessor2 = null) { NamedTypeSymbol implementingInterface = inplementingAccessor1.ContainingType; if (implementingAccessor2 is object && !implementingInterface.Equals(implementingAccessor2.ContainingType, TypeCompareKind.ConsiderEverything)) { // Implementing accessors are from different types, they cannot be tied to the same event/property. return null; } MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 1: return implementingMember.Single(); default: return null; } } static Symbol findMostSpecificImplementationInBases( Symbol interfaceMember, ImmutableArray<NamedTypeSymbol> allInterfaces, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { var implementations = ArrayBuilder<(MultiDictionary<Symbol, Symbol>.ValueSet MethodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> Bases)>.GetInstance(); foreach (var interfaceType in allInterfaces) { if (!interfaceType.IsInterface) { // this code is reachable in error situations continue; } MultiDictionary<Symbol, Symbol>.ValueSet candidate = FindImplementationInInterface(interfaceMember, interfaceType); if (candidate.Count == 0) { continue; } for (int i = 0; i < implementations.Count; i++) { (MultiDictionary<Symbol, Symbol>.ValueSet methodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases) = implementations[i]; Symbol previous = methodSet.First(); NamedTypeSymbol previousContainingType = previous.ContainingType; if (previousContainingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { // Last equivalent match wins implementations[i] = (candidate, bases); candidate = default; break; } if (bases == null) { Debug.Assert(implementations.Count == 1); bases = previousContainingType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); implementations[i] = (methodSet, bases); } if (bases.ContainsKey(interfaceType)) { // Previous candidate is more specific candidate = default; break; } } if (candidate.Count == 0) { continue; } if (implementations.Count != 0) { MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases = interfaceType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = implementations.Count - 1; i >= 0; i--) { if (bases.ContainsKey(implementations[i].MethodSet.First().ContainingType)) { // new candidate is more specific implementations.RemoveAt(i); } } implementations.Add((candidate, bases)); } else { implementations.Add((candidate, null)); } } Symbol result; switch (implementations.Count) { case 0: result = null; conflictingImplementation1 = null; conflictingImplementation2 = null; break; case 1: MultiDictionary<Symbol, Symbol>.ValueSet methodSet = implementations[0].MethodSet; switch (methodSet.Count) { case 1: result = methodSet.Single(); if (result.IsAbstract) { result = null; } break; default: result = null; break; } conflictingImplementation1 = null; conflictingImplementation2 = null; break; default: result = null; conflictingImplementation1 = implementations[0].MethodSet.First(); conflictingImplementation2 = implementations[1].MethodSet.First(); break; } implementations.Free(); return result; } } internal static MultiDictionary<Symbol, Symbol>.ValueSet FindImplementationInInterface(Symbol interfaceMember, NamedTypeSymbol interfaceType) { Debug.Assert(interfaceType.IsInterface); Debug.Assert(!interfaceMember.IsStatic); NamedTypeSymbol containingType = interfaceMember.ContainingType; if (containingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { if (!interfaceMember.IsAbstract) { if (!containingType.Equals(interfaceType, TypeCompareKind.ConsiderEverything)) { interfaceMember = interfaceMember.OriginalDefinition.SymbolAsMember(interfaceType); } return new MultiDictionary<Symbol, Symbol>.ValueSet(interfaceMember); } return default; } return interfaceType.GetExplicitImplementationForInterfaceMember(interfaceMember); } private static (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) GetImplementableAccessors(Symbol interfaceMember) { MethodSymbol interfaceAccessor1; MethodSymbol interfaceAccessor2; switch (interfaceMember.Kind) { case SymbolKind.Property: { PropertySymbol interfaceProperty = (PropertySymbol)interfaceMember; interfaceAccessor1 = interfaceProperty.GetMethod; interfaceAccessor2 = interfaceProperty.SetMethod; break; } case SymbolKind.Event: { EventSymbol interfaceEvent = (EventSymbol)interfaceMember; interfaceAccessor1 = interfaceEvent.AddMethod; interfaceAccessor2 = interfaceEvent.RemoveMethod; break; } default: { interfaceAccessor1 = null; interfaceAccessor2 = null; break; } } if (!interfaceAccessor1.IsImplementable()) { interfaceAccessor1 = null; } if (!interfaceAccessor2.IsImplementable()) { interfaceAccessor2 = null; } return (interfaceAccessor1, interfaceAccessor2); } /// <summary> /// Since dev11 didn't expose a symbol API, it had the luxury of being able to accept a base class's claim that /// it implements an interface. Roslyn, on the other hand, needs to be able to point to an implementing symbol /// for each interface member. /// /// DevDiv #718115 was triggered by some unusual metadata in a Microsoft reference assembly (Silverlight System.Windows.dll). /// The issue was that a type explicitly implemented the accessors of an interface event, but did not tie them together with /// an event declaration. To make matters worse, it declared its own protected event with the same name as the interface /// event (presumably to back the explicit implementation). As a result, when Roslyn was asked to find the implementing member /// for the interface event, it found the protected event and reported an appropriate diagnostic. What it should have done /// (and does do now) is recognize that no event associated with the accessors explicitly implementing the interface accessors /// and returned null. /// /// We resolved this issue by introducing a new step into the interface mapping algorithm: after failing to find an explicit /// implementation in a type, but before searching for an implicit implementation in that type, check for an explicit implementation /// of an associated accessor. If there is such an implementation, then immediately return the associated property or event, /// even if it is null. That is, never attempt to find an implicit implementation for an interface property or event with an /// explicitly implemented accessor. /// </summary> private static bool IsExplicitlyImplementedViaAccessors(bool checkPendingExplicitImplementations, Symbol interfaceMember, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol implementingMember) { (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); Symbol associated1; Symbol associated2; if (TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor1, currType, ref useSiteInfo, out associated1) | // NB: not || TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor2, currType, ref useSiteInfo, out associated2)) { // If there's more than one associated property/event, don't do anything special - just let the algorithm // fail in the usual way. if ((object)associated1 == null || (object)associated2 == null || associated1 == associated2) { implementingMember = associated1 ?? associated2; // In source, we should already have seen an explicit implementation for the interface property/event. // If we haven't then there is no implementation. We need this check to match dev11 in some edge cases // (e.g. IndexerTests.AmbiguousExplicitIndexerImplementation). Such cases already fail // to roundtrip correctly, so it's not important to check for a particular compilation. if ((object)implementingMember != null && implementingMember.OriginalDefinition.ContainingModule is not PEModuleSymbol && implementingMember.IsExplicitInterfaceImplementation()) { implementingMember = null; } } else { implementingMember = null; } return true; } implementingMember = null; return false; } private static bool TryGetExplicitImplementationAssociatedPropertyOrEvent(bool checkPendingExplicitImplementations, MethodSymbol interfaceAccessor, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol associated) { if ((object)interfaceAccessor != null) { // NB: uses a map that was built (and saved) when we checked for an explicit // implementation of the interface member. MultiDictionary<Symbol, Symbol>.ValueSet set = currType.GetExplicitImplementationForInterfaceMember(interfaceAccessor); if (set.Count == 1) { Symbol implementation = set.Single(); associated = implementation.Kind == SymbolKind.Method ? ((MethodSymbol)implementation).AssociatedSymbol : null; return true; } if (checkPendingExplicitImplementations && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceAccessor.ContainingType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceAccessor); if (bodyOfSynthesizedMethodImpl is object) { associated = bodyOfSynthesizedMethodImpl.AssociatedSymbol; return true; } } } associated = null; return false; } /// <summary> /// If we were looking for an accessor, then look for an accessor on the implementation of the /// corresponding interface property/event. If it is valid as an implementation (ignoring the name), /// then prefer it to our current result if: /// 1) our current result is null; or /// 2) our current result is on the same type. /// /// If there is no corresponding accessor on the implementation of the corresponding interface /// property/event and we found an accessor, then the accessor we found is invalid, so clear it. /// </summary> private static void CheckForImplementationOfCorrespondingPropertyOrEvent(MethodSymbol interfaceMethod, TypeSymbol implementingType, bool implementingTypeIsFromSomeCompilation, ref Symbol implicitImpl) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMethod.IsAccessor()); Symbol associatedInterfacePropertyOrEvent = interfaceMethod.AssociatedSymbol; // Do not make any adjustments based on presence of default interface implementation for the property or event. // We don't want an addition of default interface implementation to change an error situation to success for // scenarios where the default interface implementation wouldn't actually be used at runtime. // When we find an implicit implementation candidate, we don't want to not discard it if we would discard it when // default interface implementation was missing. Why would presence of default interface implementation suddenly // make the candidate suiatable to implement the interface? Also, if we discard the candidate, we don't want default interface // implementation to take over later, since runtime might still use the discarded candidate. // When we don't find any implicit implementation candidate, returning accessor of default interface implementation // doesn't actually help much because we would find it anyway (it is implemented explicitly). Symbol implementingPropertyOrEvent = implementingType.FindImplementationForInterfaceMemberInNonInterface(associatedInterfacePropertyOrEvent, ignoreImplementationInInterfacesIfResultIsNotReady: true); // NB: uses cache MethodSymbol correspondingImplementingAccessor = null; if ((object)implementingPropertyOrEvent != null && !implementingPropertyOrEvent.ContainingType.IsInterface) { switch (interfaceMethod.MethodKind) { case MethodKind.PropertyGet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedGetMethod(); break; case MethodKind.PropertySet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedSetMethod(); break; case MethodKind.EventAdd: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedAddMethod(); break; case MethodKind.EventRemove: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedRemoveMethod(); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMethod.MethodKind); } } if (correspondingImplementingAccessor == implicitImpl) { return; } else if ((object)correspondingImplementingAccessor == null && (object)implicitImpl != null && implicitImpl.IsAccessor()) { // If we found an accessor, but it's not (directly or indirectly) on the property implementation, // then it's not a valid match. implicitImpl = null; } else if ((object)correspondingImplementingAccessor != null && ((object)implicitImpl == null || TypeSymbol.Equals(correspondingImplementingAccessor.ContainingType, implicitImpl.ContainingType, TypeCompareKind.ConsiderEverything2))) { // Suppose the interface accessor and the implementing accessor have different names. // In Dev10, as long as the corresponding properties have an implementation relationship, // then the accessor can be considered an implementation, even though the name is different. // Later on, when we check that implementation signatures match exactly // (in SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation), // they won't (because of the names) and an explicit implementation method will be synthesized. MethodSymbol interfaceAccessorWithImplementationName = new SignatureOnlyMethodSymbol( correspondingImplementingAccessor.Name, interfaceMethod.ContainingType, interfaceMethod.MethodKind, interfaceMethod.CallingConvention, interfaceMethod.TypeParameters, interfaceMethod.Parameters, interfaceMethod.RefKind, interfaceMethod.IsInitOnly, interfaceMethod.IsStatic, interfaceMethod.ReturnTypeWithAnnotations, interfaceMethod.RefCustomModifiers, interfaceMethod.ExplicitInterfaceImplementations); // Make sure that the corresponding accessor is a real implementation. if (IsInterfaceMemberImplementation(correspondingImplementingAccessor, interfaceAccessorWithImplementationName, implementingTypeIsFromSomeCompilation)) { implicitImpl = correspondingImplementingAccessor; } } } private static void ReportDefaultInterfaceImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { if (interfaceMember.Kind == SymbolKind.Method && implementingType.ContainingModule != implicitImpl.ContainingModule) { // The default implementation is coming from a different module, which means that we probably didn't check // for the required runtime capability or language version LanguageVersion requiredVersion = MessageID.IDS_DefaultInterfaceImplementation.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType, MessageID.IDS_DefaultInterfaceImplementation.Localize(), availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } if (!implementingType.ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } } /// <summary> /// These diagnostics are for members that do implicitly implement an interface member, but do so /// in an undesirable way. /// </summary> private static void ReportImplicitImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { bool reportedAnError = false; if (interfaceMember.Kind == SymbolKind.Method) { var interfaceMethod = (MethodSymbol)interfaceMember; bool implicitImplIsAccessor = implicitImpl.IsAccessor(); bool interfaceMethodIsAccessor = interfaceMethod.IsAccessor(); if (interfaceMethodIsAccessor && !implicitImplIsAccessor && !interfaceMethod.IsIndexedPropertyAccessor()) { diagnostics.Add(ErrorCode.ERR_MethodImplementingAccessor, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (!interfaceMethodIsAccessor && implicitImplIsAccessor) { diagnostics.Add(ErrorCode.ERR_AccessorImplementingMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else { var implicitImplMethod = (MethodSymbol)implicitImpl; if (implicitImplMethod.IsConditional) { // CS0629: Conditional member '{0}' cannot implement interface member '{1}' in type '{2}' diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByConditional, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (implicitImplMethod.IsStatic && implicitImplMethod.MethodKind == MethodKind.Ordinary && implicitImplMethod.GetUnmanagedCallersOnlyAttributeData(forceComplete: true) is not null) { diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (ReportAnyMismatchedConstraints(interfaceMethod, implementingType, implicitImplMethod, diagnostics)) { reportedAnError = true; } } } if (implicitImpl.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(implicitImpl, interfaceMember)) { // it is ok to implement implicitly with no tuple names, for compatibility with C# 6, but otherwise names should match diagnostics.Add(ErrorCode.ERR_ImplBadTupleNames, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMember); reportedAnError = true; } if (!reportedAnError && implementingType.DeclaringCompilation != null) { CheckNullableReferenceTypeMismatchOnImplementingMember(implementingType, implicitImpl, interfaceMember, isExplicit: false, diagnostics); } // In constructed types, it is possible to see multiple members with the same (runtime) signature. // Now that we know which member will implement the interface member, confirm that it is the only // such member. if (!implicitImpl.ContainingType.IsDefinition) { foreach (Symbol member in implicitImpl.ContainingType.GetMembers(implicitImpl.Name)) { if (member.DeclaredAccessibility != Accessibility.Public || member.IsStatic || member == implicitImpl) { //do nothing - not an ambiguous implementation } else if (MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, member) && !member.IsAccessor()) { // CONSIDER: Dev10 does not seem to report this for indexers or their accessors. diagnostics.Add(ErrorCode.WRN_MultipleRuntimeImplementationMatches, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, member), member, interfaceMember, implementingType); } } } if (implicitImpl.IsStatic && !implementingType.ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } internal static void CheckNullableReferenceTypeMismatchOnImplementingMember(TypeSymbol implementingType, Symbol implementingMember, Symbol interfaceMember, bool isExplicit, BindingDiagnosticBag diagnostics) { if (!implementingMember.IsImplicitlyDeclared && !implementingMember.IsAccessor()) { CSharpCompilation compilation = implementingType.DeclaringCompilation; if (interfaceMember.Kind == SymbolKind.Event) { var implementingEvent = (EventSymbol)implementingMember; var implementedEvent = (EventSymbol)interfaceMember; SourceMemberContainerTypeSymbol.CheckValidNullableEventOverride(compilation, implementedEvent, implementingEvent, diagnostics, (diagnostics, implementedEvent, implementingEvent, arg) => { if (arg.isExplicit) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, implementingEvent.Locations[0], new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedEvent, arg.implementingType, implementingEvent), new FormattedSymbol(implementingEvent, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }, (implementingType, isExplicit)); } else { ReportMismatchInReturnType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInReturnType = (diagnostics, implementedMethod, implementingMethod, topLevel, arg) => { if (arg.isExplicit) { // We use ConstructedFrom symbols here and below to not leak methods with Ignored annotations in type arguments // into diagnostics diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; ReportMismatchInParameterType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInParameterType = (diagnostics, implementedMethod, implementingMethod, implementingParameter, topLevel, arg) => { if (arg.isExplicit) { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; switch (interfaceMember.Kind) { case SymbolKind.Property: var implementingProperty = (PropertySymbol)implementingMember; var implementedProperty = (PropertySymbol)interfaceMember; if (implementedProperty.GetMethod.IsImplementable()) { MethodSymbol implementingGetMethod = implementingProperty.GetOwnOrInheritedGetMethod(); SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.GetMethod, implementingGetMethod, diagnostics, reportMismatchInReturnType, // Don't check parameters on the getter if there is a setter // because they will be a subset of the setter (!implementedProperty.SetMethod.IsImplementable() || implementingGetMethod?.AssociatedSymbol != implementingProperty || implementingProperty.GetOwnOrInheritedSetMethod()?.AssociatedSymbol != implementingProperty) ? reportMismatchInParameterType : null, (implementingType, isExplicit)); } if (implementedProperty.SetMethod.IsImplementable()) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.SetMethod, implementingProperty.GetOwnOrInheritedSetMethod(), diagnostics, null, reportMismatchInParameterType, (implementingType, isExplicit)); } break; case SymbolKind.Method: var implementingMethod = (MethodSymbol)implementingMember; var implementedMethod = (MethodSymbol)interfaceMember; if (implementedMethod.IsGenericMethod) { implementedMethod = implementedMethod.Construct(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementingMethod.TypeParameters)); } SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedMethod, implementingMethod, diagnostics, reportMismatchInReturnType, reportMismatchInParameterType, (implementingType, isExplicit)); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } } } } /// <summary> /// These diagnostics are for members that almost, but not actually, implicitly implement an interface member. /// </summary> private static void ReportImplicitImplementationMismatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol closestMismatch, BindingDiagnosticBag diagnostics) { // Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. Location interfaceLocation = GetInterfaceLocation(interfaceMember, implementingType); if (closestMismatch.IsStatic != interfaceMember.IsStatic) { diagnostics.Add(closestMismatch.IsStatic ? ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (closestMismatch.DeclaredAccessibility != Accessibility.Public) { ErrorCode errorCode = interfaceMember.IsAccessor() ? ErrorCode.ERR_UnimplementedInterfaceAccessor : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic; diagnostics.Add(errorCode, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (HaveInitOnlyMismatch(interfaceMember, closestMismatch)) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else //return ref kind or type doesn't match { RefKind interfaceMemberRefKind = RefKind.None; TypeSymbol interfaceMemberReturnType; switch (interfaceMember.Kind) { case SymbolKind.Method: var method = (MethodSymbol)interfaceMember; interfaceMemberRefKind = method.RefKind; interfaceMemberReturnType = method.ReturnType; break; case SymbolKind.Property: var property = (PropertySymbol)interfaceMember; interfaceMemberRefKind = property.RefKind; interfaceMemberReturnType = property.Type; break; case SymbolKind.Event: interfaceMemberReturnType = ((EventSymbol)interfaceMember).Type; break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } bool hasRefReturnMismatch = false; switch (closestMismatch.Kind) { case SymbolKind.Method: hasRefReturnMismatch = ((MethodSymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; case SymbolKind.Property: hasRefReturnMismatch = ((PropertySymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; } DiagnosticInfo useSiteDiagnostic; if ((object)interfaceMemberReturnType != null && (useSiteDiagnostic = interfaceMemberReturnType.GetUseSiteInfo().DiagnosticInfo) != null && useSiteDiagnostic.DefaultSeverity == DiagnosticSeverity.Error) { diagnostics.Add(useSiteDiagnostic, interfaceLocation); } else if (hasRefReturnMismatch) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, interfaceLocation, implementingType, interfaceMember, closestMismatch, interfaceMemberReturnType); } } } internal static bool HaveInitOnlyMismatch(Symbol one, Symbol other) { if (!(one is MethodSymbol oneMethod)) { return false; } if (!(other is MethodSymbol otherMethod)) { return false; } return oneMethod.IsInitOnly != otherMethod.IsInitOnly; } /// <summary> /// Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. /// </summary> private static Location GetInterfaceLocation(Symbol interfaceMember, TypeSymbol implementingType) { Debug.Assert((object)implementingType != null); var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = null; if (implementingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[@interface].Contains(@interface)) { snt = implementingType as SourceMemberContainerTypeSymbol; } return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations.FirstOrNone(); } private static bool ReportAnyMismatchedConstraints(MethodSymbol interfaceMethod, TypeSymbol implementingType, MethodSymbol implicitImpl, BindingDiagnosticBag diagnostics) { Debug.Assert(interfaceMethod.Arity == implicitImpl.Arity); bool result = false; var arity = interfaceMethod.Arity; if (arity > 0) { var typeParameters1 = interfaceMethod.TypeParameters; var typeParameters2 = implicitImpl.TypeParameters; var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true); var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true); // Report any mismatched method constraints. for (int i = 0; i < arity; i++) { var typeParameter1 = typeParameters1[i]; var typeParameter2 = typeParameters2[i]; if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { // If the matching method for the interface member is defined on the implementing type, // the matching method location is used for the error. Otherwise, the location of the // implementing type is used. (This differs from Dev10 which associates the error with // the closest method always. That behavior can be confusing though, since in the case // of "interface I { M; } class A { M; } class B : A, I { }", this means reporting an error on // A.M that it does not satisfy I.M even though A does not implement I. Furthermore if // A is defined in metadata, there is no location for A.M. Instead, we simply report the // error on B if the match to I.M is in a base class.) diagnostics.Add(ErrorCode.ERR_ImplBadConstraints, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } } } return result; } internal static Location GetImplicitImplementationDiagnosticLocation(Symbol interfaceMember, TypeSymbol implementingType, Symbol member) { if (TypeSymbol.Equals(member.ContainingType, implementingType, TypeCompareKind.ConsiderEverything2)) { return member.Locations[0]; } else { var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = implementingType as SourceMemberContainerTypeSymbol; return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations[0]; } } /// <summary> /// Search the declared members of a type for one that could be an implementation /// of a given interface member (depending on interface declarations). /// </summary> /// <param name="interfaceMember">The interface member being implemented.</param> /// <param name="implementingTypeIsFromSomeCompilation">True if the implementing type is from some compilation (i.e. not from metadata).</param> /// <param name="currType">The type on which we are looking for a declared implementation of the interface member.</param> /// <param name="implicitImpl">A member on currType that could implement the interface, or null.</param> /// <param name="closeMismatch">A member on currType that could have been an attempt to implement the interface, or null.</param> /// <remarks> /// There is some similarity between this member and OverriddenOrHiddenMembersHelpers.FindOverriddenOrHiddenMembersInType. /// When making changes to this member, think about whether or not they should also be applied in MemberSymbol. /// One key difference is that custom modifiers are considered when looking up overridden members, but /// not when looking up implicit implementations. We're preserving this behavior from Dev10. /// </remarks> private static void FindPotentialImplicitImplementationMemberDeclaredInType( Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation, TypeSymbol currType, out Symbol implicitImpl, out Symbol closeMismatch) { implicitImpl = null; closeMismatch = null; bool? isOperator = null; if (interfaceMember is MethodSymbol interfaceMethod) { isOperator = interfaceMethod.MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion; } foreach (Symbol member in currType.GetMembers(interfaceMember.Name)) { if (member.Kind == interfaceMember.Kind) { if (isOperator.HasValue && (((MethodSymbol)member).MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion) != isOperator.GetValueOrDefault()) { continue; } if (IsInterfaceMemberImplementation(member, interfaceMember, implementingTypeIsFromSomeCompilation)) { implicitImpl = member; return; } // If we haven't found a match, do a weaker comparison that ignores static-ness, accessibility, and return type. else if ((object)closeMismatch == null && implementingTypeIsFromSomeCompilation) { // We can ignore custom modifiers here, because our goal is to improve the helpfulness // of an error we're already giving, rather than to generate a new error. if (MemberSignatureComparer.CSharpCloseImplicitImplementationComparer.Equals(interfaceMember, member)) { closeMismatch = member; } } } } } /// <summary> /// To implement an interface member, a candidate member must be public, non-static, and have /// the same signature. "Have the same signature" has a looser definition if the type implementing /// the interface is from source. /// </summary> /// <remarks> /// PROPERTIES: /// NOTE: we're not checking whether this property has at least the accessors /// declared in the interface. Dev10 considers it a match either way and, /// reports failure to implement accessors separately. /// /// If the implementing type (i.e. the type with the interface in its interface /// list) is in source, then we can ignore custom modifiers in/on the property /// type because they will be copied into the bridge property that explicitly /// implements the interface property (or they would be, if we created such /// a bridge property). Bridge *methods* (not properties) are inserted in /// SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. /// /// CONSIDER: The spec for interface mapping (13.4.4) could be interpreted to mean that this /// property is not an implementation unless it has an accessor for each accessor of the /// interface property. For now, we prefer to represent that case as having an implemented /// property and an unimplemented accessor because it makes finding accessor implementations /// much easier. If we decide that we want the API to report the property as unimplemented, /// then it might be appropriate to keep current result internally and just check the accessors /// before returning the value from the public API (similar to the way MethodSymbol.OverriddenMethod /// filters MethodSymbol.OverriddenOrHiddenMembers. /// </remarks> private static bool IsInterfaceMemberImplementation(Symbol candidateMember, Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation) { if (candidateMember.DeclaredAccessibility != Accessibility.Public || candidateMember.IsStatic != interfaceMember.IsStatic) { return false; } else if (HaveInitOnlyMismatch(candidateMember, interfaceMember)) { return false; } else if (implementingTypeIsFromSomeCompilation) { // We're specifically ignoring custom modifiers for source types because that's what Dev10 does. // Inexact matches are acceptable because we'll just generate bridge members - explicit implementations // with exact signatures that delegate to the inexact match. This happens automatically in // SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. return MemberSignatureComparer.CSharpImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } else { // NOTE: Dev10 seems to use the C# rules in this case as well, but it doesn't give diagnostics about // the failure of a metadata type to implement an interface so there's no problem with reporting the // CLI interpretation instead. For example, using this comparer might allow a member with a ref // parameter to implement a member with an out parameter - which Dev10 would not allow - but that's // okay because Dev10's behavior is not observable. return MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } } protected MultiDictionary<Symbol, Symbol>.ValueSet GetExplicitImplementationForInterfaceMember(Symbol interfaceMember) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return default; } if (info.explicitInterfaceImplementationMap == null) { Interlocked.CompareExchange(ref info.explicitInterfaceImplementationMap, MakeExplicitInterfaceImplementationMap(), null); } return info.explicitInterfaceImplementationMap[interfaceMember]; } private MultiDictionary<Symbol, Symbol> MakeExplicitInterfaceImplementationMap() { var map = new MultiDictionary<Symbol, Symbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach (var member in this.GetMembersUnordered()) { foreach (var interfaceMember in member.GetExplicitInterfaceImplementations()) { Debug.Assert(interfaceMember.Kind != SymbolKind.Method || (object)interfaceMember == ((MethodSymbol)interfaceMember).ConstructedFrom); map.Add(interfaceMember, member); } } return map; } #nullable enable /// <summary> /// If implementation of an interface method <paramref name="interfaceMethod"/> will be accompanied with /// a MethodImpl entry in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API, this method returns the "Body" part /// of the MethodImpl entry, i.e. the method that implements the <paramref name="interfaceMethod"/>. /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the result is the method that the language considers to implement the <paramref name="interfaceMethod"/>, /// rather than the forwarding method. In other words, it is the method that the forwarding method forwards to. /// </summary> /// <param name="interfaceMethod">The interface method that is going to be implemented by using synthesized MethodImpl entry.</param> /// <returns></returns> protected MethodSymbol? GetBodyOfSynthesizedInterfaceMethodImpl(MethodSymbol interfaceMethod) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return null; } if (info.synthesizedMethodImplMap == null) { Interlocked.CompareExchange(ref info.synthesizedMethodImplMap, makeSynthesizedMethodImplMap(), null); } if (info.synthesizedMethodImplMap.TryGetValue(interfaceMethod, out MethodSymbol? result)) { return result; } return null; ImmutableDictionary<MethodSymbol, MethodSymbol> makeSynthesizedMethodImplMap() { var map = ImmutableDictionary.CreateBuilder<MethodSymbol, MethodSymbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach ((MethodSymbol body, MethodSymbol implemented) in this.SynthesizedInterfaceMethodImpls()) { map.Add(implemented, body); } return map.ToImmutable(); } } /// <summary> /// Returns information about interface method implementations that will be accompanied with /// MethodImpl entries in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API. The "Body" is the method that /// implements the interface method "Implemented". /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the "Body" is the method that the language considers to implement the interface method, /// the "Implemented", rather than the forwarding method. In other words, it is the method that /// the forwarding method forwards to. /// </summary> internal abstract IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls(); #nullable disable protected class ExplicitInterfaceImplementationTargetMemberEqualityComparer : IEqualityComparer<Symbol> { public static readonly ExplicitInterfaceImplementationTargetMemberEqualityComparer Instance = new ExplicitInterfaceImplementationTargetMemberEqualityComparer(); private ExplicitInterfaceImplementationTargetMemberEqualityComparer() { } public bool Equals(Symbol x, Symbol y) { return x.OriginalDefinition == y.OriginalDefinition && x.ContainingType.Equals(y.ContainingType, TypeCompareKind.CLRSignatureCompareOptions); } public int GetHashCode(Symbol obj) { return obj.OriginalDefinition.GetHashCode(); } } #endregion Interface member checks #region Abstract base type checks /// <summary> /// The set of abstract members in declared in this type or declared in a base type and not overridden. /// </summary> internal ImmutableHashSet<Symbol> AbstractMembers { get { if (_lazyAbstractMembers == null) { Interlocked.CompareExchange(ref _lazyAbstractMembers, ComputeAbstractMembers(), null); } return _lazyAbstractMembers; } } private ImmutableHashSet<Symbol> ComputeAbstractMembers() { var abstractMembers = ImmutableHashSet.Create<Symbol>(); var overriddenMembers = ImmutableHashSet.Create<Symbol>(); foreach (var member in this.GetMembersUnordered()) { if (this.IsAbstract && member.IsAbstract && member.Kind != SymbolKind.NamedType) { abstractMembers = abstractMembers.Add(member); } Symbol overriddenMember = null; switch (member.Kind) { case SymbolKind.Method: { overriddenMember = ((MethodSymbol)member).OverriddenMethod; break; } case SymbolKind.Property: { overriddenMember = ((PropertySymbol)member).OverriddenProperty; break; } case SymbolKind.Event: { overriddenMember = ((EventSymbol)member).OverriddenEvent; break; } } if ((object)overriddenMember != null) { overriddenMembers = overriddenMembers.Add(overriddenMember); } } if ((object)this.BaseTypeNoUseSiteDiagnostics != null && this.BaseTypeNoUseSiteDiagnostics.IsAbstract) { foreach (var baseAbstractMember in this.BaseTypeNoUseSiteDiagnostics.AbstractMembers) { if (!overriddenMembers.Contains(baseAbstractMember)) { abstractMembers = abstractMembers.Add(baseAbstractMember); } } } return abstractMembers; } #endregion Abstract base type checks [Obsolete("Use TypeWithAnnotations.Is method.", true)] internal bool Equals(TypeWithAnnotations other) { throw ExceptionUtilities.Unreachable; } public static bool Equals(TypeSymbol left, TypeSymbol right, TypeCompareKind comparison) { if (left is null) { return right is null; } return left.Equals(right, comparison); } [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; internal ITypeSymbol GetITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { if (nullableAnnotation == DefaultNullableAnnotation) { return (ITypeSymbol)this.ISymbol; } return CreateITypeSymbol(nullableAnnotation); } internal CodeAnalysis.NullableAnnotation DefaultNullableAnnotation => NullableAnnotationExtensions.ToPublicAnnotation(this, NullableAnnotation.Oblivious); protected abstract ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation); TypeKind ITypeSymbolInternal.TypeKind => this.TypeKind; SpecialType ITypeSymbolInternal.SpecialType => this.SpecialType; bool ITypeSymbolInternal.IsReferenceType => this.IsReferenceType; bool ITypeSymbolInternal.IsValueType => this.IsValueType; ITypeSymbol ITypeSymbolInternal.GetITypeSymbol() { return GetITypeSymbol(DefaultNullableAnnotation); } internal abstract bool IsRecord { get; } internal abstract bool IsRecordStruct { 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; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; #pragma warning disable CS0660 namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A TypeSymbol is a base class for all the symbols that represent a type /// in C#. /// </summary> internal abstract partial class TypeSymbol : NamespaceOrTypeSymbol, ITypeSymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO (tomat): Consider changing this to an empty name. This name shouldn't ever leak to the user in error messages. internal const string ImplicitTypeName = "<invalid-global-code>"; // InterfaceInfo for a common case of a type not implementing anything directly or indirectly. private static readonly InterfaceInfo s_noInterfaces = new InterfaceInfo(); private ImmutableHashSet<Symbol> _lazyAbstractMembers; private InterfaceInfo _lazyInterfaceInfo; private class InterfaceInfo { // all directly implemented interfaces, their bases and all interfaces to the bases of the type recursively internal ImmutableArray<NamedTypeSymbol> allInterfaces; /// <summary> /// <see cref="TypeSymbol.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics"/> /// </summary> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> interfacesAndTheirBaseInterfaces; internal static readonly MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> EmptyInterfacesAndTheirBaseInterfaces = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(0, SymbolEqualityComparer.CLRSignature); // Key is implemented member (method, property, or event), value is implementing member (from the // perspective of this type). Don't allocate until someone needs it. private ConcurrentDictionary<Symbol, SymbolAndDiagnostics> _implementationForInterfaceMemberMap; public ConcurrentDictionary<Symbol, SymbolAndDiagnostics> ImplementationForInterfaceMemberMap { get { var map = _implementationForInterfaceMemberMap; if (map != null) { return map; } // PERF: Avoid over-allocation. In many cases, there's only 1 entry and we don't expect concurrent updates. map = new ConcurrentDictionary<Symbol, SymbolAndDiagnostics>(concurrencyLevel: 1, capacity: 1, comparer: SymbolEqualityComparer.ConsiderEverything); return Interlocked.CompareExchange(ref _implementationForInterfaceMemberMap, map, null) ?? map; } } /// <summary> /// key = interface method/property/event compared using <see cref="ExplicitInterfaceImplementationTargetMemberEqualityComparer"/>, /// value = explicitly implementing methods/properties/events declared on this type (normally a single value, multiple in case of /// an error). /// </summary> internal MultiDictionary<Symbol, Symbol> explicitInterfaceImplementationMap; #nullable enable internal ImmutableDictionary<MethodSymbol, MethodSymbol>? synthesizedMethodImplMap; #nullable disable internal bool IsDefaultValue() { return allInterfaces.IsDefault && interfacesAndTheirBaseInterfaces == null && _implementationForInterfaceMemberMap == null && explicitInterfaceImplementationMap == null && synthesizedMethodImplMap == null; } } private InterfaceInfo GetInterfaceInfo() { var info = _lazyInterfaceInfo; if (info != null) { Debug.Assert(info != s_noInterfaces || info.IsDefaultValue(), "default value was modified"); return info; } for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); if (!interfaces.IsEmpty) { // it looks like we or one of our bases implements something. info = new InterfaceInfo(); // NOTE: we are assigning lazyInterfaceInfo via interlocked not for correctness, // we just do not want to override an existing info that could be partially filled. return Interlocked.CompareExchange(ref _lazyInterfaceInfo, info, null) ?? info; } } // if we have got here it means neither we nor our bases implement anything _lazyInterfaceInfo = info = s_noInterfaces; return info; } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new TypeSymbol OriginalDefinition { get { return OriginalTypeSymbolDefinition; } } protected virtual TypeSymbol OriginalTypeSymbolDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalTypeSymbolDefinition; } } /// <summary> /// Gets the BaseType of this type. If the base type could not be determined, then /// an instance of ErrorType is returned. If this kind of type does not have a base type /// (for example, interfaces), null is returned. Also the special class System.Object /// always has a BaseType of null. /// </summary> internal abstract NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get; } internal NamedTypeSymbol BaseTypeWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } internal NamedTypeSymbol BaseTypeOriginalDefinition(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result = result.OriginalDefinition; result.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// Gets the set of interfaces that this type directly implements. This set does not include /// interfaces that are base interfaces of directly implemented interfaces. /// </summary> internal abstract ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null); /// <summary> /// The list of all interfaces of which this type is a declared subtype, excluding this type /// itself. This includes all declared base interfaces, all declared base interfaces of base /// types, and all declared base interfaces of those results (recursively). Each result /// appears exactly once in the list. This list is topologically sorted by the inheritance /// relationship: if interface type A extends interface type B, then A precedes B in the /// list. This is not quite the same as "all interfaces of which this type is a proper /// subtype" because it does not take into account variance: AllInterfaces for /// IEnumerable&lt;string&gt; will not include IEnumerable&lt;object&gt; /// </summary> internal ImmutableArray<NamedTypeSymbol> AllInterfacesNoUseSiteDiagnostics { get { return GetAllInterfaces(); } } internal ImmutableArray<NamedTypeSymbol> AllInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = AllInterfacesNoUseSiteDiagnostics; // Since bases affect content of AllInterfaces set, we need to make sure they all are good. var current = this; do { current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } while ((object)current != null); foreach (var iface in result) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// If this is a type parameter returns its effective base class, otherwise returns this type. /// </summary> internal TypeSymbol EffectiveTypeNoUseSiteDiagnostics { get { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClassNoUseSiteDiagnostics : this; } } internal TypeSymbol EffectiveType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClass(ref useSiteInfo) : this; } /// <summary> /// Returns true if this type derives from a given type. /// </summary> internal bool IsDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)type != null); Debug.Assert(!type.IsTypeParameter()); if ((object)this == (object)type) { return false; } var t = this.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)t != null) { if (type.Equals(t, comparison)) { return true; } t = t.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } /// <summary> /// Returns true if this type is equal or derives from a given type. /// </summary> internal bool IsEqualToOrDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.Equals(type, comparison) || this.IsDerivedFrom(type, comparison, ref useSiteInfo); } /// <summary> /// Determines if this type symbol represent the same type as another, according to the language /// semantics. /// </summary> /// <param name="t2">The other type.</param> /// <param name="compareKind"> /// What kind of comparison to use? /// You can ignore custom modifiers, ignore the distinction between object and dynamic, or ignore tuple element names differences. /// </param> /// <returns>True if the types are equivalent.</returns> internal virtual bool Equals(TypeSymbol t2, TypeCompareKind compareKind) { return ReferenceEquals(this, t2); } public sealed override bool Equals(Symbol other, TypeCompareKind compareKind) { var t2 = other as TypeSymbol; if (t2 is null) { return false; } return this.Equals(t2, compareKind); } /// <summary> /// We ignore custom modifiers, and the distinction between dynamic and object, when computing a type's hash code. /// </summary> /// <returns></returns> public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } protected virtual ImmutableArray<NamedTypeSymbol> GetAllInterfaces() { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return ImmutableArray<NamedTypeSymbol>.Empty; } if (info.allInterfaces.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref info.allInterfaces, MakeAllInterfaces()); } return info.allInterfaces; } /// Produce all implemented interfaces in topologically sorted order. We use /// TypeSymbol.Interfaces as the source of edge data, which has had cycles and infinitely /// long dependency cycles removed. Consequently, it is possible (and we do) use the /// simplest version of Tarjan's topological sorting algorithm. protected virtual ImmutableArray<NamedTypeSymbol> MakeAllInterfaces() { var result = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var visited = new HashSet<NamedTypeSymbol>(SymbolEqualityComparer.ConsiderEverything); for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); for (int i = interfaces.Length - 1; i >= 0; i--) { addAllInterfaces(interfaces[i], visited, result); } } result.ReverseContents(); return result.ToImmutableAndFree(); static void addAllInterfaces(NamedTypeSymbol @interface, HashSet<NamedTypeSymbol> visited, ArrayBuilder<NamedTypeSymbol> result) { if (visited.Add(@interface)) { ImmutableArray<NamedTypeSymbol> baseInterfaces = @interface.InterfacesNoUseSiteDiagnostics(); for (int i = baseInterfaces.Length - 1; i >= 0; i--) { var baseInterface = baseInterfaces[i]; addAllInterfaces(baseInterface, visited, result); } result.Add(@interface); } } } /// <summary> /// Gets the set of interfaces that this type directly implements, plus the base interfaces /// of all such types. Keys are compared using <see cref="SymbolEqualityComparer.CLRSignature"/>, /// values are distinct interfaces corresponding to the key, according to <see cref="TypeCompareKind.ConsiderEverything"/> rules. /// </summary> /// <remarks> /// CONSIDER: it probably isn't truly necessary to cache this. If space gets tight, consider /// alternative approaches (recompute every time, cache on the side, only store on some types, /// etc). /// </remarks> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics { get { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { Debug.Assert(InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces.IsEmpty); return InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces; } if (info.interfacesAndTheirBaseInterfaces == null) { Interlocked.CompareExchange(ref info.interfacesAndTheirBaseInterfaces, MakeInterfacesAndTheirBaseInterfaces(this.InterfacesNoUseSiteDiagnostics()), null); } return info.interfacesAndTheirBaseInterfaces; } } internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics; foreach (var iface in result.Keys) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } // Note: Unlike MakeAllInterfaces, this doesn't need to be virtual. It depends on // AllInterfaces for its implementation, so it will pick up all changes to MakeAllInterfaces // indirectly. private static MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> MakeInterfacesAndTheirBaseInterfaces(ImmutableArray<NamedTypeSymbol> declaredInterfaces) { var resultBuilder = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(declaredInterfaces.Length, SymbolEqualityComparer.CLRSignature, SymbolEqualityComparer.ConsiderEverything); foreach (var @interface in declaredInterfaces) { if (resultBuilder.Add(@interface, @interface)) { foreach (var baseInterface in @interface.AllInterfacesNoUseSiteDiagnostics) { resultBuilder.Add(baseInterface, baseInterface); } } } return resultBuilder; } /// <summary> /// Returns the corresponding symbol in this type or a base type that implements /// interfaceMember (either implicitly or explicitly), or null if no such symbol exists /// (which might be either because this type doesn't implement the container of /// interfaceMember, or this type doesn't supply a member that successfully implements /// interfaceMember). /// </summary> /// <param name="interfaceMember"> /// Must be a non-null interface property, method, or event. /// </param> public Symbol FindImplementationForInterfaceMember(Symbol interfaceMember) { if ((object)interfaceMember == null) { throw new ArgumentNullException(nameof(interfaceMember)); } if (!interfaceMember.IsImplementableInterfaceMember()) { return null; } if (this.IsInterfaceType()) { if (interfaceMember.IsStatic) { return null; } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return FindMostSpecificImplementation(interfaceMember, (NamedTypeSymbol)this, ref discardedUseSiteInfo); } return FindImplementationForInterfaceMemberInNonInterface(interfaceMember); } /// <summary> /// Returns true if this type is known to be a reference type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsReferenceType { get; } /// <summary> /// Returns true if this type is known to be a value type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsValueType { get; } // Only the compiler can create TypeSymbols. internal TypeSymbol() { } /// <summary> /// Gets the kind of this type. /// </summary> public abstract TypeKind TypeKind { get; } /// <summary> /// Gets corresponding special TypeId of this type. /// </summary> /// <remarks> /// Not preserved in types constructed from this one. /// </remarks> public virtual SpecialType SpecialType { get { return SpecialType.None; } } /// <summary> /// Gets corresponding primitive type code for this type declaration. /// </summary> internal Microsoft.Cci.PrimitiveTypeCode PrimitiveTypeCode => TypeKind switch { TypeKind.Pointer => Microsoft.Cci.PrimitiveTypeCode.Pointer, TypeKind.FunctionPointer => Microsoft.Cci.PrimitiveTypeCode.FunctionPointer, _ => SpecialTypes.GetTypeCode(SpecialType) }; #region Use-Site Diagnostics /// <summary> /// Return error code that has highest priority while calculating use site error for this symbol. /// </summary> protected override int HighestPriorityUseSiteError { get { return (int)ErrorCode.ERR_BogusType; } } public sealed override bool HasUnsupportedMetadata { get { DiagnosticInfo info = GetUseSiteInfo().DiagnosticInfo; return (object)info != null && info.Code == (int)ErrorCode.ERR_BogusType; } } internal abstract bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes); #endregion /// <summary> /// Is this a symbol for an anonymous type (including delegate). /// </summary> public virtual bool IsAnonymousType { get { return false; } } /// <summary> /// Is this a symbol for a Tuple. /// </summary> public virtual bool IsTupleType => false; /// <summary> /// True if the type represents a native integer. In C#, the types represented /// by language keywords 'nint' and 'nuint'. /// </summary> internal virtual bool IsNativeIntegerType => false; /// <summary> /// Verify if the given type is a tuple of a given cardinality, or can be used to back a tuple type /// with the given cardinality. /// </summary> internal bool IsTupleTypeOfCardinality(int targetCardinality) { if (IsTupleType) { return TupleElementTypesWithAnnotations.Length == targetCardinality; } return false; } /// <summary> /// If this symbol represents a tuple type, get the types of the tuple's elements. /// </summary> public virtual ImmutableArray<TypeWithAnnotations> TupleElementTypesWithAnnotations => default(ImmutableArray<TypeWithAnnotations>); /// <summary> /// If this symbol represents a tuple type, get the names of the tuple's elements. /// </summary> public virtual ImmutableArray<string> TupleElementNames => default(ImmutableArray<string>); /// <summary> /// If this symbol represents a tuple type, get the fields for the tuple's elements. /// Otherwise, returns default. /// </summary> public virtual ImmutableArray<FieldSymbol> TupleElements => default(ImmutableArray<FieldSymbol>); #nullable enable /// <summary> /// Is this type a managed type (false for everything but enum, pointer, and /// some struct types). /// </summary> /// <remarks> /// See Type::computeManagedType. /// </remarks> internal bool IsManagedType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => GetManagedKind(ref useSiteInfo) == ManagedKind.Managed; internal bool IsManagedTypeNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return IsManagedType(ref discardedUseSiteInfo); } } /// <summary> /// Indicates whether a type is managed or not (i.e. you can take a pointer to it). /// Contains additional cases to help implement FeatureNotAvailable diagnostics. /// </summary> internal abstract ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal ManagedKind ManagedKindNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return GetManagedKind(ref discardedUseSiteInfo); } } #nullable disable internal bool NeedsNullableAttribute() { return TypeWithAnnotations.NeedsNullableAttribute(typeWithAnnotationsOpt: default, typeOpt: this); } internal abstract void AddNullableTransforms(ArrayBuilder<byte> transforms); internal abstract bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result); internal abstract TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform); internal TypeSymbol SetUnknownNullabilityForReferenceTypes() { return SetNullabilityForReferenceTypes(s_setUnknownNullability); } private static readonly Func<TypeWithAnnotations, TypeWithAnnotations> s_setUnknownNullability = (type) => type.SetUnknownNullabilityForReferenceTypes(); /// <summary> /// Merges features of the type with another type where there is an identity conversion between them. /// The features to be merged are /// object vs dynamic (dynamic wins), tuple names (dropped in case of conflict), and nullable /// annotations (e.g. in type arguments). /// </summary> internal abstract TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance); /// <summary> /// Returns true if the type may contain embedded references /// </summary> public abstract bool IsRefLikeType { get; } /// <summary> /// Returns true if the type is a readonly struct /// </summary> public abstract bool IsReadOnly { get; } public string ToDisplayString(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayString((ITypeSymbol)ISymbol, topLevelNullability, format); } public ImmutableArray<SymbolDisplayPart> ToDisplayParts(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, format); } public string ToMinimalDisplayString( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayString((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } #region Interface member checks /// <summary> /// Locate implementation of the <paramref name="interfaceMember"/> in context of the current type. /// The method is using cache to optimize subsequent calls for the same <paramref name="interfaceMember"/>. /// </summary> /// <param name="interfaceMember">Member for which an implementation should be found.</param> /// <param name="ignoreImplementationInInterfacesIfResultIsNotReady"> /// The process of looking up an implementation for an accessor can involve figuring out how corresponding event/property is implemented, /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. And the process of looking up an implementation for a property can /// involve figuring out how corresponding accessors are implemented, <see cref="FindMostSpecificImplementationInInterfaces"/>. This can /// lead to cycles, which could be avoided if we ignore the presence of implementations in interfaces for the purpose of /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. Fortunately, logic in it allows us to ignore the presence of /// implementations in interfaces and we use that. /// When the value of this parameter is true and the result that takes presence of implementations in interfaces into account is not /// available from the cache, the lookup will be performed ignoring the presence of implementations in interfaces. Otherwise, result from /// the cache is returned. /// When the value of the parameter is false, the result from the cache is returned, or calculated, taking presence of implementations /// in interfaces into account and then cached. /// This means that: /// - A symbol from an interface can still be returned even when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. /// A subsequent call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If symbol from a non-interface is returned when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. A subsequent /// call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If no symbol is returned for <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> true. A subsequent call with /// <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> might return a symbol, but that symbol guaranteed to be from an interface. /// - If the first request is done with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false. A subsequent call /// is guaranteed to return the same result regardless of <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> value. /// </param> internal SymbolAndDiagnostics FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { Debug.Assert((object)interfaceMember != null); Debug.Assert(!this.IsInterfaceType()); if (this.IsInterfaceType()) { return SymbolAndDiagnostics.Empty; } var interfaceType = interfaceMember.ContainingType; if ((object)interfaceType == null || !interfaceType.IsInterface) { return SymbolAndDiagnostics.Empty; } switch (interfaceMember.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return SymbolAndDiagnostics.Empty; } // PERF: Avoid delegate allocation by splitting GetOrAdd into TryGetValue+TryAdd var map = info.ImplementationForInterfaceMemberMap; SymbolAndDiagnostics result; if (map.TryGetValue(interfaceMember, out result)) { return result; } result = ComputeImplementationAndDiagnosticsForInterfaceMember(interfaceMember, ignoreImplementationInInterfaces: ignoreImplementationInInterfacesIfResultIsNotReady, out bool implementationInInterfacesMightChangeResult); Debug.Assert(ignoreImplementationInInterfacesIfResultIsNotReady || !implementationInInterfacesMightChangeResult); Debug.Assert(!implementationInInterfacesMightChangeResult || result.Symbol is null); if (!implementationInInterfacesMightChangeResult) { map.TryAdd(interfaceMember, result); } return result; default: return SymbolAndDiagnostics.Empty; } } internal Symbol FindImplementationForInterfaceMemberInNonInterface(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { return FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMember, ignoreImplementationInInterfacesIfResultIsNotReady).Symbol; } private SymbolAndDiagnostics ComputeImplementationAndDiagnosticsForInterfaceMember(Symbol interfaceMember, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: this.DeclaringCompilation is object); var implementingMember = ComputeImplementationForInterfaceMember(interfaceMember, this, diagnostics, ignoreImplementationInInterfaces, out implementationInInterfacesMightChangeResult); var implementingMemberAndDiagnostics = new SymbolAndDiagnostics(implementingMember, diagnostics.ToReadOnlyAndFree()); return implementingMemberAndDiagnostics; } /// <summary> /// Performs interface mapping (spec 13.4.4). /// </summary> /// <remarks> /// CONSIDER: we could probably do less work in the metadata and retargeting cases - we won't use the diagnostics. /// </remarks> /// <param name="interfaceMember">A non-null implementable member on an interface type.</param> /// <param name="implementingType">The type implementing the interface property (usually "this").</param> /// <param name="diagnostics">Bag to which to add diagnostics.</param> /// <param name="ignoreImplementationInInterfaces">Do not consider implementation in an interface as a valid candidate for the purpose of this computation.</param> /// <param name="implementationInInterfacesMightChangeResult"> /// Returns true when <paramref name="ignoreImplementationInInterfaces"/> is true, the method fails to locate an implementation and an implementation in /// an interface, if any (its presence is not checked), could potentially be a candidate. Returns false otherwise. /// When true is returned, a different call with <paramref name="ignoreImplementationInInterfaces"/> false might return a symbol. That symbol, if any, /// is guaranteed to be from an interface. /// This parameter is used to optimize caching in <see cref="FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics"/>. /// </param> /// <returns>The implementing property or null, if there isn't one.</returns> private static Symbol ComputeImplementationForInterfaceMember(Symbol interfaceMember, TypeSymbol implementingType, BindingDiagnosticBag diagnostics, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMember.Kind == SymbolKind.Method || interfaceMember.Kind == SymbolKind.Property || interfaceMember.Kind == SymbolKind.Event); Debug.Assert(interfaceMember.IsImplementableInterfaceMember()); NamedTypeSymbol interfaceType = interfaceMember.ContainingType; Debug.Assert((object)interfaceType != null && interfaceType.IsInterface); bool seenTypeDeclaringInterface = false; // NOTE: In other areas of the compiler, we check whether the member is from a specific compilation. // We could do the same thing here, but that would mean that callers of the public API would have // to pass in a Compilation object when asking about interface implementation. This extra cost eliminates // the small benefit of getting identical answers from "imported" symbols, regardless of whether they // are imported as source or metadata symbols. // // ACASEY: As of 2013/01/24, we are not aware of any cases where the source and metadata behaviors // disagree *in code that can be emitted*. (If there are any, they are likely to involved ambiguous // overrides, which typically arise through combinations of ref/out and generics.) In incorrect code, // the source behavior is somewhat more generous (e.g. accepting a method with the wrong return type), // but we do not guarantee that incorrect source will be treated in the same way as incorrect metadata. // // NOTE: The batch compiler is not affected by this discrepancy, since compilations don't call these // APIs on symbols from other compilations. bool implementingTypeIsFromSomeCompilation = false; Symbol implicitImpl = null; Symbol closestMismatch = null; bool canBeImplementedImplicitlyInCSharp9 = interfaceMember.DeclaredAccessibility == Accessibility.Public && !interfaceMember.IsEventOrPropertyWithImplementableNonPublicAccessor(); TypeSymbol implementingBaseOpt = null; // Calculated only if canBeImplementedImplicitly == false bool implementingTypeImplementsInterface = false; CSharpCompilation compilation = implementingType.DeclaringCompilation; var useSiteInfo = compilation is object ? new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, compilation.Assembly) : CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies; for (TypeSymbol currType = implementingType; (object)currType != null; currType = currType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { // NOTE: In the case of PE symbols, it is possible to see an explicit implementation // on a type that does not declare the corresponding interface (or one of its // subinterfaces). In such cases, we want to return the explicit implementation, // even if it doesn't participate in interface mapping according to the C# rules. // pass 1: check for explicit impls (can't assume name matches) MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = currType.GetExplicitImplementationForInterfaceMember(interfaceMember); if (explicitImpl.Count == 1) { implementationInInterfacesMightChangeResult = false; return explicitImpl.Single(); } else if (explicitImpl.Count > 1) { if ((object)currType == implementingType || implementingTypeImplementsInterface) { diagnostics.Add(ErrorCode.ERR_DuplicateExplicitImpl, implementingType.Locations[0], interfaceMember); } implementationInInterfacesMightChangeResult = false; return null; } bool checkPendingExplicitImplementations = ((object)currType != implementingType || !currType.IsDefinition); if (checkPendingExplicitImplementations && interfaceMember is MethodSymbol interfaceMethod && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceMethod); if (bodyOfSynthesizedMethodImpl is object) { implementationInInterfacesMightChangeResult = false; return bodyOfSynthesizedMethodImpl; } } if (IsExplicitlyImplementedViaAccessors(checkPendingExplicitImplementations, interfaceMember, currType, ref useSiteInfo, out Symbol currTypeExplicitImpl)) { // We are looking for a property or event implementation and found an explicit implementation // for its accessor(s) in this type. Stop the process and return event/property associated // with the accessor(s), if any. implementationInInterfacesMightChangeResult = false; // NOTE: may be null. return currTypeExplicitImpl; } if (!seenTypeDeclaringInterface || (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null)) { if (currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { if (!seenTypeDeclaringInterface) { implementingTypeIsFromSomeCompilation = currType.OriginalDefinition.ContainingModule is not PEModuleSymbol; seenTypeDeclaringInterface = true; } if ((object)currType == implementingType) { implementingTypeImplementsInterface = true; } else if (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null) { implementingBaseOpt = currType; } } } // We want the implementation from the most derived type at or above the first one to // include the interface (or a subinterface) in its interface list if (seenTypeDeclaringInterface && (!interfaceMember.IsStatic || implementingTypeIsFromSomeCompilation)) { //pass 2: check for implicit impls (name must match) Symbol currTypeImplicitImpl; Symbol currTypeCloseMismatch; FindPotentialImplicitImplementationMemberDeclaredInType( interfaceMember, implementingTypeIsFromSomeCompilation, currType, out currTypeImplicitImpl, out currTypeCloseMismatch); if ((object)currTypeImplicitImpl != null) { implicitImpl = currTypeImplicitImpl; break; } if ((object)closestMismatch == null) { closestMismatch = currTypeCloseMismatch; } } } Debug.Assert(!canBeImplementedImplicitlyInCSharp9 || (object)implementingBaseOpt == null); bool tryDefaultInterfaceImplementation = !interfaceMember.IsStatic; // Dev10 has some extra restrictions and extra wiggle room when finding implicit // implementations for interface accessors. Perform some extra checks and possibly // update the result (i.e. implicitImpl). if (interfaceMember.IsAccessor()) { Symbol originalImplicitImpl = implicitImpl; CheckForImplementationOfCorrespondingPropertyOrEvent((MethodSymbol)interfaceMember, implementingType, implementingTypeIsFromSomeCompilation, ref implicitImpl); // If we discarded the candidate, we don't want default interface implementation to take over later, since runtime might still use the discarded candidate. if (originalImplicitImpl is object && implicitImpl is null) { tryDefaultInterfaceImplementation = false; } } Symbol defaultImpl = null; if ((object)implicitImpl == null && seenTypeDeclaringInterface && tryDefaultInterfaceImplementation) { if (ignoreImplementationInInterfaces) { implementationInInterfacesMightChangeResult = true; } else { // Check for default interface implementations defaultImpl = FindMostSpecificImplementationInInterfaces(interfaceMember, implementingType, ref useSiteInfo, diagnostics); implementationInInterfacesMightChangeResult = false; } } else { implementationInInterfacesMightChangeResult = false; } diagnostics.Add( #if !DEBUG // Don't optimize in DEBUG for better coverage for the GetInterfaceLocation function. useSiteInfo.Diagnostics is null || !implementingTypeImplementsInterface ? Location.None : #endif GetInterfaceLocation(interfaceMember, implementingType), useSiteInfo); if (defaultImpl is object) { if (implementingTypeImplementsInterface) { ReportDefaultInterfaceImplementationMatchDiagnostics(interfaceMember, implementingType, defaultImpl, diagnostics); } return defaultImpl; } if (implementingTypeImplementsInterface) { if ((object)implicitImpl != null) { if (!canBeImplementedImplicitlyInCSharp9) { if (interfaceMember.Kind == SymbolKind.Method && (object)implementingBaseOpt == null) // Otherwise any approprite errors are going to be reported for the base. { LanguageVersion requiredVersion = MessageID.IDS_FeatureImplicitImplementationOfNonPublicMembers.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, GetInterfaceLocation(interfaceMember, implementingType), implementingType, interfaceMember, implicitImpl, availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } } } ReportImplicitImplementationMatchDiagnostics(interfaceMember, implementingType, implicitImpl, diagnostics); } else if ((object)closestMismatch != null) { ReportImplicitImplementationMismatchDiagnostics(interfaceMember, implementingType, closestMismatch, diagnostics); } } return implicitImpl; } private static Symbol FindMostSpecificImplementationInInterfaces(Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, BindingDiagnosticBag diagnostics) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(!interfaceMember.IsStatic); // If we are dealing with a property or event and an implementation of at least one accessor is not from an interface, it // wouldn't be right to say that the event/property is implemented in an interface because its accessor isn't. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (stopLookup(interfaceAccessor1, implementingType) || stopLookup(interfaceAccessor2, implementingType)) { return null; } Symbol defaultImpl = FindMostSpecificImplementationInBases(interfaceMember, implementingType, ref useSiteInfo, out Symbol conflict1, out Symbol conflict2); if ((object)conflict1 != null) { Debug.Assert((object)defaultImpl == null); Debug.Assert((object)conflict2 != null); diagnostics.Add(ErrorCode.ERR_MostSpecificImplementationIsNotFound, GetInterfaceLocation(interfaceMember, implementingType), interfaceMember, conflict1, conflict2); } else { Debug.Assert(((object)conflict2 == null)); } return defaultImpl; static bool stopLookup(MethodSymbol interfaceAccessor, TypeSymbol implementingType) { if (interfaceAccessor is null) { return false; } SymbolAndDiagnostics symbolAndDiagnostics = implementingType.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceAccessor); if (symbolAndDiagnostics.Symbol is object) { return !symbolAndDiagnostics.Symbol.ContainingType.IsInterface; } // It is still possible that we actually looked for the accessor in interfaces, but failed due to an ambiguity. // Let's try to look for a property to improve diagnostics in this scenario. return !symbolAndDiagnostics.Diagnostics.Diagnostics.Any(d => d.Code == (int)ErrorCode.ERR_MostSpecificImplementationIsNotFound); } } private static Symbol FindMostSpecificImplementation(Symbol interfaceMember, NamedTypeSymbol implementingInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 0: (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); // If interface actually implements an event or property accessor, but doesn't implement the event/property, // do not look for its implementation in bases. if ((interfaceAccessor1 is object && FindImplementationInInterface(interfaceAccessor1, implementingInterface).Count != 0) || (interfaceAccessor2 is object && FindImplementationInInterface(interfaceAccessor2, implementingInterface).Count != 0)) { return null; } return FindMostSpecificImplementationInBases(interfaceMember, implementingInterface, ref useSiteInfo, out var _, out var _); case 1: { Symbol result = implementingMember.Single(); if (result.IsAbstract) { return null; } return result; } default: return null; } } /// <summary> /// One implementation M1 is considered more specific than another implementation M2 /// if M1 is declared on interface T1, M2 is declared on interface T2, and /// T1 contains T2 among its direct or indirect interfaces. /// </summary> private static Symbol FindMostSpecificImplementationInBases( Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { ImmutableArray<NamedTypeSymbol> allInterfaces = implementingType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); if (allInterfaces.IsEmpty) { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } // Properties or events can be implemented in an unconventional manner, i.e. implementing accessors might not be tied to a property/event. // If we simply look for a more specific implementing property/event, we might find one with not most specific implementing accessors. // Returning a property/event like that would be incorrect because runtime will use most specific accessor, or it will fail because there will // be an ambiguity for the accessor implementation. // So, for events and properties we look for most specific implementation of corresponding accessors and then try to tie them back to // an event/property, if any. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (interfaceAccessor1 is null && interfaceAccessor2 is null) { return findMostSpecificImplementationInBases(interfaceMember, allInterfaces, ref useSiteInfo, out conflictingImplementation1, out conflictingImplementation2); } Symbol accessorImpl1 = findMostSpecificImplementationInBases(interfaceAccessor1 ?? interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation11, out Symbol conflictingAccessorImplementation12); if (accessorImpl1 is null && conflictingAccessorImplementation11 is null) // implementation of accessor is not found { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (interfaceAccessor1 is null || interfaceAccessor2 is null) { if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; } Symbol accessorImpl2 = findMostSpecificImplementationInBases(interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation21, out Symbol conflictingAccessorImplementation22); if ((accessorImpl2 is null && conflictingAccessorImplementation21 is null) || // implementation of accessor is not found (accessorImpl1 is null) != (accessorImpl2 is null)) // there is most specific implementation for one accessor and an ambiguous implementation for the other accessor. { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1, accessorImpl2); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11, conflictingAccessorImplementation21); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12, conflictingAccessorImplementation22); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { // One pair of conflicting accessors can be tied to an event/property, but the other cannot be tied to an event/property. // Dropping conflict information since it only affects diagnostic. conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; static Symbol findImplementationInInterface(Symbol interfaceMember, Symbol inplementingAccessor1, Symbol implementingAccessor2 = null) { NamedTypeSymbol implementingInterface = inplementingAccessor1.ContainingType; if (implementingAccessor2 is object && !implementingInterface.Equals(implementingAccessor2.ContainingType, TypeCompareKind.ConsiderEverything)) { // Implementing accessors are from different types, they cannot be tied to the same event/property. return null; } MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 1: return implementingMember.Single(); default: return null; } } static Symbol findMostSpecificImplementationInBases( Symbol interfaceMember, ImmutableArray<NamedTypeSymbol> allInterfaces, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { var implementations = ArrayBuilder<(MultiDictionary<Symbol, Symbol>.ValueSet MethodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> Bases)>.GetInstance(); foreach (var interfaceType in allInterfaces) { if (!interfaceType.IsInterface) { // this code is reachable in error situations continue; } MultiDictionary<Symbol, Symbol>.ValueSet candidate = FindImplementationInInterface(interfaceMember, interfaceType); if (candidate.Count == 0) { continue; } for (int i = 0; i < implementations.Count; i++) { (MultiDictionary<Symbol, Symbol>.ValueSet methodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases) = implementations[i]; Symbol previous = methodSet.First(); NamedTypeSymbol previousContainingType = previous.ContainingType; if (previousContainingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { // Last equivalent match wins implementations[i] = (candidate, bases); candidate = default; break; } if (bases == null) { Debug.Assert(implementations.Count == 1); bases = previousContainingType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); implementations[i] = (methodSet, bases); } if (bases.ContainsKey(interfaceType)) { // Previous candidate is more specific candidate = default; break; } } if (candidate.Count == 0) { continue; } if (implementations.Count != 0) { MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases = interfaceType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = implementations.Count - 1; i >= 0; i--) { if (bases.ContainsKey(implementations[i].MethodSet.First().ContainingType)) { // new candidate is more specific implementations.RemoveAt(i); } } implementations.Add((candidate, bases)); } else { implementations.Add((candidate, null)); } } Symbol result; switch (implementations.Count) { case 0: result = null; conflictingImplementation1 = null; conflictingImplementation2 = null; break; case 1: MultiDictionary<Symbol, Symbol>.ValueSet methodSet = implementations[0].MethodSet; switch (methodSet.Count) { case 1: result = methodSet.Single(); if (result.IsAbstract) { result = null; } break; default: result = null; break; } conflictingImplementation1 = null; conflictingImplementation2 = null; break; default: result = null; conflictingImplementation1 = implementations[0].MethodSet.First(); conflictingImplementation2 = implementations[1].MethodSet.First(); break; } implementations.Free(); return result; } } internal static MultiDictionary<Symbol, Symbol>.ValueSet FindImplementationInInterface(Symbol interfaceMember, NamedTypeSymbol interfaceType) { Debug.Assert(interfaceType.IsInterface); Debug.Assert(!interfaceMember.IsStatic); NamedTypeSymbol containingType = interfaceMember.ContainingType; if (containingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { if (!interfaceMember.IsAbstract) { if (!containingType.Equals(interfaceType, TypeCompareKind.ConsiderEverything)) { interfaceMember = interfaceMember.OriginalDefinition.SymbolAsMember(interfaceType); } return new MultiDictionary<Symbol, Symbol>.ValueSet(interfaceMember); } return default; } return interfaceType.GetExplicitImplementationForInterfaceMember(interfaceMember); } private static (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) GetImplementableAccessors(Symbol interfaceMember) { MethodSymbol interfaceAccessor1; MethodSymbol interfaceAccessor2; switch (interfaceMember.Kind) { case SymbolKind.Property: { PropertySymbol interfaceProperty = (PropertySymbol)interfaceMember; interfaceAccessor1 = interfaceProperty.GetMethod; interfaceAccessor2 = interfaceProperty.SetMethod; break; } case SymbolKind.Event: { EventSymbol interfaceEvent = (EventSymbol)interfaceMember; interfaceAccessor1 = interfaceEvent.AddMethod; interfaceAccessor2 = interfaceEvent.RemoveMethod; break; } default: { interfaceAccessor1 = null; interfaceAccessor2 = null; break; } } if (!interfaceAccessor1.IsImplementable()) { interfaceAccessor1 = null; } if (!interfaceAccessor2.IsImplementable()) { interfaceAccessor2 = null; } return (interfaceAccessor1, interfaceAccessor2); } /// <summary> /// Since dev11 didn't expose a symbol API, it had the luxury of being able to accept a base class's claim that /// it implements an interface. Roslyn, on the other hand, needs to be able to point to an implementing symbol /// for each interface member. /// /// DevDiv #718115 was triggered by some unusual metadata in a Microsoft reference assembly (Silverlight System.Windows.dll). /// The issue was that a type explicitly implemented the accessors of an interface event, but did not tie them together with /// an event declaration. To make matters worse, it declared its own protected event with the same name as the interface /// event (presumably to back the explicit implementation). As a result, when Roslyn was asked to find the implementing member /// for the interface event, it found the protected event and reported an appropriate diagnostic. What it should have done /// (and does do now) is recognize that no event associated with the accessors explicitly implementing the interface accessors /// and returned null. /// /// We resolved this issue by introducing a new step into the interface mapping algorithm: after failing to find an explicit /// implementation in a type, but before searching for an implicit implementation in that type, check for an explicit implementation /// of an associated accessor. If there is such an implementation, then immediately return the associated property or event, /// even if it is null. That is, never attempt to find an implicit implementation for an interface property or event with an /// explicitly implemented accessor. /// </summary> private static bool IsExplicitlyImplementedViaAccessors(bool checkPendingExplicitImplementations, Symbol interfaceMember, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol implementingMember) { (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); Symbol associated1; Symbol associated2; if (TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor1, currType, ref useSiteInfo, out associated1) | // NB: not || TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor2, currType, ref useSiteInfo, out associated2)) { // If there's more than one associated property/event, don't do anything special - just let the algorithm // fail in the usual way. if ((object)associated1 == null || (object)associated2 == null || associated1 == associated2) { implementingMember = associated1 ?? associated2; // In source, we should already have seen an explicit implementation for the interface property/event. // If we haven't then there is no implementation. We need this check to match dev11 in some edge cases // (e.g. IndexerTests.AmbiguousExplicitIndexerImplementation). Such cases already fail // to roundtrip correctly, so it's not important to check for a particular compilation. if ((object)implementingMember != null && implementingMember.OriginalDefinition.ContainingModule is not PEModuleSymbol && implementingMember.IsExplicitInterfaceImplementation()) { implementingMember = null; } } else { implementingMember = null; } return true; } implementingMember = null; return false; } private static bool TryGetExplicitImplementationAssociatedPropertyOrEvent(bool checkPendingExplicitImplementations, MethodSymbol interfaceAccessor, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol associated) { if ((object)interfaceAccessor != null) { // NB: uses a map that was built (and saved) when we checked for an explicit // implementation of the interface member. MultiDictionary<Symbol, Symbol>.ValueSet set = currType.GetExplicitImplementationForInterfaceMember(interfaceAccessor); if (set.Count == 1) { Symbol implementation = set.Single(); associated = implementation.Kind == SymbolKind.Method ? ((MethodSymbol)implementation).AssociatedSymbol : null; return true; } if (checkPendingExplicitImplementations && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceAccessor.ContainingType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceAccessor); if (bodyOfSynthesizedMethodImpl is object) { associated = bodyOfSynthesizedMethodImpl.AssociatedSymbol; return true; } } } associated = null; return false; } /// <summary> /// If we were looking for an accessor, then look for an accessor on the implementation of the /// corresponding interface property/event. If it is valid as an implementation (ignoring the name), /// then prefer it to our current result if: /// 1) our current result is null; or /// 2) our current result is on the same type. /// /// If there is no corresponding accessor on the implementation of the corresponding interface /// property/event and we found an accessor, then the accessor we found is invalid, so clear it. /// </summary> private static void CheckForImplementationOfCorrespondingPropertyOrEvent(MethodSymbol interfaceMethod, TypeSymbol implementingType, bool implementingTypeIsFromSomeCompilation, ref Symbol implicitImpl) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMethod.IsAccessor()); Symbol associatedInterfacePropertyOrEvent = interfaceMethod.AssociatedSymbol; // Do not make any adjustments based on presence of default interface implementation for the property or event. // We don't want an addition of default interface implementation to change an error situation to success for // scenarios where the default interface implementation wouldn't actually be used at runtime. // When we find an implicit implementation candidate, we don't want to not discard it if we would discard it when // default interface implementation was missing. Why would presence of default interface implementation suddenly // make the candidate suiatable to implement the interface? Also, if we discard the candidate, we don't want default interface // implementation to take over later, since runtime might still use the discarded candidate. // When we don't find any implicit implementation candidate, returning accessor of default interface implementation // doesn't actually help much because we would find it anyway (it is implemented explicitly). Symbol implementingPropertyOrEvent = implementingType.FindImplementationForInterfaceMemberInNonInterface(associatedInterfacePropertyOrEvent, ignoreImplementationInInterfacesIfResultIsNotReady: true); // NB: uses cache MethodSymbol correspondingImplementingAccessor = null; if ((object)implementingPropertyOrEvent != null && !implementingPropertyOrEvent.ContainingType.IsInterface) { switch (interfaceMethod.MethodKind) { case MethodKind.PropertyGet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedGetMethod(); break; case MethodKind.PropertySet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedSetMethod(); break; case MethodKind.EventAdd: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedAddMethod(); break; case MethodKind.EventRemove: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedRemoveMethod(); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMethod.MethodKind); } } if (correspondingImplementingAccessor == implicitImpl) { return; } else if ((object)correspondingImplementingAccessor == null && (object)implicitImpl != null && implicitImpl.IsAccessor()) { // If we found an accessor, but it's not (directly or indirectly) on the property implementation, // then it's not a valid match. implicitImpl = null; } else if ((object)correspondingImplementingAccessor != null && ((object)implicitImpl == null || TypeSymbol.Equals(correspondingImplementingAccessor.ContainingType, implicitImpl.ContainingType, TypeCompareKind.ConsiderEverything2))) { // Suppose the interface accessor and the implementing accessor have different names. // In Dev10, as long as the corresponding properties have an implementation relationship, // then the accessor can be considered an implementation, even though the name is different. // Later on, when we check that implementation signatures match exactly // (in SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation), // they won't (because of the names) and an explicit implementation method will be synthesized. MethodSymbol interfaceAccessorWithImplementationName = new SignatureOnlyMethodSymbol( correspondingImplementingAccessor.Name, interfaceMethod.ContainingType, interfaceMethod.MethodKind, interfaceMethod.CallingConvention, interfaceMethod.TypeParameters, interfaceMethod.Parameters, interfaceMethod.RefKind, interfaceMethod.IsInitOnly, interfaceMethod.IsStatic, interfaceMethod.ReturnTypeWithAnnotations, interfaceMethod.RefCustomModifiers, interfaceMethod.ExplicitInterfaceImplementations); // Make sure that the corresponding accessor is a real implementation. if (IsInterfaceMemberImplementation(correspondingImplementingAccessor, interfaceAccessorWithImplementationName, implementingTypeIsFromSomeCompilation)) { implicitImpl = correspondingImplementingAccessor; } } } private static void ReportDefaultInterfaceImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { if (interfaceMember.Kind == SymbolKind.Method && implementingType.ContainingModule != implicitImpl.ContainingModule) { // The default implementation is coming from a different module, which means that we probably didn't check // for the required runtime capability or language version LanguageVersion requiredVersion = MessageID.IDS_DefaultInterfaceImplementation.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType, MessageID.IDS_DefaultInterfaceImplementation.Localize(), availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } if (!implementingType.ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } } /// <summary> /// These diagnostics are for members that do implicitly implement an interface member, but do so /// in an undesirable way. /// </summary> private static void ReportImplicitImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { bool reportedAnError = false; if (interfaceMember.Kind == SymbolKind.Method) { var interfaceMethod = (MethodSymbol)interfaceMember; bool implicitImplIsAccessor = implicitImpl.IsAccessor(); bool interfaceMethodIsAccessor = interfaceMethod.IsAccessor(); if (interfaceMethodIsAccessor && !implicitImplIsAccessor && !interfaceMethod.IsIndexedPropertyAccessor()) { diagnostics.Add(ErrorCode.ERR_MethodImplementingAccessor, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (!interfaceMethodIsAccessor && implicitImplIsAccessor) { diagnostics.Add(ErrorCode.ERR_AccessorImplementingMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else { var implicitImplMethod = (MethodSymbol)implicitImpl; if (implicitImplMethod.IsConditional) { // CS0629: Conditional member '{0}' cannot implement interface member '{1}' in type '{2}' diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByConditional, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (implicitImplMethod.IsStatic && implicitImplMethod.MethodKind == MethodKind.Ordinary && implicitImplMethod.GetUnmanagedCallersOnlyAttributeData(forceComplete: true) is not null) { diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (ReportAnyMismatchedConstraints(interfaceMethod, implementingType, implicitImplMethod, diagnostics)) { reportedAnError = true; } } } if (implicitImpl.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(implicitImpl, interfaceMember)) { // it is ok to implement implicitly with no tuple names, for compatibility with C# 6, but otherwise names should match diagnostics.Add(ErrorCode.ERR_ImplBadTupleNames, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMember); reportedAnError = true; } if (!reportedAnError && implementingType.DeclaringCompilation != null) { CheckNullableReferenceTypeMismatchOnImplementingMember(implementingType, implicitImpl, interfaceMember, isExplicit: false, diagnostics); } // In constructed types, it is possible to see multiple members with the same (runtime) signature. // Now that we know which member will implement the interface member, confirm that it is the only // such member. if (!implicitImpl.ContainingType.IsDefinition) { foreach (Symbol member in implicitImpl.ContainingType.GetMembers(implicitImpl.Name)) { if (member.DeclaredAccessibility != Accessibility.Public || member.IsStatic || member == implicitImpl) { //do nothing - not an ambiguous implementation } else if (MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, member) && !member.IsAccessor()) { // CONSIDER: Dev10 does not seem to report this for indexers or their accessors. diagnostics.Add(ErrorCode.WRN_MultipleRuntimeImplementationMatches, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, member), member, interfaceMember, implementingType); } } } if (implicitImpl.IsStatic && !implementingType.ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } internal static void CheckNullableReferenceTypeMismatchOnImplementingMember(TypeSymbol implementingType, Symbol implementingMember, Symbol interfaceMember, bool isExplicit, BindingDiagnosticBag diagnostics) { if (!implementingMember.IsImplicitlyDeclared && !implementingMember.IsAccessor()) { CSharpCompilation compilation = implementingType.DeclaringCompilation; if (interfaceMember.Kind == SymbolKind.Event) { var implementingEvent = (EventSymbol)implementingMember; var implementedEvent = (EventSymbol)interfaceMember; SourceMemberContainerTypeSymbol.CheckValidNullableEventOverride(compilation, implementedEvent, implementingEvent, diagnostics, (diagnostics, implementedEvent, implementingEvent, arg) => { if (arg.isExplicit) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, implementingEvent.Locations[0], new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedEvent, arg.implementingType, implementingEvent), new FormattedSymbol(implementingEvent, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }, (implementingType, isExplicit)); } else { ReportMismatchInReturnType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInReturnType = (diagnostics, implementedMethod, implementingMethod, topLevel, arg) => { if (arg.isExplicit) { // We use ConstructedFrom symbols here and below to not leak methods with Ignored annotations in type arguments // into diagnostics diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; ReportMismatchInParameterType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInParameterType = (diagnostics, implementedMethod, implementingMethod, implementingParameter, topLevel, arg) => { if (arg.isExplicit) { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; switch (interfaceMember.Kind) { case SymbolKind.Property: var implementingProperty = (PropertySymbol)implementingMember; var implementedProperty = (PropertySymbol)interfaceMember; if (implementedProperty.GetMethod.IsImplementable()) { MethodSymbol implementingGetMethod = implementingProperty.GetOwnOrInheritedGetMethod(); SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.GetMethod, implementingGetMethod, diagnostics, reportMismatchInReturnType, // Don't check parameters on the getter if there is a setter // because they will be a subset of the setter (!implementedProperty.SetMethod.IsImplementable() || implementingGetMethod?.AssociatedSymbol != implementingProperty || implementingProperty.GetOwnOrInheritedSetMethod()?.AssociatedSymbol != implementingProperty) ? reportMismatchInParameterType : null, (implementingType, isExplicit)); } if (implementedProperty.SetMethod.IsImplementable()) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.SetMethod, implementingProperty.GetOwnOrInheritedSetMethod(), diagnostics, null, reportMismatchInParameterType, (implementingType, isExplicit)); } break; case SymbolKind.Method: var implementingMethod = (MethodSymbol)implementingMember; var implementedMethod = (MethodSymbol)interfaceMember; if (implementedMethod.IsGenericMethod) { implementedMethod = implementedMethod.Construct(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementingMethod.TypeParameters)); } SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedMethod, implementingMethod, diagnostics, reportMismatchInReturnType, reportMismatchInParameterType, (implementingType, isExplicit)); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } } } } /// <summary> /// These diagnostics are for members that almost, but not actually, implicitly implement an interface member. /// </summary> private static void ReportImplicitImplementationMismatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol closestMismatch, BindingDiagnosticBag diagnostics) { // Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. Location interfaceLocation = GetInterfaceLocation(interfaceMember, implementingType); if (closestMismatch.IsStatic != interfaceMember.IsStatic) { diagnostics.Add(closestMismatch.IsStatic ? ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (closestMismatch.DeclaredAccessibility != Accessibility.Public) { ErrorCode errorCode = interfaceMember.IsAccessor() ? ErrorCode.ERR_UnimplementedInterfaceAccessor : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic; diagnostics.Add(errorCode, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (HaveInitOnlyMismatch(interfaceMember, closestMismatch)) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else //return ref kind or type doesn't match { RefKind interfaceMemberRefKind = RefKind.None; TypeSymbol interfaceMemberReturnType; switch (interfaceMember.Kind) { case SymbolKind.Method: var method = (MethodSymbol)interfaceMember; interfaceMemberRefKind = method.RefKind; interfaceMemberReturnType = method.ReturnType; break; case SymbolKind.Property: var property = (PropertySymbol)interfaceMember; interfaceMemberRefKind = property.RefKind; interfaceMemberReturnType = property.Type; break; case SymbolKind.Event: interfaceMemberReturnType = ((EventSymbol)interfaceMember).Type; break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } bool hasRefReturnMismatch = false; switch (closestMismatch.Kind) { case SymbolKind.Method: hasRefReturnMismatch = ((MethodSymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; case SymbolKind.Property: hasRefReturnMismatch = ((PropertySymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; } DiagnosticInfo useSiteDiagnostic; if ((object)interfaceMemberReturnType != null && (useSiteDiagnostic = interfaceMemberReturnType.GetUseSiteInfo().DiagnosticInfo) != null && useSiteDiagnostic.DefaultSeverity == DiagnosticSeverity.Error) { diagnostics.Add(useSiteDiagnostic, interfaceLocation); } else if (hasRefReturnMismatch) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, interfaceLocation, implementingType, interfaceMember, closestMismatch, interfaceMemberReturnType); } } } internal static bool HaveInitOnlyMismatch(Symbol one, Symbol other) { if (!(one is MethodSymbol oneMethod)) { return false; } if (!(other is MethodSymbol otherMethod)) { return false; } return oneMethod.IsInitOnly != otherMethod.IsInitOnly; } /// <summary> /// Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. /// </summary> private static Location GetInterfaceLocation(Symbol interfaceMember, TypeSymbol implementingType) { Debug.Assert((object)implementingType != null); var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = null; if (implementingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[@interface].Contains(@interface)) { snt = implementingType as SourceMemberContainerTypeSymbol; } return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations.FirstOrNone(); } private static bool ReportAnyMismatchedConstraints(MethodSymbol interfaceMethod, TypeSymbol implementingType, MethodSymbol implicitImpl, BindingDiagnosticBag diagnostics) { Debug.Assert(interfaceMethod.Arity == implicitImpl.Arity); bool result = false; var arity = interfaceMethod.Arity; if (arity > 0) { var typeParameters1 = interfaceMethod.TypeParameters; var typeParameters2 = implicitImpl.TypeParameters; var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true); var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true); // Report any mismatched method constraints. for (int i = 0; i < arity; i++) { var typeParameter1 = typeParameters1[i]; var typeParameter2 = typeParameters2[i]; if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { // If the matching method for the interface member is defined on the implementing type, // the matching method location is used for the error. Otherwise, the location of the // implementing type is used. (This differs from Dev10 which associates the error with // the closest method always. That behavior can be confusing though, since in the case // of "interface I { M; } class A { M; } class B : A, I { }", this means reporting an error on // A.M that it does not satisfy I.M even though A does not implement I. Furthermore if // A is defined in metadata, there is no location for A.M. Instead, we simply report the // error on B if the match to I.M is in a base class.) diagnostics.Add(ErrorCode.ERR_ImplBadConstraints, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } } } return result; } internal static Location GetImplicitImplementationDiagnosticLocation(Symbol interfaceMember, TypeSymbol implementingType, Symbol member) { if (TypeSymbol.Equals(member.ContainingType, implementingType, TypeCompareKind.ConsiderEverything2)) { return member.Locations[0]; } else { var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = implementingType as SourceMemberContainerTypeSymbol; return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations[0]; } } /// <summary> /// Search the declared members of a type for one that could be an implementation /// of a given interface member (depending on interface declarations). /// </summary> /// <param name="interfaceMember">The interface member being implemented.</param> /// <param name="implementingTypeIsFromSomeCompilation">True if the implementing type is from some compilation (i.e. not from metadata).</param> /// <param name="currType">The type on which we are looking for a declared implementation of the interface member.</param> /// <param name="implicitImpl">A member on currType that could implement the interface, or null.</param> /// <param name="closeMismatch">A member on currType that could have been an attempt to implement the interface, or null.</param> /// <remarks> /// There is some similarity between this member and OverriddenOrHiddenMembersHelpers.FindOverriddenOrHiddenMembersInType. /// When making changes to this member, think about whether or not they should also be applied in MemberSymbol. /// One key difference is that custom modifiers are considered when looking up overridden members, but /// not when looking up implicit implementations. We're preserving this behavior from Dev10. /// </remarks> private static void FindPotentialImplicitImplementationMemberDeclaredInType( Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation, TypeSymbol currType, out Symbol implicitImpl, out Symbol closeMismatch) { implicitImpl = null; closeMismatch = null; bool? isOperator = null; if (interfaceMember is MethodSymbol interfaceMethod) { isOperator = interfaceMethod.MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion; } foreach (Symbol member in currType.GetMembers(interfaceMember.Name)) { if (member.Kind == interfaceMember.Kind) { if (isOperator.HasValue && (((MethodSymbol)member).MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion) != isOperator.GetValueOrDefault()) { continue; } if (IsInterfaceMemberImplementation(member, interfaceMember, implementingTypeIsFromSomeCompilation)) { implicitImpl = member; return; } // If we haven't found a match, do a weaker comparison that ignores static-ness, accessibility, and return type. else if ((object)closeMismatch == null && implementingTypeIsFromSomeCompilation) { // We can ignore custom modifiers here, because our goal is to improve the helpfulness // of an error we're already giving, rather than to generate a new error. if (MemberSignatureComparer.CSharpCloseImplicitImplementationComparer.Equals(interfaceMember, member)) { closeMismatch = member; } } } } } /// <summary> /// To implement an interface member, a candidate member must be public, non-static, and have /// the same signature. "Have the same signature" has a looser definition if the type implementing /// the interface is from source. /// </summary> /// <remarks> /// PROPERTIES: /// NOTE: we're not checking whether this property has at least the accessors /// declared in the interface. Dev10 considers it a match either way and, /// reports failure to implement accessors separately. /// /// If the implementing type (i.e. the type with the interface in its interface /// list) is in source, then we can ignore custom modifiers in/on the property /// type because they will be copied into the bridge property that explicitly /// implements the interface property (or they would be, if we created such /// a bridge property). Bridge *methods* (not properties) are inserted in /// SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. /// /// CONSIDER: The spec for interface mapping (13.4.4) could be interpreted to mean that this /// property is not an implementation unless it has an accessor for each accessor of the /// interface property. For now, we prefer to represent that case as having an implemented /// property and an unimplemented accessor because it makes finding accessor implementations /// much easier. If we decide that we want the API to report the property as unimplemented, /// then it might be appropriate to keep current result internally and just check the accessors /// before returning the value from the public API (similar to the way MethodSymbol.OverriddenMethod /// filters MethodSymbol.OverriddenOrHiddenMembers. /// </remarks> private static bool IsInterfaceMemberImplementation(Symbol candidateMember, Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation) { if (candidateMember.DeclaredAccessibility != Accessibility.Public || candidateMember.IsStatic != interfaceMember.IsStatic) { return false; } else if (HaveInitOnlyMismatch(candidateMember, interfaceMember)) { return false; } else if (implementingTypeIsFromSomeCompilation) { // We're specifically ignoring custom modifiers for source types because that's what Dev10 does. // Inexact matches are acceptable because we'll just generate bridge members - explicit implementations // with exact signatures that delegate to the inexact match. This happens automatically in // SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. return MemberSignatureComparer.CSharpImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } else { // NOTE: Dev10 seems to use the C# rules in this case as well, but it doesn't give diagnostics about // the failure of a metadata type to implement an interface so there's no problem with reporting the // CLI interpretation instead. For example, using this comparer might allow a member with a ref // parameter to implement a member with an out parameter - which Dev10 would not allow - but that's // okay because Dev10's behavior is not observable. return MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } } protected MultiDictionary<Symbol, Symbol>.ValueSet GetExplicitImplementationForInterfaceMember(Symbol interfaceMember) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return default; } if (info.explicitInterfaceImplementationMap == null) { Interlocked.CompareExchange(ref info.explicitInterfaceImplementationMap, MakeExplicitInterfaceImplementationMap(), null); } return info.explicitInterfaceImplementationMap[interfaceMember]; } private MultiDictionary<Symbol, Symbol> MakeExplicitInterfaceImplementationMap() { var map = new MultiDictionary<Symbol, Symbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach (var member in this.GetMembersUnordered()) { foreach (var interfaceMember in member.GetExplicitInterfaceImplementations()) { Debug.Assert(interfaceMember.Kind != SymbolKind.Method || (object)interfaceMember == ((MethodSymbol)interfaceMember).ConstructedFrom); map.Add(interfaceMember, member); } } return map; } #nullable enable /// <summary> /// If implementation of an interface method <paramref name="interfaceMethod"/> will be accompanied with /// a MethodImpl entry in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API, this method returns the "Body" part /// of the MethodImpl entry, i.e. the method that implements the <paramref name="interfaceMethod"/>. /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the result is the method that the language considers to implement the <paramref name="interfaceMethod"/>, /// rather than the forwarding method. In other words, it is the method that the forwarding method forwards to. /// </summary> /// <param name="interfaceMethod">The interface method that is going to be implemented by using synthesized MethodImpl entry.</param> /// <returns></returns> protected MethodSymbol? GetBodyOfSynthesizedInterfaceMethodImpl(MethodSymbol interfaceMethod) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return null; } if (info.synthesizedMethodImplMap == null) { Interlocked.CompareExchange(ref info.synthesizedMethodImplMap, makeSynthesizedMethodImplMap(), null); } if (info.synthesizedMethodImplMap.TryGetValue(interfaceMethod, out MethodSymbol? result)) { return result; } return null; ImmutableDictionary<MethodSymbol, MethodSymbol> makeSynthesizedMethodImplMap() { var map = ImmutableDictionary.CreateBuilder<MethodSymbol, MethodSymbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach ((MethodSymbol body, MethodSymbol implemented) in this.SynthesizedInterfaceMethodImpls()) { map.Add(implemented, body); } return map.ToImmutable(); } } /// <summary> /// Returns information about interface method implementations that will be accompanied with /// MethodImpl entries in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API. The "Body" is the method that /// implements the interface method "Implemented". /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the "Body" is the method that the language considers to implement the interface method, /// the "Implemented", rather than the forwarding method. In other words, it is the method that /// the forwarding method forwards to. /// </summary> internal abstract IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls(); #nullable disable protected class ExplicitInterfaceImplementationTargetMemberEqualityComparer : IEqualityComparer<Symbol> { public static readonly ExplicitInterfaceImplementationTargetMemberEqualityComparer Instance = new ExplicitInterfaceImplementationTargetMemberEqualityComparer(); private ExplicitInterfaceImplementationTargetMemberEqualityComparer() { } public bool Equals(Symbol x, Symbol y) { return x.OriginalDefinition == y.OriginalDefinition && x.ContainingType.Equals(y.ContainingType, TypeCompareKind.CLRSignatureCompareOptions); } public int GetHashCode(Symbol obj) { return obj.OriginalDefinition.GetHashCode(); } } #endregion Interface member checks #region Abstract base type checks /// <summary> /// The set of abstract members in declared in this type or declared in a base type and not overridden. /// </summary> internal ImmutableHashSet<Symbol> AbstractMembers { get { if (_lazyAbstractMembers == null) { Interlocked.CompareExchange(ref _lazyAbstractMembers, ComputeAbstractMembers(), null); } return _lazyAbstractMembers; } } private ImmutableHashSet<Symbol> ComputeAbstractMembers() { var abstractMembers = ImmutableHashSet.Create<Symbol>(); var overriddenMembers = ImmutableHashSet.Create<Symbol>(); foreach (var member in this.GetMembersUnordered()) { if (this.IsAbstract && member.IsAbstract && member.Kind != SymbolKind.NamedType) { abstractMembers = abstractMembers.Add(member); } Symbol overriddenMember = null; switch (member.Kind) { case SymbolKind.Method: { overriddenMember = ((MethodSymbol)member).OverriddenMethod; break; } case SymbolKind.Property: { overriddenMember = ((PropertySymbol)member).OverriddenProperty; break; } case SymbolKind.Event: { overriddenMember = ((EventSymbol)member).OverriddenEvent; break; } } if ((object)overriddenMember != null) { overriddenMembers = overriddenMembers.Add(overriddenMember); } } if ((object)this.BaseTypeNoUseSiteDiagnostics != null && this.BaseTypeNoUseSiteDiagnostics.IsAbstract) { foreach (var baseAbstractMember in this.BaseTypeNoUseSiteDiagnostics.AbstractMembers) { if (!overriddenMembers.Contains(baseAbstractMember)) { abstractMembers = abstractMembers.Add(baseAbstractMember); } } } return abstractMembers; } #endregion Abstract base type checks [Obsolete("Use TypeWithAnnotations.Is method.", true)] internal bool Equals(TypeWithAnnotations other) { throw ExceptionUtilities.Unreachable; } public static bool Equals(TypeSymbol left, TypeSymbol right, TypeCompareKind comparison) { if (left is null) { return right is null; } return left.Equals(right, comparison); } [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; internal ITypeSymbol GetITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { if (nullableAnnotation == DefaultNullableAnnotation) { return (ITypeSymbol)this.ISymbol; } return CreateITypeSymbol(nullableAnnotation); } internal CodeAnalysis.NullableAnnotation DefaultNullableAnnotation => NullableAnnotationExtensions.ToPublicAnnotation(this, NullableAnnotation.Oblivious); protected abstract ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation); TypeKind ITypeSymbolInternal.TypeKind => this.TypeKind; SpecialType ITypeSymbolInternal.SpecialType => this.SpecialType; bool ITypeSymbolInternal.IsReferenceType => this.IsReferenceType; bool ITypeSymbolInternal.IsValueType => this.IsValueType; ITypeSymbol ITypeSymbolInternal.GetITypeSymbol() { return GetITypeSymbol(DefaultNullableAnnotation); } internal abstract bool IsRecord { get; } internal abstract bool IsRecordStruct { get; } } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/Core/Portable/Emit/EditAndContinue/IPEDeltaAssemblyBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Emit { internal interface IPEDeltaAssemblyBuilder { void OnCreatedIndices(DiagnosticBag diagnostics); IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> GetAnonymousTypeMap(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Emit { internal interface IPEDeltaAssemblyBuilder { void OnCreatedIndices(DiagnosticBag diagnostics); IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> GetAnonymousTypeMap(); } }
-1
dotnet/roslyn
55,549
Record structs have no copy constructors
Fixes https://github.com/dotnet/roslyn/issues/54413
jcouv
2021-08-11T18:45:06Z
2021-08-13T19:07:59Z
5c751989cc049a11531de176279d17c94bc1cc51
4c2b07f6ad6fda3ce90dff81a5dc7c42abd7ae56
Record structs have no copy constructors. Fixes https://github.com/dotnet/roslyn/issues/54413
./src/Compilers/VisualBasic/Portable/Parser/ISyntaxFactoryContext.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend Interface ISyntaxFactoryContext ReadOnly Property IsWithinAsyncMethodOrLambda As Boolean ReadOnly Property IsWithinIteratorContext As Boolean End Interface End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend Interface ISyntaxFactoryContext ReadOnly Property IsWithinAsyncMethodOrLambda As Boolean ReadOnly Property IsWithinIteratorContext As Boolean End Interface End Namespace
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/ExpressionEvaluator/Core/Source/FunctionResolver/FunctionResolver.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection.Metadata; using Microsoft.CodeAnalysis.Debugging; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.FunctionResolution; using Microsoft.VisualStudio.Debugger.Symbols; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal abstract class FunctionResolver : FunctionResolverBase<DkmProcess, DkmClrModuleInstance, DkmRuntimeFunctionResolutionRequest>, IDkmRuntimeFunctionResolver, IDkmModuleInstanceLoadNotification, IDkmModuleInstanceUnloadNotification, IDkmModuleModifiedNotification, IDkmModuleSymbolsLoadedNotification { void IDkmRuntimeFunctionResolver.EnableResolution(DkmRuntimeFunctionResolutionRequest request, DkmWorkList workList) { if (request.LineOffset > 0) { return; } EnableResolution(request.Process, request, OnFunctionResolved(workList)); } void IDkmModuleInstanceLoadNotification.OnModuleInstanceLoad(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptorS eventDescriptor) { OnModuleLoad(moduleInstance, workList); } void IDkmModuleInstanceUnloadNotification.OnModuleInstanceUnload(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptor eventDescriptor) { // Implementing IDkmModuleInstanceUnloadNotification // (with Synchronized="true" in .vsdconfigxml) prevents // caller from unloading modules while binding. } void IDkmModuleModifiedNotification.OnModuleModified(DkmModuleInstance moduleInstance) { // Implementing IDkmModuleModifiedNotification // (with Synchronized="true" in .vsdconfigxml) prevents // caller from modifying modules while binding. } void IDkmModuleSymbolsLoadedNotification.OnModuleSymbolsLoaded(DkmModuleInstance moduleInstance, DkmModule module, bool isReload, DkmWorkList workList, DkmEventDescriptor eventDescriptor) { OnModuleLoad(moduleInstance, workList); } private void OnModuleLoad(DkmModuleInstance moduleInstance, DkmWorkList workList) { var module = moduleInstance as DkmClrModuleInstance; Debug.Assert(module != null); // <Filter><RuntimeId RequiredValue="DkmRuntimeId.Clr"/></Filter> should ensure this. if (module == null) { // Only interested in managed modules. return; } if (module.Module == null) { // Only resolve breakpoints if symbols have been loaded. return; } OnModuleLoad(module.Process, module, OnFunctionResolved(workList)); } internal sealed override bool ShouldEnableFunctionResolver(DkmProcess process) { var dataItem = process.GetDataItem<FunctionResolverDataItem>(); if (dataItem == null) { var enable = ShouldEnable(process); dataItem = new FunctionResolverDataItem(enable); process.SetDataItem(DkmDataCreationDisposition.CreateNew, dataItem); } return dataItem.Enabled; } internal sealed override IEnumerable<DkmClrModuleInstance> GetAllModules(DkmProcess process) { foreach (var runtimeInstance in process.GetRuntimeInstances()) { var runtime = runtimeInstance as DkmClrRuntimeInstance; if (runtime == null) { continue; } foreach (var moduleInstance in runtime.GetModuleInstances()) { // Only interested in managed modules. if (moduleInstance is DkmClrModuleInstance module) { yield return module; } } } } internal sealed override string GetModuleName(DkmClrModuleInstance module) { return module.Name; } internal sealed override MetadataReader GetModuleMetadata(DkmClrModuleInstance module) { uint length; IntPtr ptr; try { ptr = module.GetMetaDataBytesPtr(out length); } catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) { return null; } Debug.Assert(length > 0); unsafe { return new MetadataReader((byte*)ptr, (int)length); } } internal sealed override DkmRuntimeFunctionResolutionRequest[] GetRequests(DkmProcess process) { return process.GetRuntimeFunctionResolutionRequests(); } internal sealed override string GetRequestModuleName(DkmRuntimeFunctionResolutionRequest request) { return request.ModuleName; } internal sealed override Guid GetLanguageId(DkmRuntimeFunctionResolutionRequest request) { return request.CompilerId.LanguageId; } private static OnFunctionResolvedDelegate<DkmClrModuleInstance, DkmRuntimeFunctionResolutionRequest> OnFunctionResolved(DkmWorkList workList) { return (DkmClrModuleInstance module, DkmRuntimeFunctionResolutionRequest request, int token, int version, int ilOffset) => { var address = DkmClrInstructionAddress.Create( module.RuntimeInstance, module, new DkmClrMethodId(Token: token, Version: (uint)version), NativeOffset: uint.MaxValue, ILOffset: (uint)ilOffset, CPUInstruction: null); // Use async overload of OnFunctionResolved to avoid deadlock. request.OnFunctionResolved(workList, address, result => { }); }; } private static readonly Guid s_messageSourceId = new Guid("ac353c9b-c599-427b-9424-cbe1ad19f81e"); private static bool ShouldEnable(DkmProcess process) { var message = DkmCustomMessage.Create( process.Connection, process, s_messageSourceId, MessageCode: 1, // Is legacy EE enabled? Parameter1: null, Parameter2: null); try { var reply = message.SendLower(); var result = (int)reply.Parameter1; // Possible values are 0 = false, 1 = true, 2 = not ready. // At this point, we should only get 0 or 1, but to be // safe, treat values other than 0 or 1 as false. Debug.Assert(result == 0 || result == 1); return result == 0; } catch (NotImplementedException) { return false; } } private sealed class FunctionResolverDataItem : DkmDataItem { internal FunctionResolverDataItem(bool enabled) { Enabled = enabled; } internal readonly bool Enabled; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection.Metadata; using Microsoft.CodeAnalysis.Debugging; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.FunctionResolution; using Microsoft.VisualStudio.Debugger.Symbols; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal abstract class FunctionResolver : FunctionResolverBase<DkmProcess, DkmClrModuleInstance, DkmRuntimeFunctionResolutionRequest>, IDkmRuntimeFunctionResolver, IDkmModuleInstanceLoadNotification, IDkmModuleInstanceUnloadNotification, IDkmModuleModifiedNotification, IDkmModuleSymbolsLoadedNotification { void IDkmRuntimeFunctionResolver.EnableResolution(DkmRuntimeFunctionResolutionRequest request, DkmWorkList workList) { if (request.LineOffset > 0) { return; } EnableResolution(request.Process, request, OnFunctionResolved(workList)); } void IDkmModuleInstanceLoadNotification.OnModuleInstanceLoad(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptorS eventDescriptor) { OnModuleLoad(moduleInstance, workList); } void IDkmModuleInstanceUnloadNotification.OnModuleInstanceUnload(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptor eventDescriptor) { // Implementing IDkmModuleInstanceUnloadNotification // (with Synchronized="true" in .vsdconfigxml) prevents // caller from unloading modules while binding. } void IDkmModuleModifiedNotification.OnModuleModified(DkmModuleInstance moduleInstance) { // Implementing IDkmModuleModifiedNotification // (with Synchronized="true" in .vsdconfigxml) prevents // caller from modifying modules while binding. } void IDkmModuleSymbolsLoadedNotification.OnModuleSymbolsLoaded(DkmModuleInstance moduleInstance, DkmModule module, bool isReload, DkmWorkList workList, DkmEventDescriptor eventDescriptor) { OnModuleLoad(moduleInstance, workList); } private void OnModuleLoad(DkmModuleInstance moduleInstance, DkmWorkList workList) { var module = moduleInstance as DkmClrModuleInstance; Debug.Assert(module != null); // <Filter><RuntimeId RequiredValue="DkmRuntimeId.Clr"/></Filter> should ensure this. if (module == null) { // Only interested in managed modules. return; } if (module.Module == null) { // Only resolve breakpoints if symbols have been loaded. return; } OnModuleLoad(module.Process, module, OnFunctionResolved(workList)); } internal sealed override bool ShouldEnableFunctionResolver(DkmProcess process) { var dataItem = process.GetDataItem<FunctionResolverDataItem>(); if (dataItem == null) { var enable = ShouldEnable(process); dataItem = new FunctionResolverDataItem(enable); process.SetDataItem(DkmDataCreationDisposition.CreateNew, dataItem); } return dataItem.Enabled; } internal sealed override IEnumerable<DkmClrModuleInstance> GetAllModules(DkmProcess process) { foreach (var runtimeInstance in process.GetRuntimeInstances()) { var runtime = runtimeInstance as DkmClrRuntimeInstance; if (runtime == null) { continue; } foreach (var moduleInstance in runtime.GetModuleInstances()) { // Only interested in managed modules. if (moduleInstance is DkmClrModuleInstance module) { yield return module; } } } } internal sealed override string GetModuleName(DkmClrModuleInstance module) { return module.Name; } internal sealed override unsafe bool TryGetMetadata(DkmClrModuleInstance module, out byte* pointer, out int length) { try { pointer = (byte*)module.GetMetaDataBytesPtr(out var size); length = (int)size; return true; } catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) { pointer = null; length = 0; return false; } } internal sealed override DkmRuntimeFunctionResolutionRequest[] GetRequests(DkmProcess process) { return process.GetRuntimeFunctionResolutionRequests(); } internal sealed override string GetRequestModuleName(DkmRuntimeFunctionResolutionRequest request) { return request.ModuleName; } internal sealed override Guid GetLanguageId(DkmRuntimeFunctionResolutionRequest request) { return request.CompilerId.LanguageId; } private static OnFunctionResolvedDelegate<DkmClrModuleInstance, DkmRuntimeFunctionResolutionRequest> OnFunctionResolved(DkmWorkList workList) { return (DkmClrModuleInstance module, DkmRuntimeFunctionResolutionRequest request, int token, int version, int ilOffset) => { var address = DkmClrInstructionAddress.Create( module.RuntimeInstance, module, new DkmClrMethodId(Token: token, Version: (uint)version), NativeOffset: uint.MaxValue, ILOffset: (uint)ilOffset, CPUInstruction: null); // Use async overload of OnFunctionResolved to avoid deadlock. request.OnFunctionResolved(workList, address, result => { }); }; } private static readonly Guid s_messageSourceId = new Guid("ac353c9b-c599-427b-9424-cbe1ad19f81e"); private static bool ShouldEnable(DkmProcess process) { var message = DkmCustomMessage.Create( process.Connection, process, s_messageSourceId, MessageCode: 1, // Is legacy EE enabled? Parameter1: null, Parameter2: null); try { var reply = message.SendLower(); var result = (int)reply.Parameter1; // Possible values are 0 = false, 1 = true, 2 = not ready. // At this point, we should only get 0 or 1, but to be // safe, treat values other than 0 or 1 as false. Debug.Assert(result == 0 || result == 1); return result == 0; } catch (NotImplementedException) { return false; } } private sealed class FunctionResolverDataItem : DkmDataItem { internal FunctionResolverDataItem(bool enabled) { Enabled = enabled; } internal readonly bool Enabled; } } }
1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/ExpressionEvaluator/Core/Source/FunctionResolver/FunctionResolverBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.VisualStudio.Debugger.Evaluation; using System; using System.Collections.Generic; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal abstract class FunctionResolverBase<TProcess, TModule, TRequest> where TProcess : class where TModule : class where TRequest : class { internal abstract bool ShouldEnableFunctionResolver(TProcess process); internal abstract IEnumerable<TModule> GetAllModules(TProcess process); internal abstract string GetModuleName(TModule module); internal abstract MetadataReader GetModuleMetadata(TModule module); internal abstract TRequest[] GetRequests(TProcess process); internal abstract string GetRequestModuleName(TRequest request); internal abstract RequestSignature GetParsedSignature(TRequest request); internal abstract bool IgnoreCase { get; } internal abstract Guid GetLanguageId(TRequest request); internal abstract Guid LanguageId { get; } internal void EnableResolution(TProcess process, TRequest request, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { if (!ShouldHandleRequest(request)) { return; } var moduleName = GetRequestModuleName(request); var signature = GetParsedSignature(request); if (signature == null) { return; } bool checkEnabled = true; foreach (var module in GetAllModules(process)) { if (checkEnabled) { if (!ShouldEnableFunctionResolver(process)) { return; } checkEnabled = false; } if (!ShouldModuleHandleRequest(module, moduleName)) { continue; } var reader = GetModuleMetadata(module); if (reader == null) { continue; } var resolver = CreateMetadataResolver(process, module, reader, onFunctionResolved); resolver.Resolve(request, signature); } } internal void OnModuleLoad(TProcess process, TModule module, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { if (!ShouldEnableFunctionResolver(process)) { return; } MetadataResolver<TProcess, TModule, TRequest> resolver = null; var requests = GetRequests(process); foreach (var request in requests) { if (!ShouldHandleRequest(request)) { continue; } var moduleName = GetRequestModuleName(request); if (!ShouldModuleHandleRequest(module, moduleName)) { continue; } var signature = GetParsedSignature(request); if (signature == null) { continue; } if (resolver == null) { var reader = GetModuleMetadata(module); if (reader == null) { return; } resolver = CreateMetadataResolver(process, module, reader, onFunctionResolved); } resolver.Resolve(request, signature); } } private MetadataResolver<TProcess, TModule, TRequest> CreateMetadataResolver( TProcess process, TModule module, MetadataReader reader, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { return new MetadataResolver<TProcess, TModule, TRequest>(process, module, reader, IgnoreCase, onFunctionResolved); } private bool ShouldHandleRequest(TRequest request) { var languageId = GetLanguageId(request); // Handle requests with no language id, a matching language id, // or causality breakpoint requests (debugging web services). return languageId == Guid.Empty || languageId == LanguageId || languageId == DkmLanguageId.CausalityBreakpoint; } private bool ShouldModuleHandleRequest(TModule module, string moduleName) { if (string.IsNullOrEmpty(moduleName)) { return true; } var name = GetModuleName(module); return moduleName.Equals(name, StringComparison.OrdinalIgnoreCase); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.VisualStudio.Debugger.Evaluation; using System; using System.Collections.Generic; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal abstract class FunctionResolverBase<TProcess, TModule, TRequest> where TProcess : class where TModule : class where TRequest : class { internal abstract bool ShouldEnableFunctionResolver(TProcess process); internal abstract IEnumerable<TModule> GetAllModules(TProcess process); internal abstract string GetModuleName(TModule module); internal abstract unsafe bool TryGetMetadata(TModule module, out byte* pointer, out int length); internal abstract TRequest[] GetRequests(TProcess process); internal abstract string GetRequestModuleName(TRequest request); internal abstract RequestSignature GetParsedSignature(TRequest request); internal abstract bool IgnoreCase { get; } internal abstract Guid GetLanguageId(TRequest request); internal abstract Guid LanguageId { get; } internal void EnableResolution(TProcess process, TRequest request, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { if (!ShouldHandleRequest(request)) { return; } var moduleName = GetRequestModuleName(request); var signature = GetParsedSignature(request); if (signature == null) { return; } bool checkEnabled = true; foreach (var module in GetAllModules(process)) { if (checkEnabled) { if (!ShouldEnableFunctionResolver(process)) { return; } checkEnabled = false; } if (!ShouldModuleHandleRequest(module, moduleName)) { continue; } var reader = GetMetadataReader(module); if (reader == null) { // ignore modules with bad metadata continue; } var resolver = CreateMetadataResolver(process, module, reader, onFunctionResolved); resolver.Resolve(request, signature); } } private unsafe MetadataReader GetMetadataReader(TModule module) { if (!TryGetMetadata(module, out var pointer, out var length)) { return null; } try { return new MetadataReader(pointer, length); } catch (BadImageFormatException) { return null; } } internal void OnModuleLoad(TProcess process, TModule module, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { if (!ShouldEnableFunctionResolver(process)) { return; } MetadataResolver<TProcess, TModule, TRequest> resolver = null; var requests = GetRequests(process); foreach (var request in requests) { if (!ShouldHandleRequest(request)) { continue; } var moduleName = GetRequestModuleName(request); if (!ShouldModuleHandleRequest(module, moduleName)) { continue; } var signature = GetParsedSignature(request); if (signature == null) { continue; } if (resolver == null) { var reader = GetMetadataReader(module); if (reader == null) { return; } resolver = CreateMetadataResolver(process, module, reader, onFunctionResolved); } resolver.Resolve(request, signature); } } private MetadataResolver<TProcess, TModule, TRequest> CreateMetadataResolver( TProcess process, TModule module, MetadataReader reader, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { return new MetadataResolver<TProcess, TModule, TRequest>(process, module, reader, IgnoreCase, onFunctionResolved); } private bool ShouldHandleRequest(TRequest request) { var languageId = GetLanguageId(request); // Handle requests with no language id, a matching language id, // or causality breakpoint requests (debugging web services). return languageId == Guid.Empty || languageId == LanguageId || languageId == DkmLanguageId.CausalityBreakpoint; } private bool ShouldModuleHandleRequest(TModule module, string moduleName) { if (string.IsNullOrEmpty(moduleName)) { return true; } var name = GetModuleName(module); return moduleName.Equals(name, StringComparison.OrdinalIgnoreCase); } } }
1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/ExpressionEvaluator/Core/Test/FunctionResolver/CSharpFunctionResolverTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using Xunit; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { public class CSharpFunctionResolverTests : FunctionResolverTestBase { [Fact] public void OnLoad() { var source = @"class C { static void F(object o) { } object F() => null; }"; var compilation = CreateCompilation(source); var module = new Module(compilation.EmitToArray()); using (var process = new Process()) { var resolver = Resolver.CSharpResolver; var request = new Request(null, MemberSignatureParser.Parse("C.F")); resolver.EnableResolution(process, request); VerifySignatures(request); process.AddModule(module); resolver.OnModuleLoad(process, module); VerifySignatures(request, "C.F(System.Object)", "C.F()"); } } /// <summary> /// ShouldEnableFunctionResolver should not be called /// until the first module is available for binding. /// </summary> [Fact] public void ShouldEnableFunctionResolver() { var sourceA = @"class A { static void F() { } static void G() { } }"; var sourceB = @"class B { static void F() { } static void G() { } }"; var bytesA = CreateCompilation(sourceA).EmitToArray(); var bytesB = CreateCompilation(sourceB).EmitToArray(); var resolver = Resolver.CSharpResolver; // Two modules loaded before two global requests, // ... resolver enabled. var moduleA = new Module(bytesA, name: "A.dll"); var moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true, modules: new[] { moduleA, moduleB })) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()", "B.F()"); VerifySignatures(requestG, "A.G()", "B.G()"); } // ... resolver disabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false, modules: new[] { moduleA, moduleB })) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } // Two modules loaded before two requests for same module, // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true, modules: new[] { moduleA, moduleB })) { var requestF = new Request("B.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("B.dll", MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "B.F()"); VerifySignatures(requestG, "B.G()"); } // ... resolver disabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false, modules: new[] { moduleA, moduleB })) { var requestF = new Request("B.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("B.dll", MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } // Two modules loaded after two global requests, // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true)) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()"); VerifySignatures(requestG, "A.G()"); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()", "B.F()"); VerifySignatures(requestG, "A.G()", "B.G()"); } // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false)) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } // Two modules after two requests for same module, // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true)) { var requestF = new Request("A.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("A.dll", MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()"); VerifySignatures(requestG, "A.G()"); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()"); VerifySignatures(requestG, "A.G()"); } // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false)) { var requestF = new Request("A.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("A.dll", MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } } /// <summary> /// Should only handle requests with expected language id or /// default language id or causality breakpoints. /// </summary> [WorkItem(15119, "https://github.com/dotnet/roslyn/issues/15119")] [Fact] public void LanguageId() { var source = @"class C { static void F() { } }"; var bytes = CreateCompilation(source).EmitToArray(); var resolver = Resolver.CSharpResolver; var unknownId = Guid.Parse("F02FB87B-64EC-486E-B039-D4A97F48858C"); var csharpLanguageId = Guid.Parse("3f5162f8-07c6-11d3-9053-00c04fa302a1"); var vbLanguageId = Guid.Parse("3a12d0b8-c26c-11d0-b442-00a0244a1dd2"); var cppLanguageId = Guid.Parse("3a12d0b7-c26c-11d0-b442-00a0244a1dd2"); // Module loaded before requests. var module = new Module(bytes); using (var process = new Process(module)) { var requestDefaultId = new Request(null, MemberSignatureParser.Parse("F"), Guid.Empty); var requestUnknown = new Request(null, MemberSignatureParser.Parse("F"), unknownId); var requestCausalityBreakpoint = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.CausalityBreakpoint); var requestMethodId = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.MethodId); var requestCSharp = new Request(null, MemberSignatureParser.Parse("F"), csharpLanguageId); var requestVB = new Request(null, MemberSignatureParser.Parse("F"), vbLanguageId); var requestCPP = new Request(null, MemberSignatureParser.Parse("F"), cppLanguageId); resolver.EnableResolution(process, requestDefaultId); VerifySignatures(requestDefaultId, "C.F()"); resolver.EnableResolution(process, requestUnknown); VerifySignatures(requestUnknown); resolver.EnableResolution(process, requestCausalityBreakpoint); VerifySignatures(requestCausalityBreakpoint, "C.F()"); resolver.EnableResolution(process, requestMethodId); VerifySignatures(requestMethodId); resolver.EnableResolution(process, requestCSharp); VerifySignatures(requestCSharp, "C.F()"); resolver.EnableResolution(process, requestVB); VerifySignatures(requestVB); resolver.EnableResolution(process, requestCPP); VerifySignatures(requestCPP); } // Module loaded after requests. module = new Module(bytes); using (var process = new Process()) { var requestDefaultId = new Request(null, MemberSignatureParser.Parse("F"), Guid.Empty); var requestUnknown = new Request(null, MemberSignatureParser.Parse("F"), unknownId); var requestCausalityBreakpoint = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.CausalityBreakpoint); var requestMethodId = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.MethodId); var requestCSharp = new Request(null, MemberSignatureParser.Parse("F"), csharpLanguageId); var requestVB = new Request(null, MemberSignatureParser.Parse("F"), vbLanguageId); var requestCPP = new Request(null, MemberSignatureParser.Parse("F"), cppLanguageId); resolver.EnableResolution(process, requestCPP); resolver.EnableResolution(process, requestVB); resolver.EnableResolution(process, requestCSharp); resolver.EnableResolution(process, requestMethodId); resolver.EnableResolution(process, requestCausalityBreakpoint); resolver.EnableResolution(process, requestUnknown); resolver.EnableResolution(process, requestDefaultId); process.AddModule(module); resolver.OnModuleLoad(process, module); VerifySignatures(requestDefaultId, "C.F()"); VerifySignatures(requestUnknown); VerifySignatures(requestCausalityBreakpoint, "C.F()"); VerifySignatures(requestMethodId); VerifySignatures(requestCSharp, "C.F()"); VerifySignatures(requestVB); VerifySignatures(requestCPP); } } [Fact] public void MissingMetadata() { var sourceA = @"class A { static void F1() { } static void F2() { } static void F3() { } static void F4() { } }"; var sourceC = @"class C { static void F1() { } static void F2() { } static void F3() { } static void F4() { } }"; var moduleA = new Module(CreateCompilation(sourceA).EmitToArray(), name: "A.dll"); var moduleB = new Module(default(ImmutableArray<byte>), name: "B.dll"); var moduleC = new Module(CreateCompilation(sourceC).EmitToArray(), name: "C.dll"); using (var process = new Process()) { var resolver = Resolver.CSharpResolver; var requestAll = new Request(null, MemberSignatureParser.Parse("F1")); var requestA = new Request("A.dll", MemberSignatureParser.Parse("F2")); var requestB = new Request("B.dll", MemberSignatureParser.Parse("F3")); var requestC = new Request("C.dll", MemberSignatureParser.Parse("F4")); // Request to all modules. resolver.EnableResolution(process, requestAll); Assert.Equal(0, moduleA.GetMetadataCount); Assert.Equal(0, moduleB.GetMetadataCount); Assert.Equal(0, moduleC.GetMetadataCount); // Load module A (available). process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, moduleA.GetMetadataCount); Assert.Equal(0, moduleB.GetMetadataCount); Assert.Equal(0, moduleC.GetMetadataCount); VerifySignatures(requestAll, "A.F1()"); VerifySignatures(requestA); VerifySignatures(requestB); VerifySignatures(requestC); // Load module B (missing). process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(1, moduleA.GetMetadataCount); Assert.Equal(1, moduleB.GetMetadataCount); Assert.Equal(0, moduleC.GetMetadataCount); VerifySignatures(requestAll, "A.F1()"); VerifySignatures(requestA); VerifySignatures(requestB); VerifySignatures(requestC); // Load module C (available). process.AddModule(moduleC); resolver.OnModuleLoad(process, moduleC); Assert.Equal(1, moduleA.GetMetadataCount); Assert.Equal(1, moduleB.GetMetadataCount); Assert.Equal(1, moduleC.GetMetadataCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA); VerifySignatures(requestB); VerifySignatures(requestC); // Request to module A (available). resolver.EnableResolution(process, requestA); Assert.Equal(2, moduleA.GetMetadataCount); Assert.Equal(1, moduleB.GetMetadataCount); Assert.Equal(1, moduleC.GetMetadataCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA, "A.F2()"); VerifySignatures(requestB); VerifySignatures(requestC); // Request to module B (missing). resolver.EnableResolution(process, requestB); Assert.Equal(2, moduleA.GetMetadataCount); Assert.Equal(2, moduleB.GetMetadataCount); Assert.Equal(1, moduleC.GetMetadataCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA, "A.F2()"); VerifySignatures(requestB); VerifySignatures(requestC); // Request to module C (available). resolver.EnableResolution(process, requestC); Assert.Equal(2, moduleA.GetMetadataCount); Assert.Equal(2, moduleB.GetMetadataCount); Assert.Equal(2, moduleC.GetMetadataCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA, "A.F2()"); VerifySignatures(requestB); VerifySignatures(requestC, "C.F4()"); } } [Fact] public void ModuleName() { var sourceA = @"public struct A { static void F() { } }"; var nameA = GetUniqueName(); var compilationA = CreateCompilation(sourceA, assemblyName: nameA); var imageA = compilationA.EmitToArray(); var refA = AssemblyMetadata.CreateFromImage(imageA).GetReference(); var sourceB = @"class B { static void F(A a) { } static void Main() { } }"; var nameB = GetUniqueName(); var compilationB = CreateCompilation(sourceB, assemblyName: nameB, options: TestOptions.DebugExe, references: new[] { refA }); var imageB = compilationB.EmitToArray(); using (var process = new Process(new Module(imageA, nameA + ".dll"), new Module(imageB, nameB + ".exe"))) { var signature = MemberSignatureParser.Parse("F"); var resolver = Resolver.CSharpResolver; // No module name. var request = new Request("", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "A.F()", "B.F(A)"); // DLL module name, uppercase. request = new Request(nameA.ToUpper() + ".DLL", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "A.F()"); // EXE module name. request = new Request(nameB + ".EXE", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "B.F(A)"); // EXE module name, lowercase. request = new Request(nameB.ToLower() + ".exe", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "B.F(A)"); // EXE module name, no extension. request = new Request(nameB, signature); resolver.EnableResolution(process, request); VerifySignatures(request); } } [Fact] public void Arrays() { var source = @"class A { } class B { static void F(A o) { } static void F(A[] o) { } static void F(A[,,] o) { } static void F(A[,,][] o) { } static void F(A[][,,] o) { } static void F(A[][][] o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F(A)", "B.F(A[])", "B.F(A[,,])", "B.F(A[][,,])", "B.F(A[,,][])", "B.F(A[][][])"); Resolve(process, resolver, "F(A)", "B.F(A)"); Resolve(process, resolver, "F(A[])", "B.F(A[])"); Resolve(process, resolver, "F(A[][])"); Resolve(process, resolver, "F(A[,])"); Resolve(process, resolver, "F(A[,,])", "B.F(A[,,])"); Resolve(process, resolver, "F(A[,,][])", "B.F(A[,,][])"); Resolve(process, resolver, "F(A[][,,])", "B.F(A[][,,])"); Resolve(process, resolver, "F(A[,][,,])"); Resolve(process, resolver, "F(A[][][])", "B.F(A[][][])"); Resolve(process, resolver, "F(A[][][][])"); } } [Fact] public void Pointers() { var source = @"class C { static unsafe void F(int*[] p) { } static unsafe void F(int** q) { } }"; var compilation = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(System.Int32*[])", "C.F(System.Int32**)"); Resolve(process, resolver, "F(int)"); Resolve(process, resolver, "F(int*)"); Resolve(process, resolver, "F(int[])"); Resolve(process, resolver, "F(int*[])", "C.F(System.Int32*[])"); Resolve(process, resolver, "F(int**)", "C.F(System.Int32**)"); Resolve(process, resolver, "F(Int32**)", "C.F(System.Int32**)"); Resolve(process, resolver, "F(C<int*>)"); Resolve(process, resolver, "F(C<int>*)"); } } [Fact] public void Nullable() { var source = @"struct S { void F(S? o) { } static void F(int?[] o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "S.F(System.Nullable<S>)", "S.F(System.Nullable<System.Int32>[])"); Resolve(process, resolver, "F(S)"); Resolve(process, resolver, "F(S?)", "S.F(System.Nullable<S>)"); Resolve(process, resolver, "F(S??)"); Resolve(process, resolver, "F(int?[])", "S.F(System.Nullable<System.Int32>[])"); } } [Fact] public void ByRef() { var source = @"class @ref { } class @out { } class C { static void F(@out a, @ref b) { } static void F(ref @out a, out @ref b) { b = null; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(out, ref)", "C.F(ref out, ref ref)"); Assert.Null(MemberSignatureParser.Parse("F(ref, out)")); Assert.Null(MemberSignatureParser.Parse("F(ref ref, out out)")); Resolve(process, resolver, "F(@out, @ref)", "C.F(out, ref)"); Resolve(process, resolver, "F(@out, out @ref)"); Resolve(process, resolver, "F(ref @out, @ref)"); Resolve(process, resolver, "F(ref @out, out @ref)", "C.F(ref out, ref ref)"); Resolve(process, resolver, "F(out @out, ref @ref)", "C.F(ref out, ref ref)"); } } [Fact] public void Methods() { var source = @"abstract class A { abstract internal object F(); } class B { object F() => null; } class C { static object F() => null; } interface I { object F(); }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F()", "C.F()"); Resolve(process, resolver, "A.F"); Resolve(process, resolver, "B.F", "B.F()"); Resolve(process, resolver, "B.F()", "B.F()"); Resolve(process, resolver, "B.F(object)"); Resolve(process, resolver, "B.F<T>"); Resolve(process, resolver, "C.F", "C.F()"); } } [Fact] public void Properties() { var source = @"abstract class A { abstract internal object P { get; set; } } class B { object P { get; set; } } class C { static object P { get; } } class D { int P { set { } } } interface I { object P { get; set; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "P", "B.get_P()", "B.set_P(System.Object)", "C.get_P()", "D.set_P(System.Int32)"); Resolve(process, resolver, "A.P"); Resolve(process, resolver, "B.P", "B.get_P()", "B.set_P(System.Object)"); Resolve(process, resolver, "B.P()"); Resolve(process, resolver, "B.P(object)"); Resolve(process, resolver, "B.P<T>"); Resolve(process, resolver, "C.P", "C.get_P()"); Resolve(process, resolver, "C.P()"); Resolve(process, resolver, "D.P", "D.set_P(System.Int32)"); Resolve(process, resolver, "D.P()"); Resolve(process, resolver, "D.P(object)"); Resolve(process, resolver, "get_P", "B.get_P()", "C.get_P()"); Resolve(process, resolver, "set_P", "B.set_P(System.Object)", "D.set_P(System.Int32)"); Resolve(process, resolver, "B.get_P()", "B.get_P()"); Resolve(process, resolver, "B.set_P", "B.set_P(System.Object)"); } } [Fact] public void Constructors() { var source = @"class A { static A() { } A() { } A(object o) { } } class B { } class C<T> { } class D { static object A => null; static void B<T>() { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "A", "A..ctor()", "A..ctor(System.Object)", "D.get_A()"); Resolve(process, resolver, "A.A", "A..ctor()", "A..ctor(System.Object)"); Resolve(process, resolver, "B", "B..ctor()"); Resolve(process, resolver, "B<T>", "D.B<T>()"); Resolve(process, resolver, "C", "C<T>..ctor()"); Resolve(process, resolver, "C<T>"); Resolve(process, resolver, "C<T>.C", "C<T>..ctor()"); Assert.Null(MemberSignatureParser.Parse(".ctor")); Assert.Null(MemberSignatureParser.Parse("A..ctor")); } } [Fact] public void GenericMethods() { var source = @"class A { static void F() { } void F<T, U>() { } static void F<T>() { } } class A<T> { static void F() { } void F<U, V>() { } } class B : A<int> { static void F<T>() { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { // Note, Dev14 matches type ignoring type parameters. For instance, // "A<T>.F" will bind to A.F() and A<T>.F(), and "A.F" will bind to A.F() // and A<T>.F. However, Dev14 does expect method type parameters to // match. Here, we expect both type and method parameters to match. var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "A.F", "A.F()"); Resolve(process, resolver, "A.F<U>()", "A.F<T>()"); Resolve(process, resolver, "A.F<T>", "A.F<T>()"); Resolve(process, resolver, "A.F<T, T>", "A.F<T, U>()"); Assert.Null(MemberSignatureParser.Parse("A.F<>()")); Assert.Null(MemberSignatureParser.Parse("A.F<,>()")); Resolve(process, resolver, "A<T>.F", "A<T>.F()"); Resolve(process, resolver, "A<_>.F<_>"); Resolve(process, resolver, "A<_>.F<_, _>", "A<T>.F<U, V>()"); Resolve(process, resolver, "B.F()"); Resolve(process, resolver, "B.F<T>()", "B.F<T>()"); Resolve(process, resolver, "B.F<T, U>()"); } } [Fact] public void Namespaces() { var source = @"namespace N { namespace M { class A<T> { static void F() { } } } } namespace N { class B { static void F() { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "N.B.F()", "N.M.A<T>.F()"); Resolve(process, resolver, "A<T>.F", "N.M.A<T>.F()"); Resolve(process, resolver, "N.A<T>.F"); Resolve(process, resolver, "M.A<T>.F", "N.M.A<T>.F()"); Resolve(process, resolver, "N.M.A<T>.F", "N.M.A<T>.F()"); Resolve(process, resolver, "N.B.F", "N.B.F()"); } } [Fact] public void NestedTypes() { var source = @"class A { class B { static void F() { } } class B<T> { static void F<U>() { } } } class B { static void F() { } } namespace N { class A<T> { class B { static void F<U>() { } } class B<U> { static void F() { } } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { // See comment in GenericMethods regarding differences with Dev14. var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F()", "A.B.F()", "N.A<T>.B<U>.F()"); Resolve(process, resolver, "F<T>", "A.B<T>.F<U>()", "N.A<T>.B.F<U>()"); Resolve(process, resolver, "A.F"); Resolve(process, resolver, "A.B.F", "A.B.F()"); Resolve(process, resolver, "A.B.F<T>"); Resolve(process, resolver, "A.B<T>.F<U>", "A.B<T>.F<U>()"); Resolve(process, resolver, "A<T>.B.F<U>", "N.A<T>.B.F<U>()"); Resolve(process, resolver, "A<T>.B<U>.F", "N.A<T>.B<U>.F()"); Resolve(process, resolver, "B.F", "B.F()", "A.B.F()"); Resolve(process, resolver, "B.F<T>", "N.A<T>.B.F<U>()"); Resolve(process, resolver, "B<T>.F", "N.A<T>.B<U>.F()"); Resolve(process, resolver, "B<T>.F<U>", "A.B<T>.F<U>()"); Assert.Null(MemberSignatureParser.Parse("A+B.F")); Assert.Null(MemberSignatureParser.Parse("A.B`1.F<T>")); } } [Fact] public void NamespacesAndTypes() { var source = @"namespace A.B { class T { } class C { static void F(C c) { } static void F(A.B<T>.C c) { } } } namespace A { class B<T> { internal class C { static void F(C c) { } static void F(A.B.C c) { } } } } class A<T> { internal class B { internal class C { static void F(C c) { } static void F(A.B<T>.C c) { } } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "A.B.C.F(A.B.C)", "A.B.C.F(A.B<A.B.T>.C)", "A.B<T>.C.F(A.B<T>.C)", "A.B<T>.C.F(A.B.C)", "A<T>.B.C.F(A<T>.B.C)", "A<T>.B.C.F(A.B<T>.C)"); Resolve(process, resolver, "F(C)", "A.B.C.F(A.B.C)", "A.B.C.F(A.B<A.B.T>.C)", "A.B<T>.C.F(A.B.C)"); Resolve(process, resolver, "F(B.C)", "A.B.C.F(A.B.C)", "A.B<T>.C.F(A.B.C)"); Resolve(process, resolver, "F(B<T>.C)", "A.B.C.F(A.B<A.B.T>.C)"); Resolve(process, resolver, "A.B.C.F", "A.B.C.F(A.B.C)", "A.B.C.F(A.B<A.B.T>.C)"); Resolve(process, resolver, "A<T>.B.C.F", "A<T>.B.C.F(A<T>.B.C)", "A<T>.B.C.F(A.B<T>.C)"); Resolve(process, resolver, "A.B<T>.C.F", "A.B<T>.C.F(A.B<T>.C)", "A.B<T>.C.F(A.B.C)"); Resolve(process, resolver, "B<T>.C.F(B<T>.C)", "A.B<T>.C.F(A.B<T>.C)"); } } [Fact] public void NamespacesAndTypes_More() { var source = @"namespace A1.B { class C { static void F(C c) { } } } namespace A2 { class B { internal class C { static void F(C c) { } static void F(A1.B.C c) { } } } } class A3 { internal class B { internal class C { static void F(C c) { } static void F(A2.B.C c) { } } } } namespace B { class C { static void F(C c) { } static void F(A3.B.C c) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F(C)", "B.C.F(B.C)", "B.C.F(A3.B.C)", "A1.B.C.F(A1.B.C)", "A2.B.C.F(A2.B.C)", "A2.B.C.F(A1.B.C)", "A3.B.C.F(A3.B.C)", "A3.B.C.F(A2.B.C)"); Resolve(process, resolver, "B.C.F(B.C)", "B.C.F(B.C)", "B.C.F(A3.B.C)", "A1.B.C.F(A1.B.C)", "A2.B.C.F(A2.B.C)", "A2.B.C.F(A1.B.C)", "A3.B.C.F(A3.B.C)", "A3.B.C.F(A2.B.C)"); Resolve(process, resolver, "B.C.F(A1.B.C)", "A1.B.C.F(A1.B.C)", "A2.B.C.F(A1.B.C)"); Resolve(process, resolver, "B.C.F(A2.B.C)", "A2.B.C.F(A2.B.C)", "A3.B.C.F(A2.B.C)"); Resolve(process, resolver, "B.C.F(A3.B.C)", "B.C.F(A3.B.C)", "A3.B.C.F(A3.B.C)"); } } [Fact] public void TypeParameters() { var source = @"class A { class B<T> { static void F<U>(B<T> t) { } static void F<U>(B<U> u) { } } } class A<T> { class B<U> { static void F<V>(T t) { } static void F<V>(A<U> u) { } static void F<V>(B<V> v) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F<T>", "A.B<T>.F<U>(A.B<T>)", "A.B<T>.F<U>(A.B<U>)", "A<T>.B<U>.F<V>(T)", "A<T>.B<U>.F<V>(A<U>)", "A<T>.B<U>.F<V>(A<T>.B<V>)"); Resolve(process, resolver, "B<T>.F<U>", "A.B<T>.F<U>(A.B<T>)", "A.B<T>.F<U>(A.B<U>)", "A<T>.B<U>.F<V>(T)", "A<T>.B<U>.F<V>(A<U>)", "A<T>.B<U>.F<V>(A<T>.B<V>)"); Resolve(process, resolver, "F<T>(B<T>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "F<U>(B<T>)"); // No T in signature to bind to. Resolve(process, resolver, "F<T>(B<U>)"); // No U in signature to bind to. Resolve(process, resolver, "B<X>.F<Y>(B<X>)", "A.B<T>.F<U>(A.B<T>)"); Resolve(process, resolver, "B<X>.F<Y>(B<Y>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "B<U>.F<V>(T)"); // No T in signature to bind to. Resolve(process, resolver, "B<U>.F<V>(A<U>)", "A<T>.B<U>.F<V>(A<U>)"); Resolve(process, resolver, "B<U>.F<V>(B<V>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "B<V>.F<U>(B<U>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "A<X>.B<Y>.F<Z>(X)", "A<T>.B<U>.F<V>(T)"); Resolve(process, resolver, "A<X>.B<Y>.F<Z>(B<Z>)", "A<T>.B<U>.F<V>(A<T>.B<V>)"); } } [Fact] public void DifferentCase_MethodsAndProperties() { var source = @"class A { static void method() { } static void Method(object o) { } object property => null; } class B { static void Method() { } object Property { get; set; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "method", "A.method()"); Resolve(process, resolver, "Method", "A.Method(System.Object)", "B.Method()"); Resolve(process, resolver, "property", "A.get_property()"); Resolve(process, resolver, "Property", "B.get_Property()", "B.set_Property(System.Object)"); Resolve(process, resolver, "PROPERTY"); Resolve(process, resolver, "get_property", "A.get_property()"); Resolve(process, resolver, "GET_PROPERTY"); } } [Fact] public void DifferentCase_NamespacesAndTypes() { var source = @"namespace one.two { class THREE { static void Method(THREE t) { } } } namespace One.Two { class Three { static void Method(Three t) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "Method", "One.Two.Three.Method(One.Two.Three)", "one.two.THREE.Method(one.two.THREE)"); Resolve(process, resolver, "Three.Method", "One.Two.Three.Method(One.Two.Three)"); Resolve(process, resolver, "three.Method"); Resolve(process, resolver, "Method(three)"); Resolve(process, resolver, "THREE.Method(THREE)", "one.two.THREE.Method(one.two.THREE)"); Resolve(process, resolver, "One.Two.Three.Method", "One.Two.Three.Method(One.Two.Three)"); Resolve(process, resolver, "ONE.TWO.THREE.Method"); Resolve(process, resolver, "Method(One.Two.Three)", "One.Two.Three.Method(One.Two.Three)"); Resolve(process, resolver, "Method(one.two.THREE)", "one.two.THREE.Method(one.two.THREE)"); Resolve(process, resolver, "Method(one.two.Three)"); Resolve(process, resolver, "THREE", "one.two.THREE..ctor()"); } } [Fact] public void TypeReferences() { var sourceA = @"public class A<T> { public class B<U> { static void F<V, W>() { } } } namespace N { public class C<T> { } }"; var compilationA = CreateCompilation(sourceA); var bytesA = compilationA.EmitToArray(); var refA = AssemblyMetadata.CreateFromImage(bytesA).GetReference(); var sourceB = @"class D<T> { static void F<U, V>(N.C<A<U>.B<V>[]> b) { } }"; var compilationB = CreateCompilation(sourceB, references: new[] { refA }); var bytesB = compilationB.EmitToArray(); using (var process = new Process(new Module(bytesA), new Module(bytesB))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F<T, U>", "A<T>.B<U>.F<V, W>()", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "F<T, U>(C)"); // No type argument for C<> Resolve(process, resolver, "F<T, U>(C<T>)"); // Incorrect type argument for C<> Resolve(process, resolver, "F<T, U>(C<B<U>>)"); // No array qualifier Resolve(process, resolver, "F<T, U>(C<B<T>[]>)"); // Incorrect type argument for B<> Resolve(process, resolver, "F<T, U>(C<B<U>[]>)", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "F<T, U>(N.C<B<U>[]>)", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "D<X>.F<Y, Z>", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "D<X>.F<Y, Z>(C<A<Y>[]>)"); // No nested type B Resolve(process, resolver, "D<X>.F<Y, Z>(C<A<Y>.B<Z>[]>)", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "D<X>.F<Y, Z>(C<A<Y>.B<Y>[]>)"); // Incorrect type argument for B<>. } } [Fact] public void Keywords_MethodName() { var source = @"namespace @namespace { struct @struct { object @public => 1; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("public")); Assert.Null(MemberSignatureParser.Parse("namespace.@struct.@public")); Assert.Null(MemberSignatureParser.Parse("@namespace.struct.@public")); Assert.Null(MemberSignatureParser.Parse("@[email protected]")); Resolve(process, resolver, "@public", "namespace.struct.get_public()"); Resolve(process, resolver, "@namespace.@struct.@public", "namespace.struct.get_public()"); } } [Fact] public void Keywords_MethodTypeParameter() { var source = @"class @class<@in> { static void F<@out>(@in i, @out o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("F<out>")); Assert.Null(MemberSignatureParser.Parse("F<in>")); Assert.Null(MemberSignatureParser.Parse("class<@in>.F<@out>")); Assert.Null(MemberSignatureParser.Parse("@class<in>.F<@out>")); Assert.Null(MemberSignatureParser.Parse("@class<@in>.F<out>")); Resolve(process, resolver, "F<@out>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "F<@in>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "@class<@in>.F<@out>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "@class<@this>.F<@base>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "@class<T>.F<U>", "class<in>.F<out>(in, out)"); } } [Fact] public void Keywords_ParameterName() { var source = @"namespace @namespace { struct @struct { } } class C { static void F(@namespace.@struct s) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("F(struct)")); Assert.Null(MemberSignatureParser.Parse("F(namespace.@struct)")); Resolve(process, resolver, "F(@struct)", "C.F(namespace.struct)"); Resolve(process, resolver, "F(@namespace.@struct)", "C.F(namespace.struct)"); } } [Fact] public void Keywords_ParameterTypeArgument() { var source = @"class @this { internal class @base { } } class @class<T> { } class C { static void F(@class<@this.@base> c) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("F(@class<base>)")); Assert.Null(MemberSignatureParser.Parse("F(@class<this.@base>)")); Assert.Null(MemberSignatureParser.Parse("F(@class<@this.base>)")); Resolve(process, resolver, "F(@class<@base>)", "C.F(class<this.base>)"); Resolve(process, resolver, "F(@class<@this.@base>)", "C.F(class<this.base>)"); } } [Fact] public void EscapedNames() { var source = @"class @object { } class Object { } class C { static void F(@object o) { } static void F(Object o) { } static void F(object o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(object)", "C.F(Object)", "C.F(System.Object)"); Resolve(process, resolver, "F(object)", "C.F(System.Object)"); Resolve(process, resolver, "F(Object)", "C.F(Object)", "C.F(System.Object)"); Resolve(process, resolver, "F(System.Object)", "C.F(System.Object)"); Resolve(process, resolver, "F(@object)", "C.F(object)"); Resolve(process, resolver, "F(@Object)", "C.F(Object)", "C.F(System.Object)"); } } [Fact] public void SpecialTypes() { var source = @"class C<T1, T2, T3, T4> { } class C { static void F(bool a, char b, sbyte c, byte d) { } static void F(short a, ushort b, int c, uint d) { } static void F(C<uint, long, ulong, float> o) { } static void F(C<double, string, object, decimal> o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F(bool, char, sbyte, byte)", "C.F(System.Boolean, System.Char, System.SByte, System.Byte)"); Resolve(process, resolver, "F(System.Int16, System.UInt16, System.Int32, System.UInt32)", "C.F(System.Int16, System.UInt16, System.Int32, System.UInt32)"); Resolve(process, resolver, "F(C<UInt32, Int64, UInt64, Single>)", "C.F(C<System.UInt32, System.Int64, System.UInt64, System.Single>)"); Resolve(process, resolver, "F(C<double, string, object, decimal>)", "C.F(C<System.Double, System.String, System.Object, System.Decimal>)"); Resolve(process, resolver, "F(bool, char, sbyte)"); Resolve(process, resolver, "F(C<double, string, object, decimal, bool>)"); } } [Fact] public void SpecialTypes_More() { var source = @"class C { static void F(System.IntPtr p) { } static void F(System.UIntPtr p) { } static void F(System.TypedReference r) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F(object)"); Resolve(process, resolver, "F(IntPtr)", "C.F(System.IntPtr)"); Resolve(process, resolver, "F(UIntPtr)", "C.F(System.UIntPtr)"); Resolve(process, resolver, "F(TypedReference)", "C.F(System.TypedReference)"); } } // Binding to "dynamic" type refs is not supported. // This is consistent with Dev14. [Fact] public void Dynamic() { var source = @"class C<T> { } class C { static void F(dynamic d) { } static void F(C<dynamic[]> d) { } }"; var compilation = CreateCompilation(source, references: new[] { CSharpRef }); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(System.Object)", "C.F(C<System.Object[]>)"); Resolve(process, resolver, "F(object)", "C.F(System.Object)"); Resolve(process, resolver, "F(C<object[]>)", "C.F(C<System.Object[]>)"); Resolve(process, resolver, "F(dynamic)"); Resolve(process, resolver, "F(C<dynamic[]>)"); } } [Fact] public void Iterator() { var source = @"class C { static System.Collections.IEnumerable F() { yield break; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F()"); } } [Fact] public void Async() { var source = @"using System.Threading.Tasks; class C { static async Task F() { await Task.Delay(0); } }"; var compilation = CreateCompilationWithMscorlib46(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F()"); } } [Fact(Skip = "global:: not supported")] public void Global() { var source = @"class C { static void F(N.C o) { } static void F(global::C o) { } } namespace N { class C { static void F(N.C o) { } static void F(global::C o) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "C.F(C)", "C.F(N.C)", "C.F(C)", "N.C.F(N.C)", "N.C.F(C)"); Resolve(process, resolver, "C.F(N.C)", "C.F(N.C)", "N.C.F(N.C)"); Resolve(process, resolver, "global::C.F(C)", "C.F(N.C)", "C.F(C)"); // Dev14 does not bind global:: Resolve(process, resolver, "C.F(global::C)", "C.F(C)", "N.C.F(C)"); // Dev14 does not bind global:: } } // Since MetadataDecoder does not load referenced // assemblies, the arity or a type reference is determined // by the type name: e.g.: "C`2". If the arity from the name is // different from the number of generic type arguments, the // method signature containing the type reference is ignored. [Fact] public void UnexpectedArity() { var sourceA = @".class public A<T> { }"; var sourceB = @"class B { static void F(object o) { } static void F(A<object> a) { } }"; ImmutableArray<byte> bytesA; ImmutableArray<byte> pdbA; EmitILToArray(sourceA, appendDefaultHeader: true, includePdb: false, assemblyBytes: out bytesA, pdbBytes: out pdbA); var refA = AssemblyMetadata.CreateFromImage(bytesA).GetReference(); var compilationB = CreateCompilation(sourceB, references: new[] { refA }); var bytesB = compilationB.EmitToArray(); using (var process = new Process(new Module(bytesB))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F(System.Object)", "B.F([notsupported])"); Resolve(process, resolver, "F(A<object>)"); } } /// <summary> /// Should not resolve to P/Invoke methods. /// </summary> [Fact] public void PInvoke() { var source = @"using System.Runtime.InteropServices; class A { [DllImport(""extern.dll"")] public static extern int F(); } class B { public static int F() => 0; }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F()"); } } private static void Resolve(Process process, Resolver resolver, string str, params string[] expectedSignatures) { var signature = MemberSignatureParser.Parse(str); Assert.NotNull(signature); Resolve(process, resolver, signature, expectedSignatures); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using Xunit; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { public class CSharpFunctionResolverTests : FunctionResolverTestBase { [Fact] public void OnLoad() { var source = @"class C { static void F(object o) { } object F() => null; }"; var compilation = CreateCompilation(source); var module = new Module(compilation.EmitToArray()); using (var process = new Process()) { var resolver = Resolver.CSharpResolver; var request = new Request(null, MemberSignatureParser.Parse("C.F")); resolver.EnableResolution(process, request); VerifySignatures(request); process.AddModule(module); resolver.OnModuleLoad(process, module); VerifySignatures(request, "C.F(System.Object)", "C.F()"); } } /// <summary> /// ShouldEnableFunctionResolver should not be called /// until the first module is available for binding. /// </summary> [Fact] public void ShouldEnableFunctionResolver() { var sourceA = @"class A { static void F() { } static void G() { } }"; var sourceB = @"class B { static void F() { } static void G() { } }"; var bytesA = CreateCompilation(sourceA).EmitToArray(); var bytesB = CreateCompilation(sourceB).EmitToArray(); var resolver = Resolver.CSharpResolver; // Two modules loaded before two global requests, // ... resolver enabled. var moduleA = new Module(bytesA, name: "A.dll"); var moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true, modules: new[] { moduleA, moduleB })) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()", "B.F()"); VerifySignatures(requestG, "A.G()", "B.G()"); } // ... resolver disabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false, modules: new[] { moduleA, moduleB })) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } // Two modules loaded before two requests for same module, // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true, modules: new[] { moduleA, moduleB })) { var requestF = new Request("B.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("B.dll", MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "B.F()"); VerifySignatures(requestG, "B.G()"); } // ... resolver disabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false, modules: new[] { moduleA, moduleB })) { var requestF = new Request("B.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("B.dll", MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } // Two modules loaded after two global requests, // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true)) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()"); VerifySignatures(requestG, "A.G()"); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()", "B.F()"); VerifySignatures(requestG, "A.G()", "B.G()"); } // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false)) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } // Two modules after two requests for same module, // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true)) { var requestF = new Request("A.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("A.dll", MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()"); VerifySignatures(requestG, "A.G()"); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()"); VerifySignatures(requestG, "A.G()"); } // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false)) { var requestF = new Request("A.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("A.dll", MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } } /// <summary> /// Should only handle requests with expected language id or /// default language id or causality breakpoints. /// </summary> [WorkItem(15119, "https://github.com/dotnet/roslyn/issues/15119")] [Fact] public void LanguageId() { var source = @"class C { static void F() { } }"; var bytes = CreateCompilation(source).EmitToArray(); var resolver = Resolver.CSharpResolver; var unknownId = Guid.Parse("F02FB87B-64EC-486E-B039-D4A97F48858C"); var csharpLanguageId = Guid.Parse("3f5162f8-07c6-11d3-9053-00c04fa302a1"); var vbLanguageId = Guid.Parse("3a12d0b8-c26c-11d0-b442-00a0244a1dd2"); var cppLanguageId = Guid.Parse("3a12d0b7-c26c-11d0-b442-00a0244a1dd2"); // Module loaded before requests. var module = new Module(bytes); using (var process = new Process(module)) { var requestDefaultId = new Request(null, MemberSignatureParser.Parse("F"), Guid.Empty); var requestUnknown = new Request(null, MemberSignatureParser.Parse("F"), unknownId); var requestCausalityBreakpoint = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.CausalityBreakpoint); var requestMethodId = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.MethodId); var requestCSharp = new Request(null, MemberSignatureParser.Parse("F"), csharpLanguageId); var requestVB = new Request(null, MemberSignatureParser.Parse("F"), vbLanguageId); var requestCPP = new Request(null, MemberSignatureParser.Parse("F"), cppLanguageId); resolver.EnableResolution(process, requestDefaultId); VerifySignatures(requestDefaultId, "C.F()"); resolver.EnableResolution(process, requestUnknown); VerifySignatures(requestUnknown); resolver.EnableResolution(process, requestCausalityBreakpoint); VerifySignatures(requestCausalityBreakpoint, "C.F()"); resolver.EnableResolution(process, requestMethodId); VerifySignatures(requestMethodId); resolver.EnableResolution(process, requestCSharp); VerifySignatures(requestCSharp, "C.F()"); resolver.EnableResolution(process, requestVB); VerifySignatures(requestVB); resolver.EnableResolution(process, requestCPP); VerifySignatures(requestCPP); } // Module loaded after requests. module = new Module(bytes); using (var process = new Process()) { var requestDefaultId = new Request(null, MemberSignatureParser.Parse("F"), Guid.Empty); var requestUnknown = new Request(null, MemberSignatureParser.Parse("F"), unknownId); var requestCausalityBreakpoint = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.CausalityBreakpoint); var requestMethodId = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.MethodId); var requestCSharp = new Request(null, MemberSignatureParser.Parse("F"), csharpLanguageId); var requestVB = new Request(null, MemberSignatureParser.Parse("F"), vbLanguageId); var requestCPP = new Request(null, MemberSignatureParser.Parse("F"), cppLanguageId); resolver.EnableResolution(process, requestCPP); resolver.EnableResolution(process, requestVB); resolver.EnableResolution(process, requestCSharp); resolver.EnableResolution(process, requestMethodId); resolver.EnableResolution(process, requestCausalityBreakpoint); resolver.EnableResolution(process, requestUnknown); resolver.EnableResolution(process, requestDefaultId); process.AddModule(module); resolver.OnModuleLoad(process, module); VerifySignatures(requestDefaultId, "C.F()"); VerifySignatures(requestUnknown); VerifySignatures(requestCausalityBreakpoint, "C.F()"); VerifySignatures(requestMethodId); VerifySignatures(requestCSharp, "C.F()"); VerifySignatures(requestVB); VerifySignatures(requestCPP); } } [Fact] public void MissingMetadata() { var sourceA = @"class A { static void F1() { } static void F2() { } static void F3() { } static void F4() { } }"; var sourceC = @"class C { static void F1() { } static void F2() { } static void F3() { } static void F4() { } }"; var moduleA = new Module(CreateCompilation(sourceA).EmitToArray(), name: "A.dll"); var moduleB = new Module(default(ImmutableArray<byte>), name: "B.dll"); var moduleC = new Module(CreateCompilation(sourceC).EmitToArray(), name: "C.dll"); using (var process = new Process()) { var resolver = Resolver.CSharpResolver; var requestAll = new Request(null, MemberSignatureParser.Parse("F1")); var requestA = new Request("A.dll", MemberSignatureParser.Parse("F2")); var requestB = new Request("B.dll", MemberSignatureParser.Parse("F3")); var requestC = new Request("C.dll", MemberSignatureParser.Parse("F4")); // Request to all modules. resolver.EnableResolution(process, requestAll); Assert.Equal(0, moduleA.MetadataAccessCount); Assert.Equal(0, moduleB.MetadataAccessCount); Assert.Equal(0, moduleC.MetadataAccessCount); // Load module A (available). process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, moduleA.MetadataAccessCount); Assert.Equal(0, moduleB.MetadataAccessCount); Assert.Equal(0, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()"); VerifySignatures(requestA); VerifySignatures(requestB); VerifySignatures(requestC); // Load module B (missing). process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(1, moduleA.MetadataAccessCount); Assert.Equal(1, moduleB.MetadataAccessCount); Assert.Equal(0, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()"); VerifySignatures(requestA); VerifySignatures(requestB); VerifySignatures(requestC); // Load module C (available). process.AddModule(moduleC); resolver.OnModuleLoad(process, moduleC); Assert.Equal(1, moduleA.MetadataAccessCount); Assert.Equal(1, moduleB.MetadataAccessCount); Assert.Equal(1, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA); VerifySignatures(requestB); VerifySignatures(requestC); // Request to module A (available). resolver.EnableResolution(process, requestA); Assert.Equal(2, moduleA.MetadataAccessCount); Assert.Equal(1, moduleB.MetadataAccessCount); Assert.Equal(1, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA, "A.F2()"); VerifySignatures(requestB); VerifySignatures(requestC); // Request to module B (missing). resolver.EnableResolution(process, requestB); Assert.Equal(2, moduleA.MetadataAccessCount); Assert.Equal(2, moduleB.MetadataAccessCount); Assert.Equal(1, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA, "A.F2()"); VerifySignatures(requestB); VerifySignatures(requestC); // Request to module C (available). resolver.EnableResolution(process, requestC); Assert.Equal(2, moduleA.MetadataAccessCount); Assert.Equal(2, moduleB.MetadataAccessCount); Assert.Equal(2, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA, "A.F2()"); VerifySignatures(requestB); VerifySignatures(requestC, "C.F4()"); } } [Fact] public void ModuleName() { var sourceA = @"public struct A { static void F() { } }"; var nameA = GetUniqueName(); var compilationA = CreateCompilation(sourceA, assemblyName: nameA); var imageA = compilationA.EmitToArray(); var refA = AssemblyMetadata.CreateFromImage(imageA).GetReference(); var sourceB = @"class B { static void F(A a) { } static void Main() { } }"; var nameB = GetUniqueName(); var compilationB = CreateCompilation(sourceB, assemblyName: nameB, options: TestOptions.DebugExe, references: new[] { refA }); var imageB = compilationB.EmitToArray(); using (var process = new Process(new Module(imageA, nameA + ".dll"), new Module(imageB, nameB + ".exe"))) { var signature = MemberSignatureParser.Parse("F"); var resolver = Resolver.CSharpResolver; // No module name. var request = new Request("", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "A.F()", "B.F(A)"); // DLL module name, uppercase. request = new Request(nameA.ToUpper() + ".DLL", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "A.F()"); // EXE module name. request = new Request(nameB + ".EXE", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "B.F(A)"); // EXE module name, lowercase. request = new Request(nameB.ToLower() + ".exe", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "B.F(A)"); // EXE module name, no extension. request = new Request(nameB, signature); resolver.EnableResolution(process, request); VerifySignatures(request); } } [Fact] [WorkItem(55475, "https://github.com/dotnet/roslyn/issues/55475")] public void BadMetadata() { var source = "class A { static void F() {} }"; var compilation = CreateCompilation(source); using var process = new Process( new Module(compilation.EmitToArray()), new Module(metadata: default), // emulates failure of the debugger to retrieve metadata new Module(metadata: TestResources.MetadataTests.Invalid.IncorrectCustomAssemblyTableSize_TooManyMethodSpecs.ToImmutableArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "A.F()"); } [Fact] public void Arrays() { var source = @"class A { } class B { static void F(A o) { } static void F(A[] o) { } static void F(A[,,] o) { } static void F(A[,,][] o) { } static void F(A[][,,] o) { } static void F(A[][][] o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F(A)", "B.F(A[])", "B.F(A[,,])", "B.F(A[][,,])", "B.F(A[,,][])", "B.F(A[][][])"); Resolve(process, resolver, "F(A)", "B.F(A)"); Resolve(process, resolver, "F(A[])", "B.F(A[])"); Resolve(process, resolver, "F(A[][])"); Resolve(process, resolver, "F(A[,])"); Resolve(process, resolver, "F(A[,,])", "B.F(A[,,])"); Resolve(process, resolver, "F(A[,,][])", "B.F(A[,,][])"); Resolve(process, resolver, "F(A[][,,])", "B.F(A[][,,])"); Resolve(process, resolver, "F(A[,][,,])"); Resolve(process, resolver, "F(A[][][])", "B.F(A[][][])"); Resolve(process, resolver, "F(A[][][][])"); } } [Fact] public void Pointers() { var source = @"class C { static unsafe void F(int*[] p) { } static unsafe void F(int** q) { } }"; var compilation = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(System.Int32*[])", "C.F(System.Int32**)"); Resolve(process, resolver, "F(int)"); Resolve(process, resolver, "F(int*)"); Resolve(process, resolver, "F(int[])"); Resolve(process, resolver, "F(int*[])", "C.F(System.Int32*[])"); Resolve(process, resolver, "F(int**)", "C.F(System.Int32**)"); Resolve(process, resolver, "F(Int32**)", "C.F(System.Int32**)"); Resolve(process, resolver, "F(C<int*>)"); Resolve(process, resolver, "F(C<int>*)"); } } [Fact] public void Nullable() { var source = @"struct S { void F(S? o) { } static void F(int?[] o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "S.F(System.Nullable<S>)", "S.F(System.Nullable<System.Int32>[])"); Resolve(process, resolver, "F(S)"); Resolve(process, resolver, "F(S?)", "S.F(System.Nullable<S>)"); Resolve(process, resolver, "F(S??)"); Resolve(process, resolver, "F(int?[])", "S.F(System.Nullable<System.Int32>[])"); } } [Fact] public void ByRef() { var source = @"class @ref { } class @out { } class C { static void F(@out a, @ref b) { } static void F(ref @out a, out @ref b) { b = null; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(out, ref)", "C.F(ref out, ref ref)"); Assert.Null(MemberSignatureParser.Parse("F(ref, out)")); Assert.Null(MemberSignatureParser.Parse("F(ref ref, out out)")); Resolve(process, resolver, "F(@out, @ref)", "C.F(out, ref)"); Resolve(process, resolver, "F(@out, out @ref)"); Resolve(process, resolver, "F(ref @out, @ref)"); Resolve(process, resolver, "F(ref @out, out @ref)", "C.F(ref out, ref ref)"); Resolve(process, resolver, "F(out @out, ref @ref)", "C.F(ref out, ref ref)"); } } [Fact] public void Methods() { var source = @"abstract class A { abstract internal object F(); } class B { object F() => null; } class C { static object F() => null; } interface I { object F(); }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F()", "C.F()"); Resolve(process, resolver, "A.F"); Resolve(process, resolver, "B.F", "B.F()"); Resolve(process, resolver, "B.F()", "B.F()"); Resolve(process, resolver, "B.F(object)"); Resolve(process, resolver, "B.F<T>"); Resolve(process, resolver, "C.F", "C.F()"); } } [Fact] public void Properties() { var source = @"abstract class A { abstract internal object P { get; set; } } class B { object P { get; set; } } class C { static object P { get; } } class D { int P { set { } } } interface I { object P { get; set; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "P", "B.get_P()", "B.set_P(System.Object)", "C.get_P()", "D.set_P(System.Int32)"); Resolve(process, resolver, "A.P"); Resolve(process, resolver, "B.P", "B.get_P()", "B.set_P(System.Object)"); Resolve(process, resolver, "B.P()"); Resolve(process, resolver, "B.P(object)"); Resolve(process, resolver, "B.P<T>"); Resolve(process, resolver, "C.P", "C.get_P()"); Resolve(process, resolver, "C.P()"); Resolve(process, resolver, "D.P", "D.set_P(System.Int32)"); Resolve(process, resolver, "D.P()"); Resolve(process, resolver, "D.P(object)"); Resolve(process, resolver, "get_P", "B.get_P()", "C.get_P()"); Resolve(process, resolver, "set_P", "B.set_P(System.Object)", "D.set_P(System.Int32)"); Resolve(process, resolver, "B.get_P()", "B.get_P()"); Resolve(process, resolver, "B.set_P", "B.set_P(System.Object)"); } } [Fact] public void Constructors() { var source = @"class A { static A() { } A() { } A(object o) { } } class B { } class C<T> { } class D { static object A => null; static void B<T>() { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "A", "A..ctor()", "A..ctor(System.Object)", "D.get_A()"); Resolve(process, resolver, "A.A", "A..ctor()", "A..ctor(System.Object)"); Resolve(process, resolver, "B", "B..ctor()"); Resolve(process, resolver, "B<T>", "D.B<T>()"); Resolve(process, resolver, "C", "C<T>..ctor()"); Resolve(process, resolver, "C<T>"); Resolve(process, resolver, "C<T>.C", "C<T>..ctor()"); Assert.Null(MemberSignatureParser.Parse(".ctor")); Assert.Null(MemberSignatureParser.Parse("A..ctor")); } } [Fact] public void GenericMethods() { var source = @"class A { static void F() { } void F<T, U>() { } static void F<T>() { } } class A<T> { static void F() { } void F<U, V>() { } } class B : A<int> { static void F<T>() { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { // Note, Dev14 matches type ignoring type parameters. For instance, // "A<T>.F" will bind to A.F() and A<T>.F(), and "A.F" will bind to A.F() // and A<T>.F. However, Dev14 does expect method type parameters to // match. Here, we expect both type and method parameters to match. var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "A.F", "A.F()"); Resolve(process, resolver, "A.F<U>()", "A.F<T>()"); Resolve(process, resolver, "A.F<T>", "A.F<T>()"); Resolve(process, resolver, "A.F<T, T>", "A.F<T, U>()"); Assert.Null(MemberSignatureParser.Parse("A.F<>()")); Assert.Null(MemberSignatureParser.Parse("A.F<,>()")); Resolve(process, resolver, "A<T>.F", "A<T>.F()"); Resolve(process, resolver, "A<_>.F<_>"); Resolve(process, resolver, "A<_>.F<_, _>", "A<T>.F<U, V>()"); Resolve(process, resolver, "B.F()"); Resolve(process, resolver, "B.F<T>()", "B.F<T>()"); Resolve(process, resolver, "B.F<T, U>()"); } } [Fact] public void Namespaces() { var source = @"namespace N { namespace M { class A<T> { static void F() { } } } } namespace N { class B { static void F() { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "N.B.F()", "N.M.A<T>.F()"); Resolve(process, resolver, "A<T>.F", "N.M.A<T>.F()"); Resolve(process, resolver, "N.A<T>.F"); Resolve(process, resolver, "M.A<T>.F", "N.M.A<T>.F()"); Resolve(process, resolver, "N.M.A<T>.F", "N.M.A<T>.F()"); Resolve(process, resolver, "N.B.F", "N.B.F()"); } } [Fact] public void NestedTypes() { var source = @"class A { class B { static void F() { } } class B<T> { static void F<U>() { } } } class B { static void F() { } } namespace N { class A<T> { class B { static void F<U>() { } } class B<U> { static void F() { } } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { // See comment in GenericMethods regarding differences with Dev14. var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F()", "A.B.F()", "N.A<T>.B<U>.F()"); Resolve(process, resolver, "F<T>", "A.B<T>.F<U>()", "N.A<T>.B.F<U>()"); Resolve(process, resolver, "A.F"); Resolve(process, resolver, "A.B.F", "A.B.F()"); Resolve(process, resolver, "A.B.F<T>"); Resolve(process, resolver, "A.B<T>.F<U>", "A.B<T>.F<U>()"); Resolve(process, resolver, "A<T>.B.F<U>", "N.A<T>.B.F<U>()"); Resolve(process, resolver, "A<T>.B<U>.F", "N.A<T>.B<U>.F()"); Resolve(process, resolver, "B.F", "B.F()", "A.B.F()"); Resolve(process, resolver, "B.F<T>", "N.A<T>.B.F<U>()"); Resolve(process, resolver, "B<T>.F", "N.A<T>.B<U>.F()"); Resolve(process, resolver, "B<T>.F<U>", "A.B<T>.F<U>()"); Assert.Null(MemberSignatureParser.Parse("A+B.F")); Assert.Null(MemberSignatureParser.Parse("A.B`1.F<T>")); } } [Fact] public void NamespacesAndTypes() { var source = @"namespace A.B { class T { } class C { static void F(C c) { } static void F(A.B<T>.C c) { } } } namespace A { class B<T> { internal class C { static void F(C c) { } static void F(A.B.C c) { } } } } class A<T> { internal class B { internal class C { static void F(C c) { } static void F(A.B<T>.C c) { } } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "A.B.C.F(A.B.C)", "A.B.C.F(A.B<A.B.T>.C)", "A.B<T>.C.F(A.B<T>.C)", "A.B<T>.C.F(A.B.C)", "A<T>.B.C.F(A<T>.B.C)", "A<T>.B.C.F(A.B<T>.C)"); Resolve(process, resolver, "F(C)", "A.B.C.F(A.B.C)", "A.B.C.F(A.B<A.B.T>.C)", "A.B<T>.C.F(A.B.C)"); Resolve(process, resolver, "F(B.C)", "A.B.C.F(A.B.C)", "A.B<T>.C.F(A.B.C)"); Resolve(process, resolver, "F(B<T>.C)", "A.B.C.F(A.B<A.B.T>.C)"); Resolve(process, resolver, "A.B.C.F", "A.B.C.F(A.B.C)", "A.B.C.F(A.B<A.B.T>.C)"); Resolve(process, resolver, "A<T>.B.C.F", "A<T>.B.C.F(A<T>.B.C)", "A<T>.B.C.F(A.B<T>.C)"); Resolve(process, resolver, "A.B<T>.C.F", "A.B<T>.C.F(A.B<T>.C)", "A.B<T>.C.F(A.B.C)"); Resolve(process, resolver, "B<T>.C.F(B<T>.C)", "A.B<T>.C.F(A.B<T>.C)"); } } [Fact] public void NamespacesAndTypes_More() { var source = @"namespace A1.B { class C { static void F(C c) { } } } namespace A2 { class B { internal class C { static void F(C c) { } static void F(A1.B.C c) { } } } } class A3 { internal class B { internal class C { static void F(C c) { } static void F(A2.B.C c) { } } } } namespace B { class C { static void F(C c) { } static void F(A3.B.C c) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F(C)", "B.C.F(B.C)", "B.C.F(A3.B.C)", "A1.B.C.F(A1.B.C)", "A2.B.C.F(A2.B.C)", "A2.B.C.F(A1.B.C)", "A3.B.C.F(A3.B.C)", "A3.B.C.F(A2.B.C)"); Resolve(process, resolver, "B.C.F(B.C)", "B.C.F(B.C)", "B.C.F(A3.B.C)", "A1.B.C.F(A1.B.C)", "A2.B.C.F(A2.B.C)", "A2.B.C.F(A1.B.C)", "A3.B.C.F(A3.B.C)", "A3.B.C.F(A2.B.C)"); Resolve(process, resolver, "B.C.F(A1.B.C)", "A1.B.C.F(A1.B.C)", "A2.B.C.F(A1.B.C)"); Resolve(process, resolver, "B.C.F(A2.B.C)", "A2.B.C.F(A2.B.C)", "A3.B.C.F(A2.B.C)"); Resolve(process, resolver, "B.C.F(A3.B.C)", "B.C.F(A3.B.C)", "A3.B.C.F(A3.B.C)"); } } [Fact] public void TypeParameters() { var source = @"class A { class B<T> { static void F<U>(B<T> t) { } static void F<U>(B<U> u) { } } } class A<T> { class B<U> { static void F<V>(T t) { } static void F<V>(A<U> u) { } static void F<V>(B<V> v) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F<T>", "A.B<T>.F<U>(A.B<T>)", "A.B<T>.F<U>(A.B<U>)", "A<T>.B<U>.F<V>(T)", "A<T>.B<U>.F<V>(A<U>)", "A<T>.B<U>.F<V>(A<T>.B<V>)"); Resolve(process, resolver, "B<T>.F<U>", "A.B<T>.F<U>(A.B<T>)", "A.B<T>.F<U>(A.B<U>)", "A<T>.B<U>.F<V>(T)", "A<T>.B<U>.F<V>(A<U>)", "A<T>.B<U>.F<V>(A<T>.B<V>)"); Resolve(process, resolver, "F<T>(B<T>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "F<U>(B<T>)"); // No T in signature to bind to. Resolve(process, resolver, "F<T>(B<U>)"); // No U in signature to bind to. Resolve(process, resolver, "B<X>.F<Y>(B<X>)", "A.B<T>.F<U>(A.B<T>)"); Resolve(process, resolver, "B<X>.F<Y>(B<Y>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "B<U>.F<V>(T)"); // No T in signature to bind to. Resolve(process, resolver, "B<U>.F<V>(A<U>)", "A<T>.B<U>.F<V>(A<U>)"); Resolve(process, resolver, "B<U>.F<V>(B<V>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "B<V>.F<U>(B<U>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "A<X>.B<Y>.F<Z>(X)", "A<T>.B<U>.F<V>(T)"); Resolve(process, resolver, "A<X>.B<Y>.F<Z>(B<Z>)", "A<T>.B<U>.F<V>(A<T>.B<V>)"); } } [Fact] public void DifferentCase_MethodsAndProperties() { var source = @"class A { static void method() { } static void Method(object o) { } object property => null; } class B { static void Method() { } object Property { get; set; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "method", "A.method()"); Resolve(process, resolver, "Method", "A.Method(System.Object)", "B.Method()"); Resolve(process, resolver, "property", "A.get_property()"); Resolve(process, resolver, "Property", "B.get_Property()", "B.set_Property(System.Object)"); Resolve(process, resolver, "PROPERTY"); Resolve(process, resolver, "get_property", "A.get_property()"); Resolve(process, resolver, "GET_PROPERTY"); } } [Fact] public void DifferentCase_NamespacesAndTypes() { var source = @"namespace one.two { class THREE { static void Method(THREE t) { } } } namespace One.Two { class Three { static void Method(Three t) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "Method", "One.Two.Three.Method(One.Two.Three)", "one.two.THREE.Method(one.two.THREE)"); Resolve(process, resolver, "Three.Method", "One.Two.Three.Method(One.Two.Three)"); Resolve(process, resolver, "three.Method"); Resolve(process, resolver, "Method(three)"); Resolve(process, resolver, "THREE.Method(THREE)", "one.two.THREE.Method(one.two.THREE)"); Resolve(process, resolver, "One.Two.Three.Method", "One.Two.Three.Method(One.Two.Three)"); Resolve(process, resolver, "ONE.TWO.THREE.Method"); Resolve(process, resolver, "Method(One.Two.Three)", "One.Two.Three.Method(One.Two.Three)"); Resolve(process, resolver, "Method(one.two.THREE)", "one.two.THREE.Method(one.two.THREE)"); Resolve(process, resolver, "Method(one.two.Three)"); Resolve(process, resolver, "THREE", "one.two.THREE..ctor()"); } } [Fact] public void TypeReferences() { var sourceA = @"public class A<T> { public class B<U> { static void F<V, W>() { } } } namespace N { public class C<T> { } }"; var compilationA = CreateCompilation(sourceA); var bytesA = compilationA.EmitToArray(); var refA = AssemblyMetadata.CreateFromImage(bytesA).GetReference(); var sourceB = @"class D<T> { static void F<U, V>(N.C<A<U>.B<V>[]> b) { } }"; var compilationB = CreateCompilation(sourceB, references: new[] { refA }); var bytesB = compilationB.EmitToArray(); using (var process = new Process(new Module(bytesA), new Module(bytesB))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F<T, U>", "A<T>.B<U>.F<V, W>()", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "F<T, U>(C)"); // No type argument for C<> Resolve(process, resolver, "F<T, U>(C<T>)"); // Incorrect type argument for C<> Resolve(process, resolver, "F<T, U>(C<B<U>>)"); // No array qualifier Resolve(process, resolver, "F<T, U>(C<B<T>[]>)"); // Incorrect type argument for B<> Resolve(process, resolver, "F<T, U>(C<B<U>[]>)", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "F<T, U>(N.C<B<U>[]>)", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "D<X>.F<Y, Z>", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "D<X>.F<Y, Z>(C<A<Y>[]>)"); // No nested type B Resolve(process, resolver, "D<X>.F<Y, Z>(C<A<Y>.B<Z>[]>)", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "D<X>.F<Y, Z>(C<A<Y>.B<Y>[]>)"); // Incorrect type argument for B<>. } } [Fact] public void Keywords_MethodName() { var source = @"namespace @namespace { struct @struct { object @public => 1; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("public")); Assert.Null(MemberSignatureParser.Parse("namespace.@struct.@public")); Assert.Null(MemberSignatureParser.Parse("@namespace.struct.@public")); Assert.Null(MemberSignatureParser.Parse("@[email protected]")); Resolve(process, resolver, "@public", "namespace.struct.get_public()"); Resolve(process, resolver, "@namespace.@struct.@public", "namespace.struct.get_public()"); } } [Fact] public void Keywords_MethodTypeParameter() { var source = @"class @class<@in> { static void F<@out>(@in i, @out o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("F<out>")); Assert.Null(MemberSignatureParser.Parse("F<in>")); Assert.Null(MemberSignatureParser.Parse("class<@in>.F<@out>")); Assert.Null(MemberSignatureParser.Parse("@class<in>.F<@out>")); Assert.Null(MemberSignatureParser.Parse("@class<@in>.F<out>")); Resolve(process, resolver, "F<@out>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "F<@in>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "@class<@in>.F<@out>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "@class<@this>.F<@base>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "@class<T>.F<U>", "class<in>.F<out>(in, out)"); } } [Fact] public void Keywords_ParameterName() { var source = @"namespace @namespace { struct @struct { } } class C { static void F(@namespace.@struct s) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("F(struct)")); Assert.Null(MemberSignatureParser.Parse("F(namespace.@struct)")); Resolve(process, resolver, "F(@struct)", "C.F(namespace.struct)"); Resolve(process, resolver, "F(@namespace.@struct)", "C.F(namespace.struct)"); } } [Fact] public void Keywords_ParameterTypeArgument() { var source = @"class @this { internal class @base { } } class @class<T> { } class C { static void F(@class<@this.@base> c) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("F(@class<base>)")); Assert.Null(MemberSignatureParser.Parse("F(@class<this.@base>)")); Assert.Null(MemberSignatureParser.Parse("F(@class<@this.base>)")); Resolve(process, resolver, "F(@class<@base>)", "C.F(class<this.base>)"); Resolve(process, resolver, "F(@class<@this.@base>)", "C.F(class<this.base>)"); } } [Fact] public void EscapedNames() { var source = @"class @object { } class Object { } class C { static void F(@object o) { } static void F(Object o) { } static void F(object o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(object)", "C.F(Object)", "C.F(System.Object)"); Resolve(process, resolver, "F(object)", "C.F(System.Object)"); Resolve(process, resolver, "F(Object)", "C.F(Object)", "C.F(System.Object)"); Resolve(process, resolver, "F(System.Object)", "C.F(System.Object)"); Resolve(process, resolver, "F(@object)", "C.F(object)"); Resolve(process, resolver, "F(@Object)", "C.F(Object)", "C.F(System.Object)"); } } [Fact] public void SpecialTypes() { var source = @"class C<T1, T2, T3, T4> { } class C { static void F(bool a, char b, sbyte c, byte d) { } static void F(short a, ushort b, int c, uint d) { } static void F(C<uint, long, ulong, float> o) { } static void F(C<double, string, object, decimal> o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F(bool, char, sbyte, byte)", "C.F(System.Boolean, System.Char, System.SByte, System.Byte)"); Resolve(process, resolver, "F(System.Int16, System.UInt16, System.Int32, System.UInt32)", "C.F(System.Int16, System.UInt16, System.Int32, System.UInt32)"); Resolve(process, resolver, "F(C<UInt32, Int64, UInt64, Single>)", "C.F(C<System.UInt32, System.Int64, System.UInt64, System.Single>)"); Resolve(process, resolver, "F(C<double, string, object, decimal>)", "C.F(C<System.Double, System.String, System.Object, System.Decimal>)"); Resolve(process, resolver, "F(bool, char, sbyte)"); Resolve(process, resolver, "F(C<double, string, object, decimal, bool>)"); } } [Fact] public void SpecialTypes_More() { var source = @"class C { static void F(System.IntPtr p) { } static void F(System.UIntPtr p) { } static void F(System.TypedReference r) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F(object)"); Resolve(process, resolver, "F(IntPtr)", "C.F(System.IntPtr)"); Resolve(process, resolver, "F(UIntPtr)", "C.F(System.UIntPtr)"); Resolve(process, resolver, "F(TypedReference)", "C.F(System.TypedReference)"); } } // Binding to "dynamic" type refs is not supported. // This is consistent with Dev14. [Fact] public void Dynamic() { var source = @"class C<T> { } class C { static void F(dynamic d) { } static void F(C<dynamic[]> d) { } }"; var compilation = CreateCompilation(source, references: new[] { CSharpRef }); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(System.Object)", "C.F(C<System.Object[]>)"); Resolve(process, resolver, "F(object)", "C.F(System.Object)"); Resolve(process, resolver, "F(C<object[]>)", "C.F(C<System.Object[]>)"); Resolve(process, resolver, "F(dynamic)"); Resolve(process, resolver, "F(C<dynamic[]>)"); } } [Fact] public void Iterator() { var source = @"class C { static System.Collections.IEnumerable F() { yield break; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F()"); } } [Fact] public void Async() { var source = @"using System.Threading.Tasks; class C { static async Task F() { await Task.Delay(0); } }"; var compilation = CreateCompilationWithMscorlib46(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F()"); } } [Fact(Skip = "global:: not supported")] public void Global() { var source = @"class C { static void F(N.C o) { } static void F(global::C o) { } } namespace N { class C { static void F(N.C o) { } static void F(global::C o) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "C.F(C)", "C.F(N.C)", "C.F(C)", "N.C.F(N.C)", "N.C.F(C)"); Resolve(process, resolver, "C.F(N.C)", "C.F(N.C)", "N.C.F(N.C)"); Resolve(process, resolver, "global::C.F(C)", "C.F(N.C)", "C.F(C)"); // Dev14 does not bind global:: Resolve(process, resolver, "C.F(global::C)", "C.F(C)", "N.C.F(C)"); // Dev14 does not bind global:: } } // Since MetadataDecoder does not load referenced // assemblies, the arity or a type reference is determined // by the type name: e.g.: "C`2". If the arity from the name is // different from the number of generic type arguments, the // method signature containing the type reference is ignored. [Fact] public void UnexpectedArity() { var sourceA = @".class public A<T> { }"; var sourceB = @"class B { static void F(object o) { } static void F(A<object> a) { } }"; ImmutableArray<byte> bytesA; ImmutableArray<byte> pdbA; EmitILToArray(sourceA, appendDefaultHeader: true, includePdb: false, assemblyBytes: out bytesA, pdbBytes: out pdbA); var refA = AssemblyMetadata.CreateFromImage(bytesA).GetReference(); var compilationB = CreateCompilation(sourceB, references: new[] { refA }); var bytesB = compilationB.EmitToArray(); using (var process = new Process(new Module(bytesB))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F(System.Object)", "B.F([notsupported])"); Resolve(process, resolver, "F(A<object>)"); } } /// <summary> /// Should not resolve to P/Invoke methods. /// </summary> [Fact] public void PInvoke() { var source = @"using System.Runtime.InteropServices; class A { [DllImport(""extern.dll"")] public static extern int F(); } class B { public static int F() => 0; }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F()"); } } private static void Resolve(Process process, Resolver resolver, string str, params string[] expectedSignatures) { var signature = MemberSignatureParser.Parse(str); Assert.NotNull(signature); Resolve(process, resolver, signature, expectedSignatures); } } }
1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/ExpressionEvaluator/Core/Test/FunctionResolver/FunctionResolverTestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Text; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { public abstract class FunctionResolverTestBase : CSharpTestBase { internal static void Resolve(Process process, Resolver resolver, RequestSignature signature, string[] expectedSignatures) { var request = new Request(null, signature); resolver.EnableResolution(process, request); VerifySignatures(request, expectedSignatures); } internal static void VerifySignatures(Request request, params string[] expectedSignatures) { var actualSignatures = request.GetResolvedAddresses().Select(a => GetMethodSignature(a.Module, a.Token)); AssertEx.Equal(expectedSignatures, actualSignatures); } private static string GetMethodSignature(Module module, int token) { var reader = module.GetMetadataInternal(); return GetMethodSignature(reader, MetadataTokens.MethodDefinitionHandle(token)); } private static string GetMethodSignature(MetadataReader reader, MethodDefinitionHandle handle) { var methodDef = reader.GetMethodDefinition(handle); var builder = new StringBuilder(); var typeDef = reader.GetTypeDefinition(methodDef.GetDeclaringType()); var allTypeParameters = typeDef.GetGenericParameters(); AppendTypeName(builder, reader, typeDef); builder.Append('.'); builder.Append(reader.GetString(methodDef.Name)); var methodTypeParameters = methodDef.GetGenericParameters(); AppendTypeParameters(builder, DecodeTypeParameters(reader, offset: 0, typeParameters: methodTypeParameters)); var decoder = new MetadataDecoder( reader, GetTypeParameterNames(reader, allTypeParameters), 0, GetTypeParameterNames(reader, methodTypeParameters)); try { AppendParameters(builder, decoder.DecodeParameters(methodDef)); } catch (NotSupportedException) { builder.Append("([notsupported])"); } return builder.ToString(); } private static ImmutableArray<string> GetTypeParameterNames(MetadataReader reader, GenericParameterHandleCollection handles) { return ImmutableArray.CreateRange(handles.Select(h => reader.GetString(reader.GetGenericParameter(h).Name))); } private static void AppendTypeName(StringBuilder builder, MetadataReader reader, TypeDefinition typeDef) { var declaringTypeHandle = typeDef.GetDeclaringType(); int declaringTypeArity; if (declaringTypeHandle.IsNil) { declaringTypeArity = 0; var namespaceName = reader.GetString(typeDef.Namespace); if (!string.IsNullOrEmpty(namespaceName)) { builder.Append(namespaceName); builder.Append('.'); } } else { var declaringType = reader.GetTypeDefinition(declaringTypeHandle); declaringTypeArity = declaringType.GetGenericParameters().Count; AppendTypeName(builder, reader, declaringType); builder.Append('.'); } var typeName = reader.GetString(typeDef.Name); int index = typeName.IndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } builder.Append(typeName); AppendTypeParameters(builder, DecodeTypeParameters(reader, declaringTypeArity, typeDef.GetGenericParameters())); } private static void AppendTypeParameters(StringBuilder builder, ImmutableArray<string> typeParameters) { if (typeParameters.Length > 0) { builder.Append('<'); AppendCommaSeparatedList(builder, typeParameters, (b, t) => b.Append(t)); builder.Append('>'); } } private static void AppendParameters(StringBuilder builder, ImmutableArray<ParameterSignature> parameters) { builder.Append('('); AppendCommaSeparatedList(builder, parameters, AppendParameter); builder.Append(')'); } private static void AppendParameter(StringBuilder builder, ParameterSignature signature) { if (signature.IsByRef) { builder.Append("ref "); } AppendType(builder, signature.Type); } private static void AppendType(StringBuilder builder, TypeSignature signature) { switch (signature.Kind) { case TypeSignatureKind.GenericType: { var genericName = (GenericTypeSignature)signature; AppendType(builder, genericName.QualifiedName); AppendTypeArguments(builder, genericName.TypeArguments); } break; case TypeSignatureKind.QualifiedType: { var qualifiedName = (QualifiedTypeSignature)signature; var qualifier = qualifiedName.Qualifier; if (qualifier != null) { AppendType(builder, qualifier); builder.Append('.'); } builder.Append(qualifiedName.Name); } break; case TypeSignatureKind.ArrayType: { var arrayType = (ArrayTypeSignature)signature; AppendType(builder, arrayType.ElementType); builder.Append('['); builder.Append(',', arrayType.Rank - 1); builder.Append(']'); } break; case TypeSignatureKind.PointerType: AppendType(builder, ((PointerTypeSignature)signature).PointedAtType); builder.Append('*'); break; default: throw new System.NotImplementedException(); } } private static void AppendTypeArguments(StringBuilder builder, ImmutableArray<TypeSignature> typeArguments) { if (typeArguments.Length > 0) { builder.Append('<'); AppendCommaSeparatedList(builder, typeArguments, AppendType); builder.Append('>'); } } private static void AppendCommaSeparatedList<T>(StringBuilder builder, ImmutableArray<T> items, Action<StringBuilder, T> appendItem) { bool any = false; foreach (var item in items) { if (any) { builder.Append(", "); } appendItem(builder, item); any = true; } } private static ImmutableArray<string> DecodeTypeParameters(MetadataReader reader, int offset, GenericParameterHandleCollection typeParameters) { int arity = typeParameters.Count - offset; Debug.Assert(arity >= 0); if (arity == 0) { return ImmutableArray<string>.Empty; } var builder = ImmutableArray.CreateBuilder<string>(arity); for (int i = 0; i < arity; i++) { var handle = typeParameters[offset + i]; var typeParameter = reader.GetGenericParameter(handle); builder.Add(reader.GetString(typeParameter.Name)); } return builder.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Text; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { public abstract class FunctionResolverTestBase : CSharpTestBase { internal static void Resolve(Process process, Resolver resolver, RequestSignature signature, string[] expectedSignatures) { var request = new Request(null, signature); resolver.EnableResolution(process, request); VerifySignatures(request, expectedSignatures); } internal static void VerifySignatures(Request request, params string[] expectedSignatures) { var actualSignatures = request.GetResolvedAddresses().Select(a => GetMethodSignature(a.Module, a.Token)); AssertEx.Equal(expectedSignatures, actualSignatures); } private static string GetMethodSignature(Module module, int token) { var reader = module.GetMetadataReader(); return GetMethodSignature(reader, MetadataTokens.MethodDefinitionHandle(token)); } private static string GetMethodSignature(MetadataReader reader, MethodDefinitionHandle handle) { var methodDef = reader.GetMethodDefinition(handle); var builder = new StringBuilder(); var typeDef = reader.GetTypeDefinition(methodDef.GetDeclaringType()); var allTypeParameters = typeDef.GetGenericParameters(); AppendTypeName(builder, reader, typeDef); builder.Append('.'); builder.Append(reader.GetString(methodDef.Name)); var methodTypeParameters = methodDef.GetGenericParameters(); AppendTypeParameters(builder, DecodeTypeParameters(reader, offset: 0, typeParameters: methodTypeParameters)); var decoder = new MetadataDecoder( reader, GetTypeParameterNames(reader, allTypeParameters), 0, GetTypeParameterNames(reader, methodTypeParameters)); try { AppendParameters(builder, decoder.DecodeParameters(methodDef)); } catch (NotSupportedException) { builder.Append("([notsupported])"); } return builder.ToString(); } private static ImmutableArray<string> GetTypeParameterNames(MetadataReader reader, GenericParameterHandleCollection handles) { return ImmutableArray.CreateRange(handles.Select(h => reader.GetString(reader.GetGenericParameter(h).Name))); } private static void AppendTypeName(StringBuilder builder, MetadataReader reader, TypeDefinition typeDef) { var declaringTypeHandle = typeDef.GetDeclaringType(); int declaringTypeArity; if (declaringTypeHandle.IsNil) { declaringTypeArity = 0; var namespaceName = reader.GetString(typeDef.Namespace); if (!string.IsNullOrEmpty(namespaceName)) { builder.Append(namespaceName); builder.Append('.'); } } else { var declaringType = reader.GetTypeDefinition(declaringTypeHandle); declaringTypeArity = declaringType.GetGenericParameters().Count; AppendTypeName(builder, reader, declaringType); builder.Append('.'); } var typeName = reader.GetString(typeDef.Name); int index = typeName.IndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } builder.Append(typeName); AppendTypeParameters(builder, DecodeTypeParameters(reader, declaringTypeArity, typeDef.GetGenericParameters())); } private static void AppendTypeParameters(StringBuilder builder, ImmutableArray<string> typeParameters) { if (typeParameters.Length > 0) { builder.Append('<'); AppendCommaSeparatedList(builder, typeParameters, (b, t) => b.Append(t)); builder.Append('>'); } } private static void AppendParameters(StringBuilder builder, ImmutableArray<ParameterSignature> parameters) { builder.Append('('); AppendCommaSeparatedList(builder, parameters, AppendParameter); builder.Append(')'); } private static void AppendParameter(StringBuilder builder, ParameterSignature signature) { if (signature.IsByRef) { builder.Append("ref "); } AppendType(builder, signature.Type); } private static void AppendType(StringBuilder builder, TypeSignature signature) { switch (signature.Kind) { case TypeSignatureKind.GenericType: { var genericName = (GenericTypeSignature)signature; AppendType(builder, genericName.QualifiedName); AppendTypeArguments(builder, genericName.TypeArguments); } break; case TypeSignatureKind.QualifiedType: { var qualifiedName = (QualifiedTypeSignature)signature; var qualifier = qualifiedName.Qualifier; if (qualifier != null) { AppendType(builder, qualifier); builder.Append('.'); } builder.Append(qualifiedName.Name); } break; case TypeSignatureKind.ArrayType: { var arrayType = (ArrayTypeSignature)signature; AppendType(builder, arrayType.ElementType); builder.Append('['); builder.Append(',', arrayType.Rank - 1); builder.Append(']'); } break; case TypeSignatureKind.PointerType: AppendType(builder, ((PointerTypeSignature)signature).PointedAtType); builder.Append('*'); break; default: throw new System.NotImplementedException(); } } private static void AppendTypeArguments(StringBuilder builder, ImmutableArray<TypeSignature> typeArguments) { if (typeArguments.Length > 0) { builder.Append('<'); AppendCommaSeparatedList(builder, typeArguments, AppendType); builder.Append('>'); } } private static void AppendCommaSeparatedList<T>(StringBuilder builder, ImmutableArray<T> items, Action<StringBuilder, T> appendItem) { bool any = false; foreach (var item in items) { if (any) { builder.Append(", "); } appendItem(builder, item); any = true; } } private static ImmutableArray<string> DecodeTypeParameters(MetadataReader reader, int offset, GenericParameterHandleCollection typeParameters) { int arity = typeParameters.Count - offset; Debug.Assert(arity >= 0); if (arity == 0) { return ImmutableArray<string>.Empty; } var builder = ImmutableArray.CreateBuilder<string>(arity); for (int i = 0; i < arity; i++) { var handle = typeParameters[offset + i]; var typeParameter = reader.GetGenericParameter(handle); builder.Add(reader.GetString(typeParameter.Name)); } return builder.ToImmutable(); } } }
1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/ExpressionEvaluator/Core/Test/FunctionResolver/Module.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Metadata; using System.Reflection.PortableExecutable; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { internal sealed class Module : IDisposable { private readonly string _name; private readonly PEReader _reader; private int _getMetadataCount; internal Module(ImmutableArray<byte> bytes, string name = null) { _name = name; _reader = bytes.IsDefault ? null : new PEReader(bytes); } internal string Name => _name; internal int GetMetadataCount => _getMetadataCount; internal MetadataReader GetMetadata() { _getMetadataCount++; return GetMetadataInternal(); } internal MetadataReader GetMetadataInternal() { if (_reader == null) { return null; } unsafe { var block = _reader.GetMetadata(); return new MetadataReader(block.Pointer, block.Length); } } void IDisposable.Dispose() { if (_reader != null) { _reader.Dispose(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { internal sealed class Module : IDisposable { private readonly PEReader? _reader; public readonly string? Name; public int MetadataAccessCount { get; private set; } internal Module(ImmutableArray<byte> metadata, string? name = null) { Name = name; _reader = metadata.IsDefault ? null : new PEReader(metadata); } internal unsafe bool TryGetMetadata(out byte* pointer, out int length) { if (_reader == null) { pointer = null; length = 0; return false; } MetadataAccessCount++; var block = _reader.GetMetadata(); pointer = block.Pointer; length = block.Length; return true; } internal unsafe MetadataReader? GetMetadataReader() { if (_reader == null) { return null; } var block = _reader.GetMetadata(); return new MetadataReader(block.Pointer, block.Length); } void IDisposable.Dispose() => _reader?.Dispose(); } }
1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/ExpressionEvaluator/Core/Test/FunctionResolver/Resolver.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { internal sealed class Resolver : FunctionResolverBase<Process, Module, Request> { internal static readonly Resolver CSharpResolver = CreateFrom(new Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.CSharpFunctionResolver()); internal static readonly Resolver VisualBasicResolver = CreateFrom(new Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.VisualBasicFunctionResolver()); private readonly bool _ignoreCase; private readonly Guid _languageId; private readonly Dictionary<Process, List<Request>> _requests; private static Resolver CreateFrom(FunctionResolver resolver) { return new Resolver(resolver.IgnoreCase, resolver.LanguageId); } private Resolver(bool ignoreCase, Guid languageId) { _ignoreCase = ignoreCase; _languageId = languageId; _requests = new Dictionary<Process, List<Request>>(); } internal void EnableResolution(Process process, Request request) { List<Request> requests; if (!_requests.TryGetValue(process, out requests)) { requests = new List<Request>(); _requests.Add(process, requests); } requests.Add(request); base.EnableResolution(process, request, OnFunctionResolved); } internal void OnModuleLoad(Process process, Module module) { base.OnModuleLoad(process, module, OnFunctionResolved); } internal override bool ShouldEnableFunctionResolver(Process process) { return process.ShouldEnableFunctionResolver(); } internal override IEnumerable<Module> GetAllModules(Process process) { return process.GetModules(); } internal override string GetModuleName(Module module) { return module.Name; } internal override MetadataReader GetModuleMetadata(Module module) { return module.GetMetadata(); } internal override Request[] GetRequests(Process process) { List<Request> requests; if (!_requests.TryGetValue(process, out requests)) { return new Request[0]; } return requests.ToArray(); } internal override string GetRequestModuleName(Request request) { return request.ModuleName; } internal override RequestSignature GetParsedSignature(Request request) { return request.Signature; } internal override bool IgnoreCase => _ignoreCase; internal override Guid GetLanguageId(Request request) { return request.LanguageId; } internal override Guid LanguageId => _languageId; private static void OnFunctionResolved(Module module, Request request, int token, int version, int ilOffset) { request.OnFunctionResolved(module, token, version, ilOffset); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { internal sealed class Resolver : FunctionResolverBase<Process, Module, Request> { internal static readonly Resolver CSharpResolver = CreateFrom(new Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.CSharpFunctionResolver()); internal static readonly Resolver VisualBasicResolver = CreateFrom(new Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.VisualBasicFunctionResolver()); private readonly bool _ignoreCase; private readonly Guid _languageId; private readonly Dictionary<Process, List<Request>> _requests; private static Resolver CreateFrom(FunctionResolver resolver) { return new Resolver(resolver.IgnoreCase, resolver.LanguageId); } private Resolver(bool ignoreCase, Guid languageId) { _ignoreCase = ignoreCase; _languageId = languageId; _requests = new Dictionary<Process, List<Request>>(); } internal void EnableResolution(Process process, Request request) { List<Request> requests; if (!_requests.TryGetValue(process, out requests)) { requests = new List<Request>(); _requests.Add(process, requests); } requests.Add(request); base.EnableResolution(process, request, OnFunctionResolved); } internal void OnModuleLoad(Process process, Module module) { base.OnModuleLoad(process, module, OnFunctionResolved); } internal override bool ShouldEnableFunctionResolver(Process process) { return process.ShouldEnableFunctionResolver(); } internal override IEnumerable<Module> GetAllModules(Process process) { return process.GetModules(); } internal override string GetModuleName(Module module) { return module.Name; } internal override unsafe bool TryGetMetadata(Module module, out byte* pointer, out int length) => module.TryGetMetadata(out pointer, out length); internal override Request[] GetRequests(Process process) { List<Request> requests; if (!_requests.TryGetValue(process, out requests)) { return new Request[0]; } return requests.ToArray(); } internal override string GetRequestModuleName(Request request) { return request.ModuleName; } internal override RequestSignature GetParsedSignature(Request request) { return request.Signature; } internal override bool IgnoreCase => _ignoreCase; internal override Guid GetLanguageId(Request request) { return request.LanguageId; } internal override Guid LanguageId => _languageId; private static void OnFunctionResolved(Module module, Request request, int token, int version, int ilOffset) { request.OnFunctionResolved(module, token, version, ilOffset); } } }
1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Compilers/Core/Portable/SourceGeneration/Nodes/DriverStateTable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class DriverStateTable { private readonly ImmutableSegmentedDictionary<object, IStateTable> _tables; internal static DriverStateTable Empty { get; } = new DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable>.Empty); private DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable> tables) { _tables = tables; } public NodeStateTable<T> GetStateTableOrEmpty<T>(object input) { if (_tables.TryGetValue(input, out var result)) { return (NodeStateTable<T>)result; } return NodeStateTable<T>.Empty; } public sealed class Builder { private readonly ImmutableSegmentedDictionary<object, IStateTable>.Builder _tableBuilder = ImmutableSegmentedDictionary.CreateBuilder<object, IStateTable>(); private readonly ImmutableArray<ISyntaxInputNode> _syntaxInputNodes; private readonly ImmutableDictionary<ISyntaxInputNode, Exception>.Builder _syntaxExceptions = ImmutableDictionary.CreateBuilder<ISyntaxInputNode, Exception>(); private readonly DriverStateTable _previousTable; private readonly CancellationToken _cancellationToken; internal GeneratorDriverState DriverState { get; } public Compilation Compilation { get; } public Builder(Compilation compilation, GeneratorDriverState driverState, ImmutableArray<ISyntaxInputNode> syntaxInputNodes, CancellationToken cancellationToken = default) { Compilation = compilation; DriverState = driverState; _previousTable = driverState.StateTable; _syntaxInputNodes = syntaxInputNodes; _cancellationToken = cancellationToken; } public IStateTable GetSyntaxInputTable(ISyntaxInputNode syntaxInputNode) { Debug.Assert(_syntaxInputNodes.Contains(syntaxInputNode)); // when we don't have a value for this node, we update all the syntax inputs at once if (!_tableBuilder.ContainsKey(syntaxInputNode)) { // get a builder for each input node var builders = ArrayBuilder<ISyntaxInputBuilder>.GetInstance(_syntaxInputNodes.Length); foreach (var node in _syntaxInputNodes) { builders.Add(node.GetBuilder(_previousTable)); } // update each tree for the builders, sharing the semantic model foreach ((var tree, var state) in GetLatestStateTableForNode(SharedInputNodes.SyntaxTrees)) { var root = tree.GetRoot(_cancellationToken); var model = state != EntryState.Removed ? Compilation.GetSemanticModel(tree) : null; for (int i = 0; i < builders.Count; i++) { try { _cancellationToken.ThrowIfCancellationRequested(); builders[i].VisitTree(root, state, model, _cancellationToken); } catch (UserFunctionException ufe) { // we're evaluating this node ahead of time, so we can't just throw the exception // instead we'll hold onto it, and throw the exception when a downstream node actually // attempts to read the value _syntaxExceptions[builders[i].SyntaxInputNode] = ufe; builders.RemoveAt(i); i--; } } } // save the updated inputs foreach (var builder in builders) { builder.SaveStateAndFree(_tableBuilder); Debug.Assert(_tableBuilder.ContainsKey(builder.SyntaxInputNode)); } builders.Free(); } // if we don't have an entry for this node, it must have thrown an exception if (!_tableBuilder.ContainsKey(syntaxInputNode)) { throw _syntaxExceptions[syntaxInputNode]; } return _tableBuilder[syntaxInputNode]; } public NodeStateTable<T> GetLatestStateTableForNode<T>(IIncrementalGeneratorNode<T> source) { // if we've already evaluated a node during this build, we can just return the existing result if (_tableBuilder.ContainsKey(source)) { return (NodeStateTable<T>)_tableBuilder[source]; } // get the previous table, if there was one for this node NodeStateTable<T> previousTable = _previousTable.GetStateTableOrEmpty<T>(source); // request the node update its state based on the current driver table and store the new result var newTable = source.UpdateStateTable(this, previousTable, _cancellationToken); _tableBuilder[source] = newTable; return newTable; } public DriverStateTable ToImmutable() { // we can compact the tables at this point, as we'll no longer be using them to determine current state var keys = _tableBuilder.Keys.ToArray(); foreach (var key in keys) { _tableBuilder[key] = _tableBuilder[key].AsCached(); } return new DriverStateTable(_tableBuilder.ToImmutable()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class DriverStateTable { private readonly ImmutableSegmentedDictionary<object, IStateTable> _tables; internal static DriverStateTable Empty { get; } = new DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable>.Empty); private DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable> tables) { _tables = tables; } public NodeStateTable<T> GetStateTableOrEmpty<T>(object input) { if (_tables.TryGetValue(input, out var result)) { return (NodeStateTable<T>)result; } return NodeStateTable<T>.Empty; } public sealed class Builder { private readonly ImmutableSegmentedDictionary<object, IStateTable>.Builder _tableBuilder = ImmutableSegmentedDictionary.CreateBuilder<object, IStateTable>(); private readonly ImmutableArray<ISyntaxInputNode> _syntaxInputNodes; private readonly ImmutableDictionary<ISyntaxInputNode, Exception>.Builder _syntaxExceptions = ImmutableDictionary.CreateBuilder<ISyntaxInputNode, Exception>(); private readonly DriverStateTable _previousTable; private readonly CancellationToken _cancellationToken; internal GeneratorDriverState DriverState { get; } public Compilation Compilation { get; } public Builder(Compilation compilation, GeneratorDriverState driverState, ImmutableArray<ISyntaxInputNode> syntaxInputNodes, CancellationToken cancellationToken = default) { Compilation = compilation; DriverState = driverState; _previousTable = driverState.StateTable; _syntaxInputNodes = syntaxInputNodes; _cancellationToken = cancellationToken; } public IStateTable GetSyntaxInputTable(ISyntaxInputNode syntaxInputNode) { Debug.Assert(_syntaxInputNodes.Contains(syntaxInputNode)); // when we don't have a value for this node, we update all the syntax inputs at once if (!_tableBuilder.ContainsKey(syntaxInputNode)) { // get a builder for each input node var builders = ArrayBuilder<ISyntaxInputBuilder>.GetInstance(_syntaxInputNodes.Length); foreach (var node in _syntaxInputNodes) { builders.Add(node.GetBuilder(_previousTable)); } // update each tree for the builders, sharing the semantic model foreach ((var tree, var state) in GetLatestStateTableForNode(SharedInputNodes.SyntaxTrees)) { var root = tree.GetRoot(_cancellationToken); var model = state != EntryState.Removed ? Compilation.GetSemanticModel(tree) : null; for (int i = 0; i < builders.Count; i++) { try { _cancellationToken.ThrowIfCancellationRequested(); builders[i].VisitTree(root, state, model, _cancellationToken); } catch (UserFunctionException ufe) { // we're evaluating this node ahead of time, so we can't just throw the exception // instead we'll hold onto it, and throw the exception when a downstream node actually // attempts to read the value _syntaxExceptions[builders[i].SyntaxInputNode] = ufe; builders.RemoveAt(i); i--; } } } // save the updated inputs foreach (var builder in builders) { builder.SaveStateAndFree(_tableBuilder); Debug.Assert(_tableBuilder.ContainsKey(builder.SyntaxInputNode)); } builders.Free(); } // if we don't have an entry for this node, it must have thrown an exception if (!_tableBuilder.ContainsKey(syntaxInputNode)) { throw _syntaxExceptions[syntaxInputNode]; } return _tableBuilder[syntaxInputNode]; } public NodeStateTable<T> GetLatestStateTableForNode<T>(IIncrementalGeneratorNode<T> source) { // if we've already evaluated a node during this build, we can just return the existing result if (_tableBuilder.ContainsKey(source)) { return (NodeStateTable<T>)_tableBuilder[source]; } // get the previous table, if there was one for this node NodeStateTable<T> previousTable = _previousTable.GetStateTableOrEmpty<T>(source); // request the node update its state based on the current driver table and store the new result var newTable = source.UpdateStateTable(this, previousTable, _cancellationToken); _tableBuilder[source] = newTable; return newTable; } public DriverStateTable ToImmutable() { // we can compact the tables at this point, as we'll no longer be using them to determine current state var keys = _tableBuilder.Keys.ToArray(); foreach (var key in keys) { _tableBuilder[key] = _tableBuilder[key].AsCached(); } return new DriverStateTable(_tableBuilder.ToImmutable()); } } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PENamespaceSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { /// <summary> /// The base class to represent a namespace imported from a PE/module. Namespaces that differ /// only by casing in name are not merged. /// </summary> internal abstract class PENamespaceSymbol : NamespaceSymbol { /// <summary> /// A map of namespaces immediately contained within this namespace /// mapped by their name (case-sensitively). /// </summary> protected Dictionary<string, PENestedNamespaceSymbol> lazyNamespaces; /// <summary> /// A map of types immediately contained within this namespace /// grouped by their name (case-sensitively). /// </summary> protected Dictionary<string, ImmutableArray<PENamedTypeSymbol>> lazyTypes; /// <summary> /// A map of NoPia local types immediately contained in this assembly. /// Maps type name (non-qualified) to the row id. Note, for VB we should use /// full name. /// </summary> private Dictionary<string, TypeDefinitionHandle> _lazyNoPiaLocalTypes; /// <summary> /// All type members in a flat array /// </summary> private ImmutableArray<PENamedTypeSymbol> _lazyFlattenedTypes; internal sealed override NamespaceExtent Extent { get { return new NamespaceExtent(this.ContainingPEModule); } } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Provide " + nameof(ArrayBuilder<Symbol>) + " capacity to reduce number of allocations.", AllowGenericEnumeration = false)] public sealed override ImmutableArray<Symbol> GetMembers() { EnsureAllMembersLoaded(); var memberTypes = GetMemberTypesPrivate(); var builder = ArrayBuilder<Symbol>.GetInstance(memberTypes.Length + lazyNamespaces.Count); builder.AddRange(memberTypes); foreach (var pair in lazyNamespaces) { builder.Add(pair.Value); } return builder.ToImmutableAndFree(); } private ImmutableArray<NamedTypeSymbol> GetMemberTypesPrivate() { //assume that EnsureAllMembersLoaded() has initialize lazyTypes if (_lazyFlattenedTypes.IsDefault) { var flattened = lazyTypes.Flatten(); ImmutableInterlocked.InterlockedExchange(ref _lazyFlattenedTypes, flattened); } return StaticCast<NamedTypeSymbol>.From(_lazyFlattenedTypes); } public sealed override ImmutableArray<Symbol> GetMembers(string name) { EnsureAllMembersLoaded(); PENestedNamespaceSymbol ns = null; ImmutableArray<PENamedTypeSymbol> t; if (lazyNamespaces.TryGetValue(name, out ns)) { if (lazyTypes.TryGetValue(name, out t)) { // TODO - Eliminate the copy by storing all members and type members instead of non-type and type members? return StaticCast<Symbol>.From(t).Add(ns); } else { return ImmutableArray.Create<Symbol>(ns); } } else if (lazyTypes.TryGetValue(name, out t)) { return StaticCast<Symbol>.From(t); } return ImmutableArray<Symbol>.Empty; } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { EnsureAllMembersLoaded(); return GetMemberTypesPrivate(); } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { EnsureAllMembersLoaded(); ImmutableArray<PENamedTypeSymbol> t; return lazyTypes.TryGetValue(name, out t) ? StaticCast<NamedTypeSymbol>.From(t) : ImmutableArray<NamedTypeSymbol>.Empty; } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return GetTypeMembers(name).WhereAsArray((type, arity) => type.Arity == arity, arity); } public sealed override ImmutableArray<Location> Locations { get { return ContainingPEModule.MetadataLocation.Cast<MetadataLocation, Location>(); } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } /// <summary> /// Returns PEModuleSymbol containing the namespace. /// </summary> /// <returns>PEModuleSymbol containing the namespace.</returns> internal abstract PEModuleSymbol ContainingPEModule { get; } protected abstract void EnsureAllMembersLoaded(); /// <summary> /// Initializes namespaces and types maps with information about /// namespaces and types immediately contained within this namespace. /// </summary> /// <param name="typesByNS"> /// The sequence of groups of TypeDef row ids for types contained within the namespace, /// recursively including those from nested namespaces. The row ids must be grouped by the /// fully-qualified namespace name case-sensitively. There could be multiple groups /// for each fully-qualified namespace name. The groups must be sorted by /// their key in case-sensitive manner. Empty string must be used as namespace name for types /// immediately contained within Global namespace. Therefore, all types in this namespace, if any, /// must be in several first IGroupings. /// </param> protected void LoadAllMembers(IEnumerable<IGrouping<string, TypeDefinitionHandle>> typesByNS) { Debug.Assert(typesByNS != null); // A sequence of groups of TypeDef row ids for types immediately contained within this namespace. IEnumerable<IGrouping<string, TypeDefinitionHandle>> nestedTypes = null; // A sequence with information about namespaces immediately contained within this namespace. // For each pair: // Key - contains simple name of a child namespace. // Value - contains a sequence similar to the one passed to this function, but // calculated for the child namespace. IEnumerable<KeyValuePair<string, IEnumerable<IGrouping<string, TypeDefinitionHandle>>>> nestedNamespaces = null; bool isGlobalNamespace = this.IsGlobalNamespace; MetadataHelpers.GetInfoForImmediateNamespaceMembers( isGlobalNamespace, isGlobalNamespace ? 0 : GetQualifiedNameLength(), typesByNS, StringComparer.Ordinal, out nestedTypes, out nestedNamespaces); LazyInitializeNamespaces(nestedNamespaces); LazyInitializeTypes(nestedTypes); } private int GetQualifiedNameLength() { int length = this.Name.Length; var parent = ContainingNamespace; while (parent?.IsGlobalNamespace == false) { // add name of the parent + "." length += parent.Name.Length + 1; parent = parent.ContainingNamespace; } return length; } /// <summary> /// Create symbols for nested namespaces and initialize namespaces map. /// </summary> private void LazyInitializeNamespaces( IEnumerable<KeyValuePair<string, IEnumerable<IGrouping<string, TypeDefinitionHandle>>>> childNamespaces) { if (this.lazyNamespaces == null) { var namespaces = new Dictionary<string, PENestedNamespaceSymbol>(StringOrdinalComparer.Instance); foreach (var child in childNamespaces) { var c = new PENestedNamespaceSymbol(child.Key, this, child.Value); namespaces.Add(c.Name, c); } Interlocked.CompareExchange(ref this.lazyNamespaces, namespaces, null); } } /// <summary> /// Create symbols for nested types and initialize types map. /// </summary> private void LazyInitializeTypes(IEnumerable<IGrouping<string, TypeDefinitionHandle>> typeGroups) { if (this.lazyTypes == null) { var moduleSymbol = ContainingPEModule; var children = ArrayBuilder<PENamedTypeSymbol>.GetInstance(); var skipCheckForPiaType = !moduleSymbol.Module.ContainsNoPiaLocalTypes(); Dictionary<string, TypeDefinitionHandle> noPiaLocalTypes = null; foreach (var g in typeGroups) { foreach (var t in g) { if (skipCheckForPiaType || !moduleSymbol.Module.IsNoPiaLocalType(t)) { children.Add(PENamedTypeSymbol.Create(moduleSymbol, this, t, g.Key)); } else { try { string typeDefName = moduleSymbol.Module.GetTypeDefNameOrThrow(t); if (noPiaLocalTypes == null) { noPiaLocalTypes = new Dictionary<string, TypeDefinitionHandle>(StringOrdinalComparer.Instance); } noPiaLocalTypes[typeDefName] = t; } catch (BadImageFormatException) { } } } } var typesDict = children.ToDictionary(c => c.Name, StringOrdinalComparer.Instance); children.Free(); if (noPiaLocalTypes != null) { Interlocked.CompareExchange(ref _lazyNoPiaLocalTypes, noPiaLocalTypes, null); } var original = Interlocked.CompareExchange(ref this.lazyTypes, typesDict, null); // Build cache of TypeDef Tokens // Potentially this can be done in the background. if (original == null) { moduleSymbol.OnNewTypeDeclarationsLoaded(typesDict); } } } internal NamedTypeSymbol LookupMetadataType(ref MetadataTypeName emittedTypeName, out bool isNoPiaLocalType) { NamedTypeSymbol result = LookupMetadataType(ref emittedTypeName); isNoPiaLocalType = false; if (result is MissingMetadataTypeSymbol) { EnsureAllMembersLoaded(); TypeDefinitionHandle typeDef; // See if this is a NoPia local type, which we should unify. // Note, VB should use FullName. if (_lazyNoPiaLocalTypes != null && _lazyNoPiaLocalTypes.TryGetValue(emittedTypeName.TypeName, out typeDef)) { result = (NamedTypeSymbol)new MetadataDecoder(ContainingPEModule).GetTypeOfToken(typeDef, out isNoPiaLocalType); Debug.Assert(isNoPiaLocalType); } } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { /// <summary> /// The base class to represent a namespace imported from a PE/module. Namespaces that differ /// only by casing in name are not merged. /// </summary> internal abstract class PENamespaceSymbol : NamespaceSymbol { /// <summary> /// A map of namespaces immediately contained within this namespace /// mapped by their name (case-sensitively). /// </summary> protected Dictionary<string, PENestedNamespaceSymbol> lazyNamespaces; /// <summary> /// A map of types immediately contained within this namespace /// grouped by their name (case-sensitively). /// </summary> protected Dictionary<string, ImmutableArray<PENamedTypeSymbol>> lazyTypes; /// <summary> /// A map of NoPia local types immediately contained in this assembly. /// Maps type name (non-qualified) to the row id. Note, for VB we should use /// full name. /// </summary> private Dictionary<string, TypeDefinitionHandle> _lazyNoPiaLocalTypes; /// <summary> /// All type members in a flat array /// </summary> private ImmutableArray<PENamedTypeSymbol> _lazyFlattenedTypes; internal sealed override NamespaceExtent Extent { get { return new NamespaceExtent(this.ContainingPEModule); } } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Provide " + nameof(ArrayBuilder<Symbol>) + " capacity to reduce number of allocations.", AllowGenericEnumeration = false)] public sealed override ImmutableArray<Symbol> GetMembers() { EnsureAllMembersLoaded(); var memberTypes = GetMemberTypesPrivate(); var builder = ArrayBuilder<Symbol>.GetInstance(memberTypes.Length + lazyNamespaces.Count); builder.AddRange(memberTypes); foreach (var pair in lazyNamespaces) { builder.Add(pair.Value); } return builder.ToImmutableAndFree(); } private ImmutableArray<NamedTypeSymbol> GetMemberTypesPrivate() { //assume that EnsureAllMembersLoaded() has initialize lazyTypes if (_lazyFlattenedTypes.IsDefault) { var flattened = lazyTypes.Flatten(); ImmutableInterlocked.InterlockedExchange(ref _lazyFlattenedTypes, flattened); } return StaticCast<NamedTypeSymbol>.From(_lazyFlattenedTypes); } public sealed override ImmutableArray<Symbol> GetMembers(string name) { EnsureAllMembersLoaded(); PENestedNamespaceSymbol ns = null; ImmutableArray<PENamedTypeSymbol> t; if (lazyNamespaces.TryGetValue(name, out ns)) { if (lazyTypes.TryGetValue(name, out t)) { // TODO - Eliminate the copy by storing all members and type members instead of non-type and type members? return StaticCast<Symbol>.From(t).Add(ns); } else { return ImmutableArray.Create<Symbol>(ns); } } else if (lazyTypes.TryGetValue(name, out t)) { return StaticCast<Symbol>.From(t); } return ImmutableArray<Symbol>.Empty; } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { EnsureAllMembersLoaded(); return GetMemberTypesPrivate(); } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { EnsureAllMembersLoaded(); ImmutableArray<PENamedTypeSymbol> t; return lazyTypes.TryGetValue(name, out t) ? StaticCast<NamedTypeSymbol>.From(t) : ImmutableArray<NamedTypeSymbol>.Empty; } public sealed override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return GetTypeMembers(name).WhereAsArray((type, arity) => type.Arity == arity, arity); } public sealed override ImmutableArray<Location> Locations { get { return ContainingPEModule.MetadataLocation.Cast<MetadataLocation, Location>(); } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } /// <summary> /// Returns PEModuleSymbol containing the namespace. /// </summary> /// <returns>PEModuleSymbol containing the namespace.</returns> internal abstract PEModuleSymbol ContainingPEModule { get; } protected abstract void EnsureAllMembersLoaded(); /// <summary> /// Initializes namespaces and types maps with information about /// namespaces and types immediately contained within this namespace. /// </summary> /// <param name="typesByNS"> /// The sequence of groups of TypeDef row ids for types contained within the namespace, /// recursively including those from nested namespaces. The row ids must be grouped by the /// fully-qualified namespace name case-sensitively. There could be multiple groups /// for each fully-qualified namespace name. The groups must be sorted by /// their key in case-sensitive manner. Empty string must be used as namespace name for types /// immediately contained within Global namespace. Therefore, all types in this namespace, if any, /// must be in several first IGroupings. /// </param> protected void LoadAllMembers(IEnumerable<IGrouping<string, TypeDefinitionHandle>> typesByNS) { Debug.Assert(typesByNS != null); // A sequence of groups of TypeDef row ids for types immediately contained within this namespace. IEnumerable<IGrouping<string, TypeDefinitionHandle>> nestedTypes = null; // A sequence with information about namespaces immediately contained within this namespace. // For each pair: // Key - contains simple name of a child namespace. // Value - contains a sequence similar to the one passed to this function, but // calculated for the child namespace. IEnumerable<KeyValuePair<string, IEnumerable<IGrouping<string, TypeDefinitionHandle>>>> nestedNamespaces = null; bool isGlobalNamespace = this.IsGlobalNamespace; MetadataHelpers.GetInfoForImmediateNamespaceMembers( isGlobalNamespace, isGlobalNamespace ? 0 : GetQualifiedNameLength(), typesByNS, StringComparer.Ordinal, out nestedTypes, out nestedNamespaces); LazyInitializeNamespaces(nestedNamespaces); LazyInitializeTypes(nestedTypes); } private int GetQualifiedNameLength() { int length = this.Name.Length; var parent = ContainingNamespace; while (parent?.IsGlobalNamespace == false) { // add name of the parent + "." length += parent.Name.Length + 1; parent = parent.ContainingNamespace; } return length; } /// <summary> /// Create symbols for nested namespaces and initialize namespaces map. /// </summary> private void LazyInitializeNamespaces( IEnumerable<KeyValuePair<string, IEnumerable<IGrouping<string, TypeDefinitionHandle>>>> childNamespaces) { if (this.lazyNamespaces == null) { var namespaces = new Dictionary<string, PENestedNamespaceSymbol>(StringOrdinalComparer.Instance); foreach (var child in childNamespaces) { var c = new PENestedNamespaceSymbol(child.Key, this, child.Value); namespaces.Add(c.Name, c); } Interlocked.CompareExchange(ref this.lazyNamespaces, namespaces, null); } } /// <summary> /// Create symbols for nested types and initialize types map. /// </summary> private void LazyInitializeTypes(IEnumerable<IGrouping<string, TypeDefinitionHandle>> typeGroups) { if (this.lazyTypes == null) { var moduleSymbol = ContainingPEModule; var children = ArrayBuilder<PENamedTypeSymbol>.GetInstance(); var skipCheckForPiaType = !moduleSymbol.Module.ContainsNoPiaLocalTypes(); Dictionary<string, TypeDefinitionHandle> noPiaLocalTypes = null; foreach (var g in typeGroups) { foreach (var t in g) { if (skipCheckForPiaType || !moduleSymbol.Module.IsNoPiaLocalType(t)) { children.Add(PENamedTypeSymbol.Create(moduleSymbol, this, t, g.Key)); } else { try { string typeDefName = moduleSymbol.Module.GetTypeDefNameOrThrow(t); if (noPiaLocalTypes == null) { noPiaLocalTypes = new Dictionary<string, TypeDefinitionHandle>(StringOrdinalComparer.Instance); } noPiaLocalTypes[typeDefName] = t; } catch (BadImageFormatException) { } } } } var typesDict = children.ToDictionary(c => c.Name, StringOrdinalComparer.Instance); children.Free(); if (noPiaLocalTypes != null) { Interlocked.CompareExchange(ref _lazyNoPiaLocalTypes, noPiaLocalTypes, null); } var original = Interlocked.CompareExchange(ref this.lazyTypes, typesDict, null); // Build cache of TypeDef Tokens // Potentially this can be done in the background. if (original == null) { moduleSymbol.OnNewTypeDeclarationsLoaded(typesDict); } } } internal NamedTypeSymbol LookupMetadataType(ref MetadataTypeName emittedTypeName, out bool isNoPiaLocalType) { NamedTypeSymbol result = LookupMetadataType(ref emittedTypeName); isNoPiaLocalType = false; if (result is MissingMetadataTypeSymbol) { EnsureAllMembersLoaded(); TypeDefinitionHandle typeDef; // See if this is a NoPia local type, which we should unify. // Note, VB should use FullName. if (_lazyNoPiaLocalTypes != null && _lazyNoPiaLocalTypes.TryGetValue(emittedTypeName.TypeName, out typeDef)) { result = (NamedTypeSymbol)new MetadataDecoder(ContainingPEModule).GetTypeOfToken(typeDef, out isNoPiaLocalType); Debug.Assert(isNoPiaLocalType); } } return result; } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService.DocCommentFormatter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { internal class DocCommentFormatter { private const int s_indentSize = 2; private const int s_wrapLength = 80; private static readonly string s_summaryHeader = FeaturesResources.Summary_colon; private static readonly string s_paramHeader = FeaturesResources.Parameters_colon; private const string s_labelFormat = "{0}:"; private static readonly string s_typeParameterHeader = FeaturesResources.Type_parameters_colon; private static readonly string s_returnsHeader = FeaturesResources.Returns_colon; private static readonly string s_valueHeader = FeaturesResources.Value_colon; private static readonly string s_exceptionsHeader = FeaturesResources.Exceptions_colon; private static readonly string s_remarksHeader = FeaturesResources.Remarks_colon; internal static ImmutableArray<string> Format(IDocumentationCommentFormattingService docCommentFormattingService, DocumentationComment docComment) { var formattedCommentLinesBuilder = ArrayBuilder<string>.GetInstance(); var lineBuilder = new StringBuilder(); var formattedSummaryText = docCommentFormattingService.Format(docComment.SummaryText); if (!string.IsNullOrWhiteSpace(formattedSummaryText)) { formattedCommentLinesBuilder.Add(s_summaryHeader); formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedSummaryText)); } var parameterNames = docComment.ParameterNames; if (parameterNames.Length > 0) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_paramHeader); for (var i = 0; i < parameterNames.Length; i++) { if (i != 0) { formattedCommentLinesBuilder.Add(string.Empty); } lineBuilder.Clear(); lineBuilder.Append(' ', s_indentSize); lineBuilder.Append(string.Format(s_labelFormat, parameterNames[i])); formattedCommentLinesBuilder.Add(lineBuilder.ToString()); var rawParameterText = docComment.GetParameterText(parameterNames[i]); var formattedParameterText = docCommentFormattingService.Format(rawParameterText); if (!string.IsNullOrWhiteSpace(formattedParameterText)) { formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedParameterText)); } } } var typeParameterNames = docComment.TypeParameterNames; if (typeParameterNames.Length > 0) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_typeParameterHeader); for (var i = 0; i < typeParameterNames.Length; i++) { if (i != 0) { formattedCommentLinesBuilder.Add(string.Empty); } lineBuilder.Clear(); lineBuilder.Append(' ', s_indentSize); lineBuilder.Append(string.Format(s_labelFormat, typeParameterNames[i])); formattedCommentLinesBuilder.Add(lineBuilder.ToString()); var rawTypeParameterText = docComment.GetTypeParameterText(typeParameterNames[i]); var formattedTypeParameterText = docCommentFormattingService.Format(rawTypeParameterText); if (!string.IsNullOrWhiteSpace(formattedTypeParameterText)) { formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedTypeParameterText)); } } } var formattedReturnsText = docCommentFormattingService.Format(docComment.ReturnsText); if (!string.IsNullOrWhiteSpace(formattedReturnsText)) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_returnsHeader); formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedReturnsText)); } var formattedValueText = docCommentFormattingService.Format(docComment.ValueText); if (!string.IsNullOrWhiteSpace(formattedValueText)) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_valueHeader); formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedValueText)); } var exceptionTypes = docComment.ExceptionTypes; if (exceptionTypes.Length > 0) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_exceptionsHeader); for (var i = 0; i < exceptionTypes.Length; i++) { var rawExceptionTexts = docComment.GetExceptionTexts(exceptionTypes[i]); for (var j = 0; j < rawExceptionTexts.Length; j++) { if (i != 0 || j != 0) { formattedCommentLinesBuilder.Add(string.Empty); } lineBuilder.Clear(); lineBuilder.Append(' ', s_indentSize); lineBuilder.Append(string.Format(s_labelFormat, exceptionTypes[i])); formattedCommentLinesBuilder.Add(lineBuilder.ToString()); var formattedExceptionText = docCommentFormattingService.Format(rawExceptionTexts[j]); if (!string.IsNullOrWhiteSpace(formattedExceptionText)) { formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedExceptionText)); } } } } var formattedRemarksText = docCommentFormattingService.Format(docComment.RemarksText); if (!string.IsNullOrWhiteSpace(formattedRemarksText)) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_remarksHeader); formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedRemarksText)); } // Eliminate any blank lines at the beginning. while (formattedCommentLinesBuilder.Count > 0 && formattedCommentLinesBuilder[0].Length == 0) { formattedCommentLinesBuilder.RemoveAt(0); } // Eliminate any blank lines at the end. while (formattedCommentLinesBuilder.Count > 0 && formattedCommentLinesBuilder[^1].Length == 0) { formattedCommentLinesBuilder.RemoveAt(formattedCommentLinesBuilder.Count - 1); } return formattedCommentLinesBuilder.ToImmutableAndFree(); } private static ImmutableArray<string> CreateWrappedTextFromRawText(string rawText) { using var _ = ArrayBuilder<string>.GetInstance(out var lines); // First split the string into constituent lines. var split = rawText.Split(new[] { "\r\n" }, System.StringSplitOptions.None); // Now split each line into multiple lines. foreach (var item in split) SplitRawLineIntoFormattedLines(item, lines); return lines.ToImmutable(); } private static void SplitRawLineIntoFormattedLines( string line, ArrayBuilder<string> lines) { var indent = new StringBuilder().Append(' ', s_indentSize * 2).ToString(); var words = line.Split(' '); var firstInLine = true; var sb = new StringBuilder(); sb.Append(indent); foreach (var word in words) { // We must always append at least one word to ensure progress. if (firstInLine) { firstInLine = false; } else { sb.Append(' '); } sb.Append(word); if (sb.Length >= s_wrapLength) { lines.Add(sb.ToString()); sb.Clear(); sb.Append(indent); firstInLine = true; } } if (sb.ToString().Trim() != string.Empty) { lines.Add(sb.ToString()); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { internal class DocCommentFormatter { private const int s_indentSize = 2; private const int s_wrapLength = 80; private static readonly string s_summaryHeader = FeaturesResources.Summary_colon; private static readonly string s_paramHeader = FeaturesResources.Parameters_colon; private const string s_labelFormat = "{0}:"; private static readonly string s_typeParameterHeader = FeaturesResources.Type_parameters_colon; private static readonly string s_returnsHeader = FeaturesResources.Returns_colon; private static readonly string s_valueHeader = FeaturesResources.Value_colon; private static readonly string s_exceptionsHeader = FeaturesResources.Exceptions_colon; private static readonly string s_remarksHeader = FeaturesResources.Remarks_colon; internal static ImmutableArray<string> Format(IDocumentationCommentFormattingService docCommentFormattingService, DocumentationComment docComment) { var formattedCommentLinesBuilder = ArrayBuilder<string>.GetInstance(); var lineBuilder = new StringBuilder(); var formattedSummaryText = docCommentFormattingService.Format(docComment.SummaryText); if (!string.IsNullOrWhiteSpace(formattedSummaryText)) { formattedCommentLinesBuilder.Add(s_summaryHeader); formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedSummaryText)); } var parameterNames = docComment.ParameterNames; if (parameterNames.Length > 0) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_paramHeader); for (var i = 0; i < parameterNames.Length; i++) { if (i != 0) { formattedCommentLinesBuilder.Add(string.Empty); } lineBuilder.Clear(); lineBuilder.Append(' ', s_indentSize); lineBuilder.Append(string.Format(s_labelFormat, parameterNames[i])); formattedCommentLinesBuilder.Add(lineBuilder.ToString()); var rawParameterText = docComment.GetParameterText(parameterNames[i]); var formattedParameterText = docCommentFormattingService.Format(rawParameterText); if (!string.IsNullOrWhiteSpace(formattedParameterText)) { formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedParameterText)); } } } var typeParameterNames = docComment.TypeParameterNames; if (typeParameterNames.Length > 0) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_typeParameterHeader); for (var i = 0; i < typeParameterNames.Length; i++) { if (i != 0) { formattedCommentLinesBuilder.Add(string.Empty); } lineBuilder.Clear(); lineBuilder.Append(' ', s_indentSize); lineBuilder.Append(string.Format(s_labelFormat, typeParameterNames[i])); formattedCommentLinesBuilder.Add(lineBuilder.ToString()); var rawTypeParameterText = docComment.GetTypeParameterText(typeParameterNames[i]); var formattedTypeParameterText = docCommentFormattingService.Format(rawTypeParameterText); if (!string.IsNullOrWhiteSpace(formattedTypeParameterText)) { formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedTypeParameterText)); } } } var formattedReturnsText = docCommentFormattingService.Format(docComment.ReturnsText); if (!string.IsNullOrWhiteSpace(formattedReturnsText)) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_returnsHeader); formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedReturnsText)); } var formattedValueText = docCommentFormattingService.Format(docComment.ValueText); if (!string.IsNullOrWhiteSpace(formattedValueText)) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_valueHeader); formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedValueText)); } var exceptionTypes = docComment.ExceptionTypes; if (exceptionTypes.Length > 0) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_exceptionsHeader); for (var i = 0; i < exceptionTypes.Length; i++) { var rawExceptionTexts = docComment.GetExceptionTexts(exceptionTypes[i]); for (var j = 0; j < rawExceptionTexts.Length; j++) { if (i != 0 || j != 0) { formattedCommentLinesBuilder.Add(string.Empty); } lineBuilder.Clear(); lineBuilder.Append(' ', s_indentSize); lineBuilder.Append(string.Format(s_labelFormat, exceptionTypes[i])); formattedCommentLinesBuilder.Add(lineBuilder.ToString()); var formattedExceptionText = docCommentFormattingService.Format(rawExceptionTexts[j]); if (!string.IsNullOrWhiteSpace(formattedExceptionText)) { formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedExceptionText)); } } } } var formattedRemarksText = docCommentFormattingService.Format(docComment.RemarksText); if (!string.IsNullOrWhiteSpace(formattedRemarksText)) { formattedCommentLinesBuilder.Add(string.Empty); formattedCommentLinesBuilder.Add(s_remarksHeader); formattedCommentLinesBuilder.AddRange(CreateWrappedTextFromRawText(formattedRemarksText)); } // Eliminate any blank lines at the beginning. while (formattedCommentLinesBuilder.Count > 0 && formattedCommentLinesBuilder[0].Length == 0) { formattedCommentLinesBuilder.RemoveAt(0); } // Eliminate any blank lines at the end. while (formattedCommentLinesBuilder.Count > 0 && formattedCommentLinesBuilder[^1].Length == 0) { formattedCommentLinesBuilder.RemoveAt(formattedCommentLinesBuilder.Count - 1); } return formattedCommentLinesBuilder.ToImmutableAndFree(); } private static ImmutableArray<string> CreateWrappedTextFromRawText(string rawText) { using var _ = ArrayBuilder<string>.GetInstance(out var lines); // First split the string into constituent lines. var split = rawText.Split(new[] { "\r\n" }, System.StringSplitOptions.None); // Now split each line into multiple lines. foreach (var item in split) SplitRawLineIntoFormattedLines(item, lines); return lines.ToImmutable(); } private static void SplitRawLineIntoFormattedLines( string line, ArrayBuilder<string> lines) { var indent = new StringBuilder().Append(' ', s_indentSize * 2).ToString(); var words = line.Split(' '); var firstInLine = true; var sb = new StringBuilder(); sb.Append(indent); foreach (var word in words) { // We must always append at least one word to ensure progress. if (firstInLine) { firstInLine = false; } else { sb.Append(' '); } sb.Append(word); if (sb.Length >= s_wrapLength) { lines.Add(sb.ToString()); sb.Clear(); sb.Append(indent); firstInLine = true; } } if (sb.ToString().Trim() != string.Empty) { lines.Add(sb.ToString()); } } } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/EditorFeatures/Core/EditorConfigSettings/Data/CodeStyle/CodeStyleSetting.EnumCodeStyleSetting.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data { internal abstract partial class CodeStyleSetting { private class EnumCodeStyleSetting<T> : EnumCodeStyleSettingBase<T> where T : Enum { private readonly Option2<CodeStyleOption2<T>> _option; private readonly AnalyzerConfigOptions _editorConfigOptions; private readonly OptionSet _visualStudioOptions; public EnumCodeStyleSetting(Option2<CodeStyleOption2<T>> option, string description, T[] enumValues, string[] valueDescriptions, AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updater, string fileName) : base(description, enumValues, valueDescriptions, option.Group.Description, updater) { _option = option; _editorConfigOptions = editorConfigOptions; _visualStudioOptions = visualStudioOptions; Location = new SettingLocation(IsDefinedInEditorConfig ? LocationKind.EditorConfig : LocationKind.VisualStudio, fileName); } public override bool IsDefinedInEditorConfig => _editorConfigOptions.TryGetEditorConfigOption<CodeStyleOption2<T>>(_option, out _); public override SettingLocation Location { get; protected set; } protected override void ChangeSeverity(NotificationOption2 severity) { ICodeStyleOption option = GetOption(); Location = Location with { LocationKind = LocationKind.EditorConfig }; Updater.QueueUpdate(_option, option.WithNotification(severity)); } public override void ChangeValue(int valueIndex) { ICodeStyleOption option = GetOption(); Location = Location with { LocationKind = LocationKind.EditorConfig }; Updater.QueueUpdate(_option, option.WithValue(_enumValues[valueIndex])); } protected override CodeStyleOption2<T> GetOption() => _editorConfigOptions.TryGetEditorConfigOption(_option, out CodeStyleOption2<T>? value) && value is not null ? value : _visualStudioOptions.GetOption(_option); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data { internal abstract partial class CodeStyleSetting { private class EnumCodeStyleSetting<T> : EnumCodeStyleSettingBase<T> where T : Enum { private readonly Option2<CodeStyleOption2<T>> _option; private readonly AnalyzerConfigOptions _editorConfigOptions; private readonly OptionSet _visualStudioOptions; public EnumCodeStyleSetting(Option2<CodeStyleOption2<T>> option, string description, T[] enumValues, string[] valueDescriptions, AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updater, string fileName) : base(description, enumValues, valueDescriptions, option.Group.Description, updater) { _option = option; _editorConfigOptions = editorConfigOptions; _visualStudioOptions = visualStudioOptions; Location = new SettingLocation(IsDefinedInEditorConfig ? LocationKind.EditorConfig : LocationKind.VisualStudio, fileName); } public override bool IsDefinedInEditorConfig => _editorConfigOptions.TryGetEditorConfigOption<CodeStyleOption2<T>>(_option, out _); public override SettingLocation Location { get; protected set; } protected override void ChangeSeverity(NotificationOption2 severity) { ICodeStyleOption option = GetOption(); Location = Location with { LocationKind = LocationKind.EditorConfig }; Updater.QueueUpdate(_option, option.WithNotification(severity)); } public override void ChangeValue(int valueIndex) { ICodeStyleOption option = GetOption(); Location = Location with { LocationKind = LocationKind.EditorConfig }; Updater.QueueUpdate(_option, option.WithValue(_enumValues[valueIndex])); } protected override CodeStyleOption2<T> GetOption() => _editorConfigOptions.TryGetEditorConfigOption(_option, out CodeStyleOption2<T>? value) && value is not null ? value : _visualStudioOptions.GetOption(_option); } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Features/Core/Portable/InvertConditional/AbstractInvertConditionalCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.InvertConditional { internal abstract class AbstractInvertConditionalCodeRefactoringProvider<TConditionalExpressionSyntax> : CodeRefactoringProvider where TConditionalExpressionSyntax : SyntaxNode { protected abstract bool ShouldOffer(TConditionalExpressionSyntax conditional); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; var conditional = await FindConditionalAsync(document, span, cancellationToken).ConfigureAwait(false); if (conditional == null || !ShouldOffer(conditional)) { return; } context.RegisterRefactoring(new MyCodeAction( c => InvertConditionalAsync(document, span, c)), conditional.Span); } private static async Task<TConditionalExpressionSyntax?> FindConditionalAsync( Document document, TextSpan span, CancellationToken cancellationToken) => await document.TryGetRelevantNodeAsync<TConditionalExpressionSyntax>(span, cancellationToken).ConfigureAwait(false); private static async Task<Document> InvertConditionalAsync( Document document, TextSpan span, CancellationToken cancellationToken) { var conditional = await FindConditionalAsync(document, span, cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(conditional); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); editor.Generator.SyntaxFacts.GetPartsOfConditionalExpression(conditional, out var condition, out var whenTrue, out var whenFalse); editor.ReplaceNode(condition, editor.Generator.Negate(editor.Generator.SyntaxGeneratorInternal, condition, semanticModel, cancellationToken)); editor.ReplaceNode(whenTrue, whenFalse.WithTriviaFrom(whenTrue)); editor.ReplaceNode(whenFalse, whenTrue.WithTriviaFrom(whenFalse)); return document.WithSyntaxRoot(editor.GetChangedRoot()); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(FeaturesResources.Invert_conditional, createChangedDocument, nameof(FeaturesResources.Invert_conditional)) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.InvertConditional { internal abstract class AbstractInvertConditionalCodeRefactoringProvider<TConditionalExpressionSyntax> : CodeRefactoringProvider where TConditionalExpressionSyntax : SyntaxNode { protected abstract bool ShouldOffer(TConditionalExpressionSyntax conditional); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; var conditional = await FindConditionalAsync(document, span, cancellationToken).ConfigureAwait(false); if (conditional == null || !ShouldOffer(conditional)) { return; } context.RegisterRefactoring(new MyCodeAction( c => InvertConditionalAsync(document, span, c)), conditional.Span); } private static async Task<TConditionalExpressionSyntax?> FindConditionalAsync( Document document, TextSpan span, CancellationToken cancellationToken) => await document.TryGetRelevantNodeAsync<TConditionalExpressionSyntax>(span, cancellationToken).ConfigureAwait(false); private static async Task<Document> InvertConditionalAsync( Document document, TextSpan span, CancellationToken cancellationToken) { var conditional = await FindConditionalAsync(document, span, cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(conditional); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); editor.Generator.SyntaxFacts.GetPartsOfConditionalExpression(conditional, out var condition, out var whenTrue, out var whenFalse); editor.ReplaceNode(condition, editor.Generator.Negate(editor.Generator.SyntaxGeneratorInternal, condition, semanticModel, cancellationToken)); editor.ReplaceNode(whenTrue, whenFalse.WithTriviaFrom(whenTrue)); editor.ReplaceNode(whenFalse, whenTrue.WithTriviaFrom(whenFalse)); return document.WithSyntaxRoot(editor.GetChangedRoot()); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(FeaturesResources.Invert_conditional, createChangedDocument, nameof(FeaturesResources.Invert_conditional)) { } } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Features/Core/Portable/Navigation/IDocumentNavigationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Navigation { internal interface IDocumentNavigationService : IWorkspaceService { /// <summary> /// Determines whether it is possible to navigate to the given position in the specified document. /// </summary> bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given line/offset in the specified document. /// </summary> bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given virtual position in the specified document. /// </summary> bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken); /// <summary> /// Navigates to the given position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken); /// <summary> /// Navigates to the given line/offset in the specified document, opening it if necessary. /// </summary> bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken); /// <summary> /// Navigates to the given virtual position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken); } internal static class IDocumentNavigationServiceExtensions { public static bool CanNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.CanNavigateToPosition(workspace, documentId, position, virtualSpace: 0, cancellationToken); public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options: null, cancellationToken); public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options, allowInvalidSpan: false, cancellationToken); public static bool TryNavigateToLineAndOffset(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => service.TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options: null, cancellationToken); public static bool TryNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.TryNavigateToPosition(workspace, documentId, position, virtualSpace: 0, options: null, 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.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Navigation { internal interface IDocumentNavigationService : IWorkspaceService { /// <summary> /// Determines whether it is possible to navigate to the given position in the specified document. /// </summary> bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given line/offset in the specified document. /// </summary> bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken); /// <summary> /// Determines whether it is possible to navigate to the given virtual position in the specified document. /// </summary> bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken); /// <summary> /// Navigates to the given position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, bool allowInvalidSpan, CancellationToken cancellationToken); /// <summary> /// Navigates to the given line/offset in the specified document, opening it if necessary. /// </summary> bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken); /// <summary> /// Navigates to the given virtual position in the specified document, opening it if necessary. /// </summary> bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken); } internal static class IDocumentNavigationServiceExtensions { public static bool CanNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.CanNavigateToPosition(workspace, documentId, position, virtualSpace: 0, cancellationToken); public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options: null, cancellationToken); public static bool TryNavigateToSpan(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken) => service.TryNavigateToSpan(workspace, documentId, textSpan, options, allowInvalidSpan: false, cancellationToken); public static bool TryNavigateToLineAndOffset(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => service.TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options: null, cancellationToken); public static bool TryNavigateToPosition(this IDocumentNavigationService service, Workspace workspace, DocumentId documentId, int position, CancellationToken cancellationToken) => service.TryNavigateToPosition(workspace, documentId, position, virtualSpace: 0, options: null, cancellationToken); } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxNodeExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SyntaxNodeExtensions { public static SyntaxNode GetRequiredParent(this SyntaxNode node) => node.Parent ?? throw new InvalidOperationException("Node's parent was null"); public static IEnumerable<SyntaxNodeOrToken> DepthFirstTraversal(this SyntaxNode node) => SyntaxNodeOrTokenExtensions.DepthFirstTraversal(node); public static IEnumerable<SyntaxNode> GetAncestors(this SyntaxNode node) { var current = node.Parent; while (current != null) { yield return current; current = current.GetParent(ascendOutOfTrivia: true); } } public static IEnumerable<TNode> GetAncestors<TNode>(this SyntaxNode node) where TNode : SyntaxNode { var current = node.Parent; while (current != null) { if (current is TNode tNode) { yield return tNode; } current = current.GetParent(ascendOutOfTrivia: true); } } public static TNode? GetAncestor<TNode>(this SyntaxNode node) where TNode : SyntaxNode { var current = node.Parent; while (current != null) { if (current is TNode tNode) { return tNode; } current = current.GetParent(ascendOutOfTrivia: true); } return null; } public static TNode? GetAncestorOrThis<TNode>(this SyntaxNode? node) where TNode : SyntaxNode { return node?.GetAncestorsOrThis<TNode>().FirstOrDefault(); } public static IEnumerable<TNode> GetAncestorsOrThis<TNode>(this SyntaxNode? node) where TNode : SyntaxNode { var current = node; while (current != null) { if (current is TNode tNode) { yield return tNode; } current = current.GetParent(ascendOutOfTrivia: true); } } public static bool HasAncestor<TNode>(this SyntaxNode node) where TNode : SyntaxNode { return node.GetAncestors<TNode>().Any(); } public static IEnumerable<TSyntaxNode> Traverse<TSyntaxNode>( this SyntaxNode node, TextSpan searchSpan, Func<SyntaxNode, bool> predicate) where TSyntaxNode : SyntaxNode { Contract.ThrowIfNull(node); var nodes = new LinkedList<SyntaxNode>(); nodes.AddFirst(node); while (nodes.Count > 0) { var currentNode = nodes.First!.Value; nodes.RemoveFirst(); if (currentNode != null && searchSpan.Contains(currentNode.FullSpan) && predicate(currentNode)) { if (currentNode is TSyntaxNode tSyntax) { yield return tSyntax; } nodes.AddRangeAtHead(currentNode.ChildNodes()); } } } public static bool CheckParent<T>([NotNullWhen(returnValue: true)] this SyntaxNode? node, Func<T, bool> valueChecker) where T : SyntaxNode { if (!(node?.Parent is T parentNode)) { return false; } return valueChecker(parentNode); } /// <summary> /// Returns true if is a given token is a child token of a certain type of parent node. /// </summary> /// <typeparam name="TParent">The type of the parent node.</typeparam> /// <param name="node">The node that we are testing.</param> /// <param name="childGetter">A function that, when given the parent node, returns the child token we are interested in.</param> public static bool IsChildNode<TParent>(this SyntaxNode node, Func<TParent, SyntaxNode?> childGetter) where TParent : SyntaxNode { var ancestor = node.GetAncestor<TParent>(); if (ancestor == null) { return false; } var ancestorNode = childGetter(ancestor); return node == ancestorNode; } /// <summary> /// Returns true if this node is found underneath the specified child in the given parent. /// </summary> public static bool IsFoundUnder<TParent>(this SyntaxNode node, Func<TParent, SyntaxNode?> childGetter) where TParent : SyntaxNode { var ancestor = node.GetAncestor<TParent>(); if (ancestor == null) { return false; } var child = childGetter(ancestor); // See if node passes through child on the way up to ancestor. return node.GetAncestorsOrThis<SyntaxNode>().Contains(child); } public static SyntaxNode GetCommonRoot(this SyntaxNode node1, SyntaxNode node2) { Contract.ThrowIfTrue(node1.RawKind == 0 || node2.RawKind == 0); // find common starting node from two nodes. // as long as two nodes belong to same tree, there must be at least one common root (Ex, compilation unit) var ancestors = node1.GetAncestorsOrThis<SyntaxNode>(); var set = new HashSet<SyntaxNode>(node2.GetAncestorsOrThis<SyntaxNode>()); return ancestors.First(set.Contains); } public static int Width(this SyntaxNode node) => node.Span.Length; public static int FullWidth(this SyntaxNode node) => node.FullSpan.Length; public static SyntaxNode? FindInnermostCommonNode(this IEnumerable<SyntaxNode> nodes, Func<SyntaxNode, bool> predicate) => nodes.FindInnermostCommonNode()?.FirstAncestorOrSelf(predicate); public static SyntaxNode? FindInnermostCommonNode(this IEnumerable<SyntaxNode> nodes) { // Two collections we use to make this operation as efficient as possible. One is a // stack of the current shared ancestor chain shared by all nodes so far. It starts // with the full ancestor chain of the first node, and can only get smaller over time. // It should be log(n) with the size of the tree as it's only storing a parent chain. // // The second is a set with the exact same contents as the array. It's used for O(1) // lookups if a node is in the ancestor chain or not. using var _1 = ArrayBuilder<SyntaxNode>.GetInstance(out var commonAncestorsStack); using var _2 = PooledHashSet<SyntaxNode>.GetInstance(out var commonAncestorsSet); var first = true; foreach (var node in nodes) { // If we're just starting, initialize the ancestors set/array with the ancestors of // this node. if (first) { first = false; foreach (var ancestor in node.ValueAncestorsAndSelf()) { commonAncestorsSet.Add(ancestor); commonAncestorsStack.Add(ancestor); } // Reverse the ancestors stack so that we go downwards with CompilationUnit at // the start, and then go down to this starting node. This enables cheap // popping later on. commonAncestorsStack.ReverseContents(); continue; } // On a subsequent node, walk its ancestors to find the first match var commonAncestor = FindCommonAncestor(node, commonAncestorsSet); if (commonAncestor == null) { // So this shouldn't happen as long as the nodes are from the same tree. And // the caller really shouldn't be calling from different trees. However, the // previous impl supported that, so continue to have this behavior. // // If this doesn't fire, that means that all callers seem sane. If it does // fire, we can relax this (but we should consider fixing the caller). Debug.Fail("Could not find common ancestor."); return null; } // Now remove everything in the ancestors array up to that common ancestor. This is // generally quite efficient. Either we settle on a common node quickly. and don't // need to do work here, or we keep tossing data from our common-ancestor scratch // pad, making further work faster. while (commonAncestorsStack.Count > 0 && commonAncestorsStack.Peek() != commonAncestor) { commonAncestorsSet.Remove(commonAncestorsStack.Peek()); commonAncestorsStack.Pop(); } if (commonAncestorsStack.Count == 0) { // So this shouldn't happen as long as the nodes are from the same tree. And // the caller really shouldn't be calling from different trees. However, the // previous impl supported that, so continue to have this behavior. // // If this doesn't fire, that means that all callers seem sane. If it does // fire, we can relax this (but we should consider fixing the caller). Debug.Fail("Could not find common ancestor."); return null; } } // The common ancestor is the one at the end of the ancestor stack. This could be empty // in the case where the caller passed in an empty enumerable of nodes. return commonAncestorsStack.Count == 0 ? null : commonAncestorsStack.Peek(); // local functions static SyntaxNode? FindCommonAncestor(SyntaxNode node, HashSet<SyntaxNode> commonAncestorsSet) { foreach (var ancestor in node.ValueAncestorsAndSelf()) { if (commonAncestorsSet.Contains(ancestor)) return ancestor; } return null; } } public static TSyntaxNode? FindInnermostCommonNode<TSyntaxNode>(this IEnumerable<SyntaxNode> nodes) where TSyntaxNode : SyntaxNode => (TSyntaxNode?)nodes.FindInnermostCommonNode(t => t is TSyntaxNode); /// <summary> /// create a new root node from the given root after adding annotations to the tokens /// /// tokens should belong to the given root /// </summary> public static SyntaxNode AddAnnotations(this SyntaxNode root, IEnumerable<Tuple<SyntaxToken, SyntaxAnnotation>> pairs) { Contract.ThrowIfNull(root); Contract.ThrowIfNull(pairs); var tokenMap = pairs.GroupBy(p => p.Item1, p => p.Item2).ToDictionary(g => g.Key, g => g.ToArray()); return root.ReplaceTokens(tokenMap.Keys, (o, n) => o.WithAdditionalAnnotations(tokenMap[o])); } /// <summary> /// create a new root node from the given root after adding annotations to the nodes /// /// nodes should belong to the given root /// </summary> public static SyntaxNode AddAnnotations(this SyntaxNode root, IEnumerable<Tuple<SyntaxNode, SyntaxAnnotation>> pairs) { Contract.ThrowIfNull(root); Contract.ThrowIfNull(pairs); var tokenMap = pairs.GroupBy(p => p.Item1, p => p.Item2).ToDictionary(g => g.Key, g => g.ToArray()); return root.ReplaceNodes(tokenMap.Keys, (o, n) => o.WithAdditionalAnnotations(tokenMap[o])); } public static TextSpan GetContainedSpan(this IEnumerable<SyntaxNode> nodes) { Contract.ThrowIfNull(nodes); Contract.ThrowIfFalse(nodes.Any()); var fullSpan = nodes.First().Span; foreach (var node in nodes) { fullSpan = TextSpan.FromBounds( Math.Min(fullSpan.Start, node.SpanStart), Math.Max(fullSpan.End, node.Span.End)); } return fullSpan; } public static IEnumerable<TextSpan> GetContiguousSpans( this IEnumerable<SyntaxNode> nodes, Func<SyntaxNode, SyntaxToken>? getLastToken = null) { (SyntaxNode node, TextSpan textSpan)? previous = null; // Sort the nodes in source location order. foreach (var node in nodes.OrderBy(n => n.SpanStart)) { TextSpan textSpan; if (previous == null) { textSpan = node.Span; } else { var lastToken = getLastToken?.Invoke(previous.Value.node) ?? previous.Value.node.GetLastToken(); if (lastToken.GetNextToken(includeDirectives: true) == node.GetFirstToken()) { // Expand the span textSpan = TextSpan.FromBounds(previous.Value.textSpan.Start, node.Span.End); } else { // Return the last span, and start a new one yield return previous.Value.textSpan; textSpan = node.Span; } } previous = (node, textSpan); } if (previous.HasValue) { yield return previous.Value.textSpan; } } public static bool OverlapsHiddenPosition(this SyntaxNode node, CancellationToken cancellationToken) => node.OverlapsHiddenPosition(node.Span, cancellationToken); public static bool OverlapsHiddenPosition(this SyntaxNode node, TextSpan span, CancellationToken cancellationToken) => node.SyntaxTree.OverlapsHiddenPosition(span, cancellationToken); public static bool OverlapsHiddenPosition(this SyntaxNode declaration, SyntaxNode startNode, SyntaxNode endNode, CancellationToken cancellationToken) { var start = startNode.Span.End; var end = endNode.SpanStart; var textSpan = TextSpan.FromBounds(start, end); return declaration.OverlapsHiddenPosition(textSpan, cancellationToken); } public static IEnumerable<T> GetAnnotatedNodes<T>(this SyntaxNode node, SyntaxAnnotation syntaxAnnotation) where T : SyntaxNode => node.GetAnnotatedNodesAndTokens(syntaxAnnotation).Select(n => n.AsNode()).OfType<T>(); /// <summary> /// Creates a new tree of nodes from the existing tree with the specified old nodes replaced with a newly computed nodes. /// </summary> /// <param name="root">The root of the tree that contains all the specified nodes.</param> /// <param name="nodes">The nodes from the tree to be replaced.</param> /// <param name="computeReplacementAsync">A function that computes a replacement node for /// the argument nodes. The first argument is one of the original specified nodes. The second argument is /// the same node possibly rewritten with replaced descendants.</param> /// <param name="cancellationToken"></param> public static Task<TRootNode> ReplaceNodesAsync<TRootNode>( this TRootNode root, IEnumerable<SyntaxNode> nodes, Func<SyntaxNode, SyntaxNode, CancellationToken, Task<SyntaxNode>> computeReplacementAsync, CancellationToken cancellationToken) where TRootNode : SyntaxNode { return root.ReplaceSyntaxAsync( nodes: nodes, computeReplacementNodeAsync: computeReplacementAsync, tokens: null, computeReplacementTokenAsync: null, trivia: null, computeReplacementTriviaAsync: null, cancellationToken: cancellationToken); } /// <summary> /// Creates a new tree of tokens from the existing tree with the specified old tokens replaced with a newly computed tokens. /// </summary> /// <param name="root">The root of the tree that contains all the specified tokens.</param> /// <param name="tokens">The tokens from the tree to be replaced.</param> /// <param name="computeReplacementAsync">A function that computes a replacement token for /// the argument tokens. The first argument is one of the originally specified tokens. The second argument is /// the same token possibly rewritten with replaced trivia.</param> /// <param name="cancellationToken"></param> public static Task<TRootNode> ReplaceTokensAsync<TRootNode>( this TRootNode root, IEnumerable<SyntaxToken> tokens, Func<SyntaxToken, SyntaxToken, CancellationToken, Task<SyntaxToken>> computeReplacementAsync, CancellationToken cancellationToken) where TRootNode : SyntaxNode { return root.ReplaceSyntaxAsync( nodes: null, computeReplacementNodeAsync: null, tokens: tokens, computeReplacementTokenAsync: computeReplacementAsync, trivia: null, computeReplacementTriviaAsync: null, cancellationToken: cancellationToken); } public static Task<TRoot> ReplaceTriviaAsync<TRoot>( this TRoot root, IEnumerable<SyntaxTrivia> trivia, Func<SyntaxTrivia, SyntaxTrivia, CancellationToken, Task<SyntaxTrivia>> computeReplacementAsync, CancellationToken cancellationToken) where TRoot : SyntaxNode { return root.ReplaceSyntaxAsync( nodes: null, computeReplacementNodeAsync: null, tokens: null, computeReplacementTokenAsync: null, trivia: trivia, computeReplacementTriviaAsync: computeReplacementAsync, cancellationToken: cancellationToken); } public static async Task<TRoot> ReplaceSyntaxAsync<TRoot>( this TRoot root, IEnumerable<SyntaxNode>? nodes, Func<SyntaxNode, SyntaxNode, CancellationToken, Task<SyntaxNode>>? computeReplacementNodeAsync, IEnumerable<SyntaxToken>? tokens, Func<SyntaxToken, SyntaxToken, CancellationToken, Task<SyntaxToken>>? computeReplacementTokenAsync, IEnumerable<SyntaxTrivia>? trivia, Func<SyntaxTrivia, SyntaxTrivia, CancellationToken, Task<SyntaxTrivia>>? computeReplacementTriviaAsync, CancellationToken cancellationToken) where TRoot : SyntaxNode { // index all nodes, tokens and trivia by the full spans they cover var nodesToReplace = nodes != null ? nodes.ToDictionary(n => n.FullSpan) : new Dictionary<TextSpan, SyntaxNode>(); var tokensToReplace = tokens != null ? tokens.ToDictionary(t => t.FullSpan) : new Dictionary<TextSpan, SyntaxToken>(); var triviaToReplace = trivia != null ? trivia.ToDictionary(t => t.FullSpan) : new Dictionary<TextSpan, SyntaxTrivia>(); var nodeReplacements = new Dictionary<SyntaxNode, SyntaxNode>(); var tokenReplacements = new Dictionary<SyntaxToken, SyntaxToken>(); var triviaReplacements = new Dictionary<SyntaxTrivia, SyntaxTrivia>(); var retryAnnotations = new AnnotationTable<object>("RetryReplace"); var spans = new List<TextSpan>(nodesToReplace.Count + tokensToReplace.Count + triviaToReplace.Count); spans.AddRange(nodesToReplace.Keys); spans.AddRange(tokensToReplace.Keys); spans.AddRange(triviaToReplace.Keys); while (spans.Count > 0) { // sort the spans of the items to be replaced so we can tell if any overlap spans.Sort((x, y) => { // order by end offset, and then by length var d = x.End - y.End; if (d == 0) { d = x.Length - y.Length; } return d; }); // compute replacements for all nodes that will go in the same batch // only spans that do not overlap go in the same batch. TextSpan previous = default; foreach (var span in spans) { // only add to replacement map if we don't intersect with the previous node. This taken with the sort order // should ensure that parent nodes are not processed in the same batch as child nodes. if (previous == default || !previous.IntersectsWith(span)) { if (nodesToReplace.TryGetValue(span, out var currentNode)) { var original = (SyntaxNode?)retryAnnotations.GetAnnotations(currentNode).SingleOrDefault() ?? currentNode; var newNode = await computeReplacementNodeAsync!(original, currentNode, cancellationToken).ConfigureAwait(false); nodeReplacements[currentNode] = newNode; } else if (tokensToReplace.TryGetValue(span, out var currentToken)) { var original = (SyntaxToken?)retryAnnotations.GetAnnotations(currentToken).SingleOrDefault() ?? currentToken; var newToken = await computeReplacementTokenAsync!(original, currentToken, cancellationToken).ConfigureAwait(false); tokenReplacements[currentToken] = newToken; } else if (triviaToReplace.TryGetValue(span, out var currentTrivia)) { var original = (SyntaxTrivia?)retryAnnotations.GetAnnotations(currentTrivia).SingleOrDefault() ?? currentTrivia; var newTrivia = await computeReplacementTriviaAsync!(original, currentTrivia, cancellationToken).ConfigureAwait(false); triviaReplacements[currentTrivia] = newTrivia; } } previous = span; } var retryNodes = false; var retryTokens = false; var retryTrivia = false; // replace nodes in batch // submit all nodes so we can annotate the ones we don't replace root = root.ReplaceSyntax( nodes: nodesToReplace.Values, computeReplacementNode: (original, rewritten) => { if (rewritten != original || !nodeReplacements.TryGetValue(original, out var replaced)) { // the subtree did change, or we didn't have a replacement for it in this batch // so we need to add an annotation so we can find this node again for the next batch. replaced = retryAnnotations.WithAdditionalAnnotations(rewritten, original); retryNodes = true; } return replaced; }, tokens: tokensToReplace.Values, computeReplacementToken: (original, rewritten) => { if (rewritten != original || !tokenReplacements.TryGetValue(original, out var replaced)) { // the subtree did change, or we didn't have a replacement for it in this batch // so we need to add an annotation so we can find this node again for the next batch. replaced = retryAnnotations.WithAdditionalAnnotations(rewritten, original); retryTokens = true; } return replaced; }, trivia: triviaToReplace.Values, computeReplacementTrivia: (original, rewritten) => { if (!triviaReplacements.TryGetValue(original, out var replaced)) { // the subtree did change, or we didn't have a replacement for it in this batch // so we need to add an annotation so we can find this node again for the next batch. replaced = retryAnnotations.WithAdditionalAnnotations(rewritten, original); retryTrivia = true; } return replaced; }); nodesToReplace.Clear(); tokensToReplace.Clear(); triviaToReplace.Clear(); spans.Clear(); // prepare next batch out of all remaining annotated nodes if (retryNodes) { nodesToReplace = retryAnnotations.GetAnnotatedNodes(root).ToDictionary(n => n.FullSpan); spans.AddRange(nodesToReplace.Keys); } if (retryTokens) { tokensToReplace = retryAnnotations.GetAnnotatedTokens(root).ToDictionary(t => t.FullSpan); spans.AddRange(tokensToReplace.Keys); } if (retryTrivia) { triviaToReplace = retryAnnotations.GetAnnotatedTrivia(root).ToDictionary(t => t.FullSpan); spans.AddRange(triviaToReplace.Keys); } } return root; } /// <summary> /// Look inside a trivia list for a skipped token that contains the given position. /// </summary> private static readonly Func<SyntaxTriviaList, int, SyntaxToken> s_findSkippedTokenForward = FindSkippedTokenForward; /// <summary> /// Look inside a trivia list for a skipped token that contains the given position. /// </summary> private static SyntaxToken FindSkippedTokenForward(SyntaxTriviaList triviaList, int position) { foreach (var trivia in triviaList) { if (trivia.HasStructure) { if (trivia.GetStructure() is ISkippedTokensTriviaSyntax skippedTokensTrivia) { foreach (var token in skippedTokensTrivia.Tokens) { if (token.Span.Length > 0 && position <= token.Span.End) { return token; } } } } } return default; } /// <summary> /// Look inside a trivia list for a skipped token that contains the given position. /// </summary> private static readonly Func<SyntaxTriviaList, int, SyntaxToken> s_findSkippedTokenBackward = FindSkippedTokenBackward; /// <summary> /// Look inside a trivia list for a skipped token that contains the given position. /// </summary> private static SyntaxToken FindSkippedTokenBackward(SyntaxTriviaList triviaList, int position) { foreach (var trivia in triviaList.Reverse()) { if (trivia.HasStructure) { if (trivia.GetStructure() is ISkippedTokensTriviaSyntax skippedTokensTrivia) { foreach (var token in skippedTokensTrivia.Tokens) { if (token.Span.Length > 0 && token.SpanStart <= position) { return token; } } } } } return default; } private static SyntaxToken GetInitialToken( SyntaxNode root, int position, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) { return (position < root.FullSpan.End || !(root is ICompilationUnitSyntax)) ? root.FindToken(position, includeSkipped || includeDirectives || includeDocumentationComments) : root.GetLastToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true) .GetPreviousToken(includeZeroWidth: false, includeSkipped: includeSkipped, includeDirectives: includeDirectives, includeDocumentationComments: includeDocumentationComments); } /// <summary> /// If the position is inside of token, return that token; otherwise, return the token to the right. /// </summary> public static SyntaxToken FindTokenOnRightOfPosition( this SyntaxNode root, int position, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) { var findSkippedToken = includeSkipped ? s_findSkippedTokenForward : ((l, p) => default); var token = GetInitialToken(root, position, includeSkipped, includeDirectives, includeDocumentationComments); if (position < token.SpanStart) { var skippedToken = findSkippedToken(token.LeadingTrivia, position); token = skippedToken.RawKind != 0 ? skippedToken : token; } else if (token.Span.End <= position) { do { var skippedToken = findSkippedToken(token.TrailingTrivia, position); token = skippedToken.RawKind != 0 ? skippedToken : token.GetNextToken(includeZeroWidth: false, includeSkipped: includeSkipped, includeDirectives: includeDirectives, includeDocumentationComments: includeDocumentationComments); } while (token.RawKind != 0 && token.Span.End <= position && token.Span.End <= root.FullSpan.End); } if (token.Span.Length == 0) { token = token.GetNextToken(); } return token; } /// <summary> /// If the position is inside of token, return that token; otherwise, return the token to the left. /// </summary> public static SyntaxToken FindTokenOnLeftOfPosition( this SyntaxNode root, int position, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) { var findSkippedToken = includeSkipped ? s_findSkippedTokenBackward : ((l, p) => default); var token = GetInitialToken(root, position, includeSkipped, includeDirectives, includeDocumentationComments); if (position <= token.SpanStart) { do { var skippedToken = findSkippedToken(token.LeadingTrivia, position); token = skippedToken.RawKind != 0 ? skippedToken : token.GetPreviousToken(includeZeroWidth: false, includeSkipped: includeSkipped, includeDirectives: includeDirectives, includeDocumentationComments: includeDocumentationComments); } while (position <= token.SpanStart && root.FullSpan.Start < token.SpanStart); } else if (token.Span.End < position) { var skippedToken = findSkippedToken(token.TrailingTrivia, position); token = skippedToken.RawKind != 0 ? skippedToken : token; } if (token.Span.Length == 0) { token = token.GetPreviousToken(); } return token; } public static T WithPrependedLeadingTrivia<T>( this T node, params SyntaxTrivia[] trivia) where T : SyntaxNode { if (trivia.Length == 0) { return node; } return node.WithPrependedLeadingTrivia((IEnumerable<SyntaxTrivia>)trivia); } public static T WithPrependedLeadingTrivia<T>( this T node, SyntaxTriviaList trivia) where T : SyntaxNode { if (trivia.Count == 0) { return node; } return node.WithLeadingTrivia(trivia.Concat(node.GetLeadingTrivia())); } public static T WithPrependedLeadingTrivia<T>( this T node, IEnumerable<SyntaxTrivia> trivia) where T : SyntaxNode { var list = new SyntaxTriviaList(); list = list.AddRange(trivia); return node.WithPrependedLeadingTrivia(list); } public static T WithAppendedTrailingTrivia<T>( this T node, params SyntaxTrivia[] trivia) where T : SyntaxNode { if (trivia.Length == 0) { return node; } return node.WithAppendedTrailingTrivia((IEnumerable<SyntaxTrivia>)trivia); } public static T WithAppendedTrailingTrivia<T>( this T node, SyntaxTriviaList trivia) where T : SyntaxNode { if (trivia.Count == 0) { return node; } return node.WithTrailingTrivia(node.GetTrailingTrivia().Concat(trivia)); } public static T WithAppendedTrailingTrivia<T>( this T node, IEnumerable<SyntaxTrivia> trivia) where T : SyntaxNode { var list = new SyntaxTriviaList(); list = list.AddRange(trivia); return node.WithAppendedTrailingTrivia(list); } public static T With<T>( this T node, IEnumerable<SyntaxTrivia> leadingTrivia, IEnumerable<SyntaxTrivia> trailingTrivia) where T : SyntaxNode { return node.WithLeadingTrivia(leadingTrivia).WithTrailingTrivia(trailingTrivia); } /// <summary> /// Creates a new token with the leading trivia removed. /// </summary> public static SyntaxToken WithoutLeadingTrivia(this SyntaxToken token) { return token.WithLeadingTrivia(default(SyntaxTriviaList)); } /// <summary> /// Creates a new token with the trailing trivia removed. /// </summary> public static SyntaxToken WithoutTrailingTrivia(this SyntaxToken token) { return token.WithTrailingTrivia(default(SyntaxTriviaList)); } // Copy of the same function in SyntaxNode.cs public static SyntaxNode? GetParent(this SyntaxNode node, bool ascendOutOfTrivia) { var parent = node.Parent; if (parent == null && ascendOutOfTrivia) { if (node is IStructuredTriviaSyntax structuredTrivia) { parent = structuredTrivia.ParentTrivia.Token.Parent; } } return parent; } public static TNode? FirstAncestorOrSelfUntil<TNode>(this SyntaxNode? node, Func<SyntaxNode, bool> predicate) where TNode : SyntaxNode { for (var current = node; current != null; current = current.GetParent(ascendOutOfTrivia: true)) { if (current is TNode tnode) { return tnode; } if (predicate(current)) { break; } } return null; } /// <summary> /// Gets a list of ancestor nodes (including this node) /// </summary> public static ValueAncestorsAndSelfEnumerable ValueAncestorsAndSelf(this SyntaxNode syntaxNode, bool ascendOutOfTrivia = true) => new(syntaxNode, ascendOutOfTrivia); public struct ValueAncestorsAndSelfEnumerable { private readonly SyntaxNode _syntaxNode; private readonly bool _ascendOutOfTrivia; public ValueAncestorsAndSelfEnumerable(SyntaxNode syntaxNode, bool ascendOutOfTrivia) { _syntaxNode = syntaxNode; _ascendOutOfTrivia = ascendOutOfTrivia; } public Enumerator GetEnumerator() => new(_syntaxNode, _ascendOutOfTrivia); public struct Enumerator { private readonly SyntaxNode _start; private readonly bool _ascendOutOfTrivia; public Enumerator(SyntaxNode syntaxNode, bool ascendOutOfTrivia) { _start = syntaxNode; _ascendOutOfTrivia = ascendOutOfTrivia; Current = null!; } public SyntaxNode Current { get; private set; } public bool MoveNext() { Current = Current == null ? _start : GetParent(Current, _ascendOutOfTrivia)!; return Current != null; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SyntaxNodeExtensions { public static SyntaxNode GetRequiredParent(this SyntaxNode node) => node.Parent ?? throw new InvalidOperationException("Node's parent was null"); public static IEnumerable<SyntaxNodeOrToken> DepthFirstTraversal(this SyntaxNode node) => SyntaxNodeOrTokenExtensions.DepthFirstTraversal(node); public static IEnumerable<SyntaxNode> GetAncestors(this SyntaxNode node) { var current = node.Parent; while (current != null) { yield return current; current = current.GetParent(ascendOutOfTrivia: true); } } public static IEnumerable<TNode> GetAncestors<TNode>(this SyntaxNode node) where TNode : SyntaxNode { var current = node.Parent; while (current != null) { if (current is TNode tNode) { yield return tNode; } current = current.GetParent(ascendOutOfTrivia: true); } } public static TNode? GetAncestor<TNode>(this SyntaxNode node) where TNode : SyntaxNode { var current = node.Parent; while (current != null) { if (current is TNode tNode) { return tNode; } current = current.GetParent(ascendOutOfTrivia: true); } return null; } public static TNode? GetAncestorOrThis<TNode>(this SyntaxNode? node) where TNode : SyntaxNode { return node?.GetAncestorsOrThis<TNode>().FirstOrDefault(); } public static IEnumerable<TNode> GetAncestorsOrThis<TNode>(this SyntaxNode? node) where TNode : SyntaxNode { var current = node; while (current != null) { if (current is TNode tNode) { yield return tNode; } current = current.GetParent(ascendOutOfTrivia: true); } } public static bool HasAncestor<TNode>(this SyntaxNode node) where TNode : SyntaxNode { return node.GetAncestors<TNode>().Any(); } public static IEnumerable<TSyntaxNode> Traverse<TSyntaxNode>( this SyntaxNode node, TextSpan searchSpan, Func<SyntaxNode, bool> predicate) where TSyntaxNode : SyntaxNode { Contract.ThrowIfNull(node); var nodes = new LinkedList<SyntaxNode>(); nodes.AddFirst(node); while (nodes.Count > 0) { var currentNode = nodes.First!.Value; nodes.RemoveFirst(); if (currentNode != null && searchSpan.Contains(currentNode.FullSpan) && predicate(currentNode)) { if (currentNode is TSyntaxNode tSyntax) { yield return tSyntax; } nodes.AddRangeAtHead(currentNode.ChildNodes()); } } } public static bool CheckParent<T>([NotNullWhen(returnValue: true)] this SyntaxNode? node, Func<T, bool> valueChecker) where T : SyntaxNode { if (!(node?.Parent is T parentNode)) { return false; } return valueChecker(parentNode); } /// <summary> /// Returns true if is a given token is a child token of a certain type of parent node. /// </summary> /// <typeparam name="TParent">The type of the parent node.</typeparam> /// <param name="node">The node that we are testing.</param> /// <param name="childGetter">A function that, when given the parent node, returns the child token we are interested in.</param> public static bool IsChildNode<TParent>(this SyntaxNode node, Func<TParent, SyntaxNode?> childGetter) where TParent : SyntaxNode { var ancestor = node.GetAncestor<TParent>(); if (ancestor == null) { return false; } var ancestorNode = childGetter(ancestor); return node == ancestorNode; } /// <summary> /// Returns true if this node is found underneath the specified child in the given parent. /// </summary> public static bool IsFoundUnder<TParent>(this SyntaxNode node, Func<TParent, SyntaxNode?> childGetter) where TParent : SyntaxNode { var ancestor = node.GetAncestor<TParent>(); if (ancestor == null) { return false; } var child = childGetter(ancestor); // See if node passes through child on the way up to ancestor. return node.GetAncestorsOrThis<SyntaxNode>().Contains(child); } public static SyntaxNode GetCommonRoot(this SyntaxNode node1, SyntaxNode node2) { Contract.ThrowIfTrue(node1.RawKind == 0 || node2.RawKind == 0); // find common starting node from two nodes. // as long as two nodes belong to same tree, there must be at least one common root (Ex, compilation unit) var ancestors = node1.GetAncestorsOrThis<SyntaxNode>(); var set = new HashSet<SyntaxNode>(node2.GetAncestorsOrThis<SyntaxNode>()); return ancestors.First(set.Contains); } public static int Width(this SyntaxNode node) => node.Span.Length; public static int FullWidth(this SyntaxNode node) => node.FullSpan.Length; public static SyntaxNode? FindInnermostCommonNode(this IEnumerable<SyntaxNode> nodes, Func<SyntaxNode, bool> predicate) => nodes.FindInnermostCommonNode()?.FirstAncestorOrSelf(predicate); public static SyntaxNode? FindInnermostCommonNode(this IEnumerable<SyntaxNode> nodes) { // Two collections we use to make this operation as efficient as possible. One is a // stack of the current shared ancestor chain shared by all nodes so far. It starts // with the full ancestor chain of the first node, and can only get smaller over time. // It should be log(n) with the size of the tree as it's only storing a parent chain. // // The second is a set with the exact same contents as the array. It's used for O(1) // lookups if a node is in the ancestor chain or not. using var _1 = ArrayBuilder<SyntaxNode>.GetInstance(out var commonAncestorsStack); using var _2 = PooledHashSet<SyntaxNode>.GetInstance(out var commonAncestorsSet); var first = true; foreach (var node in nodes) { // If we're just starting, initialize the ancestors set/array with the ancestors of // this node. if (first) { first = false; foreach (var ancestor in node.ValueAncestorsAndSelf()) { commonAncestorsSet.Add(ancestor); commonAncestorsStack.Add(ancestor); } // Reverse the ancestors stack so that we go downwards with CompilationUnit at // the start, and then go down to this starting node. This enables cheap // popping later on. commonAncestorsStack.ReverseContents(); continue; } // On a subsequent node, walk its ancestors to find the first match var commonAncestor = FindCommonAncestor(node, commonAncestorsSet); if (commonAncestor == null) { // So this shouldn't happen as long as the nodes are from the same tree. And // the caller really shouldn't be calling from different trees. However, the // previous impl supported that, so continue to have this behavior. // // If this doesn't fire, that means that all callers seem sane. If it does // fire, we can relax this (but we should consider fixing the caller). Debug.Fail("Could not find common ancestor."); return null; } // Now remove everything in the ancestors array up to that common ancestor. This is // generally quite efficient. Either we settle on a common node quickly. and don't // need to do work here, or we keep tossing data from our common-ancestor scratch // pad, making further work faster. while (commonAncestorsStack.Count > 0 && commonAncestorsStack.Peek() != commonAncestor) { commonAncestorsSet.Remove(commonAncestorsStack.Peek()); commonAncestorsStack.Pop(); } if (commonAncestorsStack.Count == 0) { // So this shouldn't happen as long as the nodes are from the same tree. And // the caller really shouldn't be calling from different trees. However, the // previous impl supported that, so continue to have this behavior. // // If this doesn't fire, that means that all callers seem sane. If it does // fire, we can relax this (but we should consider fixing the caller). Debug.Fail("Could not find common ancestor."); return null; } } // The common ancestor is the one at the end of the ancestor stack. This could be empty // in the case where the caller passed in an empty enumerable of nodes. return commonAncestorsStack.Count == 0 ? null : commonAncestorsStack.Peek(); // local functions static SyntaxNode? FindCommonAncestor(SyntaxNode node, HashSet<SyntaxNode> commonAncestorsSet) { foreach (var ancestor in node.ValueAncestorsAndSelf()) { if (commonAncestorsSet.Contains(ancestor)) return ancestor; } return null; } } public static TSyntaxNode? FindInnermostCommonNode<TSyntaxNode>(this IEnumerable<SyntaxNode> nodes) where TSyntaxNode : SyntaxNode => (TSyntaxNode?)nodes.FindInnermostCommonNode(t => t is TSyntaxNode); /// <summary> /// create a new root node from the given root after adding annotations to the tokens /// /// tokens should belong to the given root /// </summary> public static SyntaxNode AddAnnotations(this SyntaxNode root, IEnumerable<Tuple<SyntaxToken, SyntaxAnnotation>> pairs) { Contract.ThrowIfNull(root); Contract.ThrowIfNull(pairs); var tokenMap = pairs.GroupBy(p => p.Item1, p => p.Item2).ToDictionary(g => g.Key, g => g.ToArray()); return root.ReplaceTokens(tokenMap.Keys, (o, n) => o.WithAdditionalAnnotations(tokenMap[o])); } /// <summary> /// create a new root node from the given root after adding annotations to the nodes /// /// nodes should belong to the given root /// </summary> public static SyntaxNode AddAnnotations(this SyntaxNode root, IEnumerable<Tuple<SyntaxNode, SyntaxAnnotation>> pairs) { Contract.ThrowIfNull(root); Contract.ThrowIfNull(pairs); var tokenMap = pairs.GroupBy(p => p.Item1, p => p.Item2).ToDictionary(g => g.Key, g => g.ToArray()); return root.ReplaceNodes(tokenMap.Keys, (o, n) => o.WithAdditionalAnnotations(tokenMap[o])); } public static TextSpan GetContainedSpan(this IEnumerable<SyntaxNode> nodes) { Contract.ThrowIfNull(nodes); Contract.ThrowIfFalse(nodes.Any()); var fullSpan = nodes.First().Span; foreach (var node in nodes) { fullSpan = TextSpan.FromBounds( Math.Min(fullSpan.Start, node.SpanStart), Math.Max(fullSpan.End, node.Span.End)); } return fullSpan; } public static IEnumerable<TextSpan> GetContiguousSpans( this IEnumerable<SyntaxNode> nodes, Func<SyntaxNode, SyntaxToken>? getLastToken = null) { (SyntaxNode node, TextSpan textSpan)? previous = null; // Sort the nodes in source location order. foreach (var node in nodes.OrderBy(n => n.SpanStart)) { TextSpan textSpan; if (previous == null) { textSpan = node.Span; } else { var lastToken = getLastToken?.Invoke(previous.Value.node) ?? previous.Value.node.GetLastToken(); if (lastToken.GetNextToken(includeDirectives: true) == node.GetFirstToken()) { // Expand the span textSpan = TextSpan.FromBounds(previous.Value.textSpan.Start, node.Span.End); } else { // Return the last span, and start a new one yield return previous.Value.textSpan; textSpan = node.Span; } } previous = (node, textSpan); } if (previous.HasValue) { yield return previous.Value.textSpan; } } public static bool OverlapsHiddenPosition(this SyntaxNode node, CancellationToken cancellationToken) => node.OverlapsHiddenPosition(node.Span, cancellationToken); public static bool OverlapsHiddenPosition(this SyntaxNode node, TextSpan span, CancellationToken cancellationToken) => node.SyntaxTree.OverlapsHiddenPosition(span, cancellationToken); public static bool OverlapsHiddenPosition(this SyntaxNode declaration, SyntaxNode startNode, SyntaxNode endNode, CancellationToken cancellationToken) { var start = startNode.Span.End; var end = endNode.SpanStart; var textSpan = TextSpan.FromBounds(start, end); return declaration.OverlapsHiddenPosition(textSpan, cancellationToken); } public static IEnumerable<T> GetAnnotatedNodes<T>(this SyntaxNode node, SyntaxAnnotation syntaxAnnotation) where T : SyntaxNode => node.GetAnnotatedNodesAndTokens(syntaxAnnotation).Select(n => n.AsNode()).OfType<T>(); /// <summary> /// Creates a new tree of nodes from the existing tree with the specified old nodes replaced with a newly computed nodes. /// </summary> /// <param name="root">The root of the tree that contains all the specified nodes.</param> /// <param name="nodes">The nodes from the tree to be replaced.</param> /// <param name="computeReplacementAsync">A function that computes a replacement node for /// the argument nodes. The first argument is one of the original specified nodes. The second argument is /// the same node possibly rewritten with replaced descendants.</param> /// <param name="cancellationToken"></param> public static Task<TRootNode> ReplaceNodesAsync<TRootNode>( this TRootNode root, IEnumerable<SyntaxNode> nodes, Func<SyntaxNode, SyntaxNode, CancellationToken, Task<SyntaxNode>> computeReplacementAsync, CancellationToken cancellationToken) where TRootNode : SyntaxNode { return root.ReplaceSyntaxAsync( nodes: nodes, computeReplacementNodeAsync: computeReplacementAsync, tokens: null, computeReplacementTokenAsync: null, trivia: null, computeReplacementTriviaAsync: null, cancellationToken: cancellationToken); } /// <summary> /// Creates a new tree of tokens from the existing tree with the specified old tokens replaced with a newly computed tokens. /// </summary> /// <param name="root">The root of the tree that contains all the specified tokens.</param> /// <param name="tokens">The tokens from the tree to be replaced.</param> /// <param name="computeReplacementAsync">A function that computes a replacement token for /// the argument tokens. The first argument is one of the originally specified tokens. The second argument is /// the same token possibly rewritten with replaced trivia.</param> /// <param name="cancellationToken"></param> public static Task<TRootNode> ReplaceTokensAsync<TRootNode>( this TRootNode root, IEnumerable<SyntaxToken> tokens, Func<SyntaxToken, SyntaxToken, CancellationToken, Task<SyntaxToken>> computeReplacementAsync, CancellationToken cancellationToken) where TRootNode : SyntaxNode { return root.ReplaceSyntaxAsync( nodes: null, computeReplacementNodeAsync: null, tokens: tokens, computeReplacementTokenAsync: computeReplacementAsync, trivia: null, computeReplacementTriviaAsync: null, cancellationToken: cancellationToken); } public static Task<TRoot> ReplaceTriviaAsync<TRoot>( this TRoot root, IEnumerable<SyntaxTrivia> trivia, Func<SyntaxTrivia, SyntaxTrivia, CancellationToken, Task<SyntaxTrivia>> computeReplacementAsync, CancellationToken cancellationToken) where TRoot : SyntaxNode { return root.ReplaceSyntaxAsync( nodes: null, computeReplacementNodeAsync: null, tokens: null, computeReplacementTokenAsync: null, trivia: trivia, computeReplacementTriviaAsync: computeReplacementAsync, cancellationToken: cancellationToken); } public static async Task<TRoot> ReplaceSyntaxAsync<TRoot>( this TRoot root, IEnumerable<SyntaxNode>? nodes, Func<SyntaxNode, SyntaxNode, CancellationToken, Task<SyntaxNode>>? computeReplacementNodeAsync, IEnumerable<SyntaxToken>? tokens, Func<SyntaxToken, SyntaxToken, CancellationToken, Task<SyntaxToken>>? computeReplacementTokenAsync, IEnumerable<SyntaxTrivia>? trivia, Func<SyntaxTrivia, SyntaxTrivia, CancellationToken, Task<SyntaxTrivia>>? computeReplacementTriviaAsync, CancellationToken cancellationToken) where TRoot : SyntaxNode { // index all nodes, tokens and trivia by the full spans they cover var nodesToReplace = nodes != null ? nodes.ToDictionary(n => n.FullSpan) : new Dictionary<TextSpan, SyntaxNode>(); var tokensToReplace = tokens != null ? tokens.ToDictionary(t => t.FullSpan) : new Dictionary<TextSpan, SyntaxToken>(); var triviaToReplace = trivia != null ? trivia.ToDictionary(t => t.FullSpan) : new Dictionary<TextSpan, SyntaxTrivia>(); var nodeReplacements = new Dictionary<SyntaxNode, SyntaxNode>(); var tokenReplacements = new Dictionary<SyntaxToken, SyntaxToken>(); var triviaReplacements = new Dictionary<SyntaxTrivia, SyntaxTrivia>(); var retryAnnotations = new AnnotationTable<object>("RetryReplace"); var spans = new List<TextSpan>(nodesToReplace.Count + tokensToReplace.Count + triviaToReplace.Count); spans.AddRange(nodesToReplace.Keys); spans.AddRange(tokensToReplace.Keys); spans.AddRange(triviaToReplace.Keys); while (spans.Count > 0) { // sort the spans of the items to be replaced so we can tell if any overlap spans.Sort((x, y) => { // order by end offset, and then by length var d = x.End - y.End; if (d == 0) { d = x.Length - y.Length; } return d; }); // compute replacements for all nodes that will go in the same batch // only spans that do not overlap go in the same batch. TextSpan previous = default; foreach (var span in spans) { // only add to replacement map if we don't intersect with the previous node. This taken with the sort order // should ensure that parent nodes are not processed in the same batch as child nodes. if (previous == default || !previous.IntersectsWith(span)) { if (nodesToReplace.TryGetValue(span, out var currentNode)) { var original = (SyntaxNode?)retryAnnotations.GetAnnotations(currentNode).SingleOrDefault() ?? currentNode; var newNode = await computeReplacementNodeAsync!(original, currentNode, cancellationToken).ConfigureAwait(false); nodeReplacements[currentNode] = newNode; } else if (tokensToReplace.TryGetValue(span, out var currentToken)) { var original = (SyntaxToken?)retryAnnotations.GetAnnotations(currentToken).SingleOrDefault() ?? currentToken; var newToken = await computeReplacementTokenAsync!(original, currentToken, cancellationToken).ConfigureAwait(false); tokenReplacements[currentToken] = newToken; } else if (triviaToReplace.TryGetValue(span, out var currentTrivia)) { var original = (SyntaxTrivia?)retryAnnotations.GetAnnotations(currentTrivia).SingleOrDefault() ?? currentTrivia; var newTrivia = await computeReplacementTriviaAsync!(original, currentTrivia, cancellationToken).ConfigureAwait(false); triviaReplacements[currentTrivia] = newTrivia; } } previous = span; } var retryNodes = false; var retryTokens = false; var retryTrivia = false; // replace nodes in batch // submit all nodes so we can annotate the ones we don't replace root = root.ReplaceSyntax( nodes: nodesToReplace.Values, computeReplacementNode: (original, rewritten) => { if (rewritten != original || !nodeReplacements.TryGetValue(original, out var replaced)) { // the subtree did change, or we didn't have a replacement for it in this batch // so we need to add an annotation so we can find this node again for the next batch. replaced = retryAnnotations.WithAdditionalAnnotations(rewritten, original); retryNodes = true; } return replaced; }, tokens: tokensToReplace.Values, computeReplacementToken: (original, rewritten) => { if (rewritten != original || !tokenReplacements.TryGetValue(original, out var replaced)) { // the subtree did change, or we didn't have a replacement for it in this batch // so we need to add an annotation so we can find this node again for the next batch. replaced = retryAnnotations.WithAdditionalAnnotations(rewritten, original); retryTokens = true; } return replaced; }, trivia: triviaToReplace.Values, computeReplacementTrivia: (original, rewritten) => { if (!triviaReplacements.TryGetValue(original, out var replaced)) { // the subtree did change, or we didn't have a replacement for it in this batch // so we need to add an annotation so we can find this node again for the next batch. replaced = retryAnnotations.WithAdditionalAnnotations(rewritten, original); retryTrivia = true; } return replaced; }); nodesToReplace.Clear(); tokensToReplace.Clear(); triviaToReplace.Clear(); spans.Clear(); // prepare next batch out of all remaining annotated nodes if (retryNodes) { nodesToReplace = retryAnnotations.GetAnnotatedNodes(root).ToDictionary(n => n.FullSpan); spans.AddRange(nodesToReplace.Keys); } if (retryTokens) { tokensToReplace = retryAnnotations.GetAnnotatedTokens(root).ToDictionary(t => t.FullSpan); spans.AddRange(tokensToReplace.Keys); } if (retryTrivia) { triviaToReplace = retryAnnotations.GetAnnotatedTrivia(root).ToDictionary(t => t.FullSpan); spans.AddRange(triviaToReplace.Keys); } } return root; } /// <summary> /// Look inside a trivia list for a skipped token that contains the given position. /// </summary> private static readonly Func<SyntaxTriviaList, int, SyntaxToken> s_findSkippedTokenForward = FindSkippedTokenForward; /// <summary> /// Look inside a trivia list for a skipped token that contains the given position. /// </summary> private static SyntaxToken FindSkippedTokenForward(SyntaxTriviaList triviaList, int position) { foreach (var trivia in triviaList) { if (trivia.HasStructure) { if (trivia.GetStructure() is ISkippedTokensTriviaSyntax skippedTokensTrivia) { foreach (var token in skippedTokensTrivia.Tokens) { if (token.Span.Length > 0 && position <= token.Span.End) { return token; } } } } } return default; } /// <summary> /// Look inside a trivia list for a skipped token that contains the given position. /// </summary> private static readonly Func<SyntaxTriviaList, int, SyntaxToken> s_findSkippedTokenBackward = FindSkippedTokenBackward; /// <summary> /// Look inside a trivia list for a skipped token that contains the given position. /// </summary> private static SyntaxToken FindSkippedTokenBackward(SyntaxTriviaList triviaList, int position) { foreach (var trivia in triviaList.Reverse()) { if (trivia.HasStructure) { if (trivia.GetStructure() is ISkippedTokensTriviaSyntax skippedTokensTrivia) { foreach (var token in skippedTokensTrivia.Tokens) { if (token.Span.Length > 0 && token.SpanStart <= position) { return token; } } } } } return default; } private static SyntaxToken GetInitialToken( SyntaxNode root, int position, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) { return (position < root.FullSpan.End || !(root is ICompilationUnitSyntax)) ? root.FindToken(position, includeSkipped || includeDirectives || includeDocumentationComments) : root.GetLastToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true) .GetPreviousToken(includeZeroWidth: false, includeSkipped: includeSkipped, includeDirectives: includeDirectives, includeDocumentationComments: includeDocumentationComments); } /// <summary> /// If the position is inside of token, return that token; otherwise, return the token to the right. /// </summary> public static SyntaxToken FindTokenOnRightOfPosition( this SyntaxNode root, int position, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) { var findSkippedToken = includeSkipped ? s_findSkippedTokenForward : ((l, p) => default); var token = GetInitialToken(root, position, includeSkipped, includeDirectives, includeDocumentationComments); if (position < token.SpanStart) { var skippedToken = findSkippedToken(token.LeadingTrivia, position); token = skippedToken.RawKind != 0 ? skippedToken : token; } else if (token.Span.End <= position) { do { var skippedToken = findSkippedToken(token.TrailingTrivia, position); token = skippedToken.RawKind != 0 ? skippedToken : token.GetNextToken(includeZeroWidth: false, includeSkipped: includeSkipped, includeDirectives: includeDirectives, includeDocumentationComments: includeDocumentationComments); } while (token.RawKind != 0 && token.Span.End <= position && token.Span.End <= root.FullSpan.End); } if (token.Span.Length == 0) { token = token.GetNextToken(); } return token; } /// <summary> /// If the position is inside of token, return that token; otherwise, return the token to the left. /// </summary> public static SyntaxToken FindTokenOnLeftOfPosition( this SyntaxNode root, int position, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) { var findSkippedToken = includeSkipped ? s_findSkippedTokenBackward : ((l, p) => default); var token = GetInitialToken(root, position, includeSkipped, includeDirectives, includeDocumentationComments); if (position <= token.SpanStart) { do { var skippedToken = findSkippedToken(token.LeadingTrivia, position); token = skippedToken.RawKind != 0 ? skippedToken : token.GetPreviousToken(includeZeroWidth: false, includeSkipped: includeSkipped, includeDirectives: includeDirectives, includeDocumentationComments: includeDocumentationComments); } while (position <= token.SpanStart && root.FullSpan.Start < token.SpanStart); } else if (token.Span.End < position) { var skippedToken = findSkippedToken(token.TrailingTrivia, position); token = skippedToken.RawKind != 0 ? skippedToken : token; } if (token.Span.Length == 0) { token = token.GetPreviousToken(); } return token; } public static T WithPrependedLeadingTrivia<T>( this T node, params SyntaxTrivia[] trivia) where T : SyntaxNode { if (trivia.Length == 0) { return node; } return node.WithPrependedLeadingTrivia((IEnumerable<SyntaxTrivia>)trivia); } public static T WithPrependedLeadingTrivia<T>( this T node, SyntaxTriviaList trivia) where T : SyntaxNode { if (trivia.Count == 0) { return node; } return node.WithLeadingTrivia(trivia.Concat(node.GetLeadingTrivia())); } public static T WithPrependedLeadingTrivia<T>( this T node, IEnumerable<SyntaxTrivia> trivia) where T : SyntaxNode { var list = new SyntaxTriviaList(); list = list.AddRange(trivia); return node.WithPrependedLeadingTrivia(list); } public static T WithAppendedTrailingTrivia<T>( this T node, params SyntaxTrivia[] trivia) where T : SyntaxNode { if (trivia.Length == 0) { return node; } return node.WithAppendedTrailingTrivia((IEnumerable<SyntaxTrivia>)trivia); } public static T WithAppendedTrailingTrivia<T>( this T node, SyntaxTriviaList trivia) where T : SyntaxNode { if (trivia.Count == 0) { return node; } return node.WithTrailingTrivia(node.GetTrailingTrivia().Concat(trivia)); } public static T WithAppendedTrailingTrivia<T>( this T node, IEnumerable<SyntaxTrivia> trivia) where T : SyntaxNode { var list = new SyntaxTriviaList(); list = list.AddRange(trivia); return node.WithAppendedTrailingTrivia(list); } public static T With<T>( this T node, IEnumerable<SyntaxTrivia> leadingTrivia, IEnumerable<SyntaxTrivia> trailingTrivia) where T : SyntaxNode { return node.WithLeadingTrivia(leadingTrivia).WithTrailingTrivia(trailingTrivia); } /// <summary> /// Creates a new token with the leading trivia removed. /// </summary> public static SyntaxToken WithoutLeadingTrivia(this SyntaxToken token) { return token.WithLeadingTrivia(default(SyntaxTriviaList)); } /// <summary> /// Creates a new token with the trailing trivia removed. /// </summary> public static SyntaxToken WithoutTrailingTrivia(this SyntaxToken token) { return token.WithTrailingTrivia(default(SyntaxTriviaList)); } // Copy of the same function in SyntaxNode.cs public static SyntaxNode? GetParent(this SyntaxNode node, bool ascendOutOfTrivia) { var parent = node.Parent; if (parent == null && ascendOutOfTrivia) { if (node is IStructuredTriviaSyntax structuredTrivia) { parent = structuredTrivia.ParentTrivia.Token.Parent; } } return parent; } public static TNode? FirstAncestorOrSelfUntil<TNode>(this SyntaxNode? node, Func<SyntaxNode, bool> predicate) where TNode : SyntaxNode { for (var current = node; current != null; current = current.GetParent(ascendOutOfTrivia: true)) { if (current is TNode tnode) { return tnode; } if (predicate(current)) { break; } } return null; } /// <summary> /// Gets a list of ancestor nodes (including this node) /// </summary> public static ValueAncestorsAndSelfEnumerable ValueAncestorsAndSelf(this SyntaxNode syntaxNode, bool ascendOutOfTrivia = true) => new(syntaxNode, ascendOutOfTrivia); public struct ValueAncestorsAndSelfEnumerable { private readonly SyntaxNode _syntaxNode; private readonly bool _ascendOutOfTrivia; public ValueAncestorsAndSelfEnumerable(SyntaxNode syntaxNode, bool ascendOutOfTrivia) { _syntaxNode = syntaxNode; _ascendOutOfTrivia = ascendOutOfTrivia; } public Enumerator GetEnumerator() => new(_syntaxNode, _ascendOutOfTrivia); public struct Enumerator { private readonly SyntaxNode _start; private readonly bool _ascendOutOfTrivia; public Enumerator(SyntaxNode syntaxNode, bool ascendOutOfTrivia) { _start = syntaxNode; _ascendOutOfTrivia = ascendOutOfTrivia; Current = null!; } public SyntaxNode Current { get; private set; } public bool MoveNext() { Current = Current == null ? _start : GetParent(Current, _ascendOutOfTrivia)!; return Current != null; } } } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./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
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Compilers/CSharp/Portable/Syntax/InternalSyntax/CSharpSyntaxRewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { using Microsoft.CodeAnalysis.Syntax.InternalSyntax; #nullable enable internal partial class CSharpSyntaxRewriter : CSharpSyntaxVisitor<CSharpSyntaxNode> #nullable disable { protected readonly bool VisitIntoStructuredTrivia; public CSharpSyntaxRewriter(bool visitIntoStructuredTrivia = false) { this.VisitIntoStructuredTrivia = visitIntoStructuredTrivia; } public override CSharpSyntaxNode VisitToken(SyntaxToken token) { var leading = this.VisitList(token.LeadingTrivia); var trailing = this.VisitList(token.TrailingTrivia); if (leading != token.LeadingTrivia || trailing != token.TrailingTrivia) { if (leading != token.LeadingTrivia) { token = token.TokenWithLeadingTrivia(leading.Node); } if (trailing != token.TrailingTrivia) { token = token.TokenWithTrailingTrivia(trailing.Node); } } return token; } public SyntaxList<TNode> VisitList<TNode>(SyntaxList<TNode> list) where TNode : CSharpSyntaxNode { SyntaxListBuilder alternate = null; for (int i = 0, n = list.Count; i < n; i++) { var item = list[i]; var visited = this.Visit(item); if (item != visited && alternate == null) { alternate = new SyntaxListBuilder(n); alternate.AddRange(list, 0, i); } if (alternate != null) { Debug.Assert(visited != null && visited.Kind != SyntaxKind.None, "Cannot remove node using Syntax.InternalSyntax.SyntaxRewriter."); alternate.Add(visited); } } if (alternate != null) { return alternate.ToList(); } return list; } public SeparatedSyntaxList<TNode> VisitList<TNode>(SeparatedSyntaxList<TNode> list) where TNode : CSharpSyntaxNode { // A separated list is filled with C# nodes and C# tokens. Both of which // derive from InternalSyntax.CSharpSyntaxNode. So this cast is appropriately // typesafe. var withSeps = (SyntaxList<CSharpSyntaxNode>)list.GetWithSeparators(); var result = this.VisitList(withSeps); if (result != withSeps) { return result.AsSeparatedList<TNode>(); } return list; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { using Microsoft.CodeAnalysis.Syntax.InternalSyntax; #nullable enable internal partial class CSharpSyntaxRewriter : CSharpSyntaxVisitor<CSharpSyntaxNode> #nullable disable { protected readonly bool VisitIntoStructuredTrivia; public CSharpSyntaxRewriter(bool visitIntoStructuredTrivia = false) { this.VisitIntoStructuredTrivia = visitIntoStructuredTrivia; } public override CSharpSyntaxNode VisitToken(SyntaxToken token) { var leading = this.VisitList(token.LeadingTrivia); var trailing = this.VisitList(token.TrailingTrivia); if (leading != token.LeadingTrivia || trailing != token.TrailingTrivia) { if (leading != token.LeadingTrivia) { token = token.TokenWithLeadingTrivia(leading.Node); } if (trailing != token.TrailingTrivia) { token = token.TokenWithTrailingTrivia(trailing.Node); } } return token; } public SyntaxList<TNode> VisitList<TNode>(SyntaxList<TNode> list) where TNode : CSharpSyntaxNode { SyntaxListBuilder alternate = null; for (int i = 0, n = list.Count; i < n; i++) { var item = list[i]; var visited = this.Visit(item); if (item != visited && alternate == null) { alternate = new SyntaxListBuilder(n); alternate.AddRange(list, 0, i); } if (alternate != null) { Debug.Assert(visited != null && visited.Kind != SyntaxKind.None, "Cannot remove node using Syntax.InternalSyntax.SyntaxRewriter."); alternate.Add(visited); } } if (alternate != null) { return alternate.ToList(); } return list; } public SeparatedSyntaxList<TNode> VisitList<TNode>(SeparatedSyntaxList<TNode> list) where TNode : CSharpSyntaxNode { // A separated list is filled with C# nodes and C# tokens. Both of which // derive from InternalSyntax.CSharpSyntaxNode. So this cast is appropriately // typesafe. var withSeps = (SyntaxList<CSharpSyntaxNode>)list.GetWithSeparators(); var result = this.VisitList(withSeps); if (result != withSeps) { return result.AsSeparatedList<TNode>(); } return list; } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Compilers/CSharp/Test/Symbol/Symbols/Source/DelegateTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DelegateTests : CSharpTestBase { [Fact] public void MissingTypes() { var text = @" delegate void A(); "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // (2,15): error CS0518: Predefined type 'System.MulticastDelegate' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.MulticastDelegate"), // (2,10): error CS0518: Predefined type 'System.Void' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void"), // (2,1): error CS0518: Predefined type 'System.Void' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "delegate void A();").WithArguments("System.Void"), // (2,1): error CS0518: Predefined type 'System.Object' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "delegate void A();").WithArguments("System.Object"), // (2,1): error CS0518: Predefined type 'System.IntPtr' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "delegate void A();").WithArguments("System.IntPtr") ); } [WorkItem(530363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530363")] [Fact] public void MissingAsyncTypes() { var source = "delegate void A();"; var comp = CreateEmptyCompilation( source: new[] { Parse(source) }, references: new[] { MinCorlibRef }); comp.VerifyDiagnostics(); } [Fact] public void Simple1() { var text = @" class A { delegate void D(); } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var d = a.GetMembers("D")[0] as NamedTypeSymbol; var tmp = d.GetMembers(); Assert.Equal(d.Locations[0], d.DelegateInvokeMethod.Locations[0], EqualityComparer<Location>.Default); Assert.Equal(d.Locations[0], d.InstanceConstructors[0].Locations[0], EqualityComparer<Location>.Default); } [Fact] public void Duplicate() { var text = @" delegate void D(int x); delegate void D(float y); "; var comp = CreateCompilation(text); var diags = comp.GetDeclarationDiagnostics(); Assert.Equal(1, diags.Count()); var global = comp.GlobalNamespace; var d = global.GetTypeMembers("D", 0); Assert.Equal(2, d.Length); } [Fact] public void MetadataDelegateField() { var text = @" class A { public System.Func<int> Field; } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var field = a.GetMembers("Field")[0] as FieldSymbol; var fieldType = field.Type as NamedTypeSymbol; Assert.Equal(TypeKind.Delegate, fieldType.TypeKind); var invoke = fieldType.DelegateInvokeMethod; Assert.Equal(MethodKind.DelegateInvoke, invoke.MethodKind); var ctor = fieldType.InstanceConstructors[0]; Assert.Equal(2, ctor.Parameters.Length); Assert.Equal(comp.GetSpecialType(SpecialType.System_Object), ctor.Parameters[0].Type); Assert.Equal(comp.GetSpecialType(SpecialType.System_IntPtr), ctor.Parameters[1].Type); } [WorkItem(537188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537188")] [Fact] public void SimpleDelegate() { var text = @"delegate void MyDel(int n);"; var comp = CreateCompilation(text); var v = comp.GlobalNamespace.GetTypeMembers("MyDel", 0).Single(); Assert.NotNull(v); Assert.Equal(SymbolKind.NamedType, v.Kind); Assert.Equal(TypeKind.Delegate, v.TypeKind); Assert.True(v.IsReferenceType); Assert.False(v.IsValueType); Assert.True(v.IsSealed); Assert.False(v.IsAbstract); Assert.Equal(0, v.Arity); // number of type parameters Assert.Equal(1, v.DelegateInvokeMethod.Parameters.Length); Assert.Equal(Accessibility.Internal, v.DeclaredAccessibility); Assert.Equal("System.MulticastDelegate", v.BaseType().ToTestDisplayString()); } [WorkItem(537188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537188")] [WorkItem(538707, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538707")] [Fact] public void BeginInvokeEndInvoke() { var text = @" delegate int MyDel(int x, ref int y, out int z); namespace System { interface IAsyncResult {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var myDel = global.GetTypeMembers("MyDel", 0).Single() as NamedTypeSymbol; var invoke = myDel.DelegateInvokeMethod; var beginInvoke = myDel.GetMembers("BeginInvoke").Single() as MethodSymbol; Assert.Equal(invoke.Parameters.Length + 2, beginInvoke.Parameters.Length); Assert.Equal(TypeKind.Interface, beginInvoke.ReturnType.TypeKind); Assert.Equal("System.IAsyncResult", beginInvoke.ReturnType.ToTestDisplayString()); for (int i = 0; i < invoke.Parameters.Length; i++) { Assert.Equal(invoke.Parameters[i].Type, beginInvoke.Parameters[i].Type); Assert.Equal(invoke.Parameters[i].RefKind, beginInvoke.Parameters[i].RefKind); } var lastParameterType = beginInvoke.Parameters[invoke.Parameters.Length].Type; Assert.Equal("System.AsyncCallback", lastParameterType.ToTestDisplayString()); Assert.Equal(SpecialType.System_AsyncCallback, lastParameterType.SpecialType); Assert.Equal("System.Object", beginInvoke.Parameters[invoke.Parameters.Length + 1].Type.ToTestDisplayString()); var endInvoke = myDel.GetMembers("EndInvoke").Single() as MethodSymbol; Assert.Equal(invoke.ReturnType, endInvoke.ReturnType); int k = 0; for (int i = 0; i < invoke.Parameters.Length; i++) { if (invoke.Parameters[i].RefKind != RefKind.None) { Assert.Equal(invoke.Parameters[i].Type, endInvoke.Parameters[k].Type); Assert.Equal(invoke.Parameters[i].RefKind, endInvoke.Parameters[k++].RefKind); } } lastParameterType = endInvoke.Parameters[k++].Type; Assert.Equal("System.IAsyncResult", lastParameterType.ToTestDisplayString()); Assert.Equal(SpecialType.System_IAsyncResult, lastParameterType.SpecialType); Assert.Equal(k, endInvoke.Parameters.Length); } [WorkItem(537188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537188")] [Fact] public void GenericDelegate() { var text = @"namespace NS { internal delegate void D<Q>(Q q); }"; var comp = CreateCompilation(text); var namespaceNS = comp.GlobalNamespace.GetMembers("NS").First() as NamespaceOrTypeSymbol; Assert.Equal(1, namespaceNS.GetTypeMembers().Length); var d = namespaceNS.GetTypeMembers("D").First(); Assert.Equal(namespaceNS, d.ContainingSymbol); Assert.Equal(SymbolKind.NamedType, d.Kind); Assert.Equal(TypeKind.Delegate, d.TypeKind); Assert.Equal(Accessibility.Internal, d.DeclaredAccessibility); Assert.Equal(1, d.TypeParameters.Length); Assert.Equal("Q", d.TypeParameters[0].Name); var q = d.TypeParameters[0]; Assert.Equal(q.ContainingSymbol, d); Assert.Equal(d.DelegateInvokeMethod.Parameters[0].Type, q); // same as type parameter Assert.Equal(1, d.TypeArguments().Length); } [WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")] [Fact] public void DelegateEscapedIdentifier() { var text = @" delegate void @out(); "; var comp = CreateCompilation(Parse(text)); NamedTypeSymbol dout = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("out").Single(); Assert.Equal("out", dout.Name); Assert.Equal("@out", dout.ToString()); } [Fact] public void DelegatesEverywhere() { var text = @" using System; delegate int Intf(int x); class C { Intf I; Intf Method(Intf f1) { Intf i = f1; i = f1; I = i; i = I; Delegate d1 = f1; MulticastDelegate m1 = f1; object o1 = f1; f1 = i; return f1; } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void DelegateCreation() { var text = @" namespace CSSample { class Program { static void Main(string[] args) { } delegate void D1(); delegate void D2(); delegate int D3(int x); static D1 d1; static D2 d2; static D3 d3; internal virtual void V() { } void M() { } static void S() { } static int M2(int x) { return x; } static void F(Program p) { // Good cases d2 = new D2(d1); d1 = new D1(d2); d1 = new D1(d2.Invoke); d1 = new D1(d1); d1 = new D1(p.V); d1 = new D1(p.M); d1 = new D1(S); } } } "; CreateCompilation(text).VerifyDiagnostics( // (17,19): warning CS0169: The field 'CSSample.Program.d3' is never used // static D3 d3; Diagnostic(ErrorCode.WRN_UnreferencedField, "d3").WithArguments("CSSample.Program.d3")); } [WorkItem(538722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538722")] [Fact] public void MulticastIsNotDelegate() { var text = @" using System; class Program { static void Main() { MulticastDelegate d = Main; } } "; CreateCompilation(text).VerifyDiagnostics( // (7,27): error CS0428: Cannot convert method group 'Main' to non-delegate type 'System.MulticastDelegate'. Did you intend to invoke the method? Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate")); } [WorkItem(538706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538706")] [Fact] public void DelegateMethodParameterNames() { var text = @" delegate int D(int x, ref int y, out int z); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(3, invokeParameters.Length); Assert.Equal("x", invokeParameters[0].Name); Assert.Equal("y", invokeParameters[1].Name); Assert.Equal("z", invokeParameters[2].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(5, beginInvokeParameters.Length); Assert.Equal("x", beginInvokeParameters[0].Name); Assert.Equal("y", beginInvokeParameters[1].Name); Assert.Equal("z", beginInvokeParameters[2].Name); Assert.Equal("callback", beginInvokeParameters[3].Name); Assert.Equal("object", beginInvokeParameters[4].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(3, endInvokeParameters.Length); Assert.Equal("y", endInvokeParameters[0].Name); Assert.Equal("z", endInvokeParameters[1].Name); Assert.Equal("result", endInvokeParameters[2].Name); } [WorkItem(541179, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541179")] [Fact] public void DelegateWithTypeParameterNamedInvoke() { var text = @" delegate void F<Invoke>(Invoke i); class Goo { void M(int i) { F<int> x = M; } } "; CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithOutParameterNamedResult() { var text = @" delegate void D(out int result); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(1, invokeParameters.Length); Assert.Equal("result", invokeParameters[0].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(3, beginInvokeParameters.Length); Assert.Equal("result", beginInvokeParameters[0].Name); Assert.Equal("callback", beginInvokeParameters[1].Name); Assert.Equal("object", beginInvokeParameters[2].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(2, endInvokeParameters.Length); Assert.Equal("result", endInvokeParameters[0].Name); Assert.Equal("__result", endInvokeParameters[1].Name); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithOutParameterNamedResult2() { var text = @" delegate void D(out int @__result); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(1, invokeParameters.Length); Assert.Equal("__result", invokeParameters[0].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(3, beginInvokeParameters.Length); Assert.Equal("__result", beginInvokeParameters[0].Name); Assert.Equal("callback", beginInvokeParameters[1].Name); Assert.Equal("object", beginInvokeParameters[2].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(2, endInvokeParameters.Length); Assert.Equal("__result", endInvokeParameters[0].Name); Assert.Equal("result", endInvokeParameters[1].Name); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithOutParameterNamedResult3() { var text = @" delegate void D(out int result, out int @__result); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(2, invokeParameters.Length); Assert.Equal("result", invokeParameters[0].Name); Assert.Equal("__result", invokeParameters[1].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(4, beginInvokeParameters.Length); Assert.Equal("result", invokeParameters[0].Name); Assert.Equal("__result", invokeParameters[1].Name); Assert.Equal("callback", beginInvokeParameters[2].Name); Assert.Equal("object", beginInvokeParameters[3].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(3, endInvokeParameters.Length); Assert.Equal("result", endInvokeParameters[0].Name); Assert.Equal("__result", endInvokeParameters[1].Name); Assert.Equal("____result", endInvokeParameters[2].Name); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithParametersNamedCallbackAndObject() { var text = @" delegate void D(int callback, int @object); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(2, invokeParameters.Length); Assert.Equal("callback", invokeParameters[0].Name); Assert.Equal("object", invokeParameters[1].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(4, beginInvokeParameters.Length); Assert.Equal("callback", beginInvokeParameters[0].Name); Assert.Equal("object", beginInvokeParameters[1].Name); Assert.Equal("__callback", beginInvokeParameters[2].Name); Assert.Equal("__object", beginInvokeParameters[3].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(1, endInvokeParameters.Length); Assert.Equal("result", endInvokeParameters[0].Name); } [Fact] public void DelegateConversion() { var text = @" public class A { } public class B { } public class C<T> { } public class DelegateTest { public static void FT<T>(T t) { } public static void FTT<T>(T t1, T t2) { } public static void FTi<T>(T t, int x) { } public static void FST<S, T>(S s, T t) { } public static void FCT<T>(C<T> c) { } public static void PT<T>(params T[] args) { } public static void PTT<T>(T t, params T[] arr) { } public static void PST<S, T>(S s, params T[] arr) { } public delegate void Da(A x); public delegate void Daa(A x, A y); public delegate void Dab(A x, B y); public delegate void Dai(A x, int y); public delegate void Dpa(A[] x); public delegate void Dapa(A x, A[] y); public delegate void Dapb(A x, B[] y); public delegate void Dpapa(A[] x, A[] y); public delegate void Dca(C<A> x); public delegate void D1<T>(T t); public static void Run() { Da da; Daa daa; Dai dai; Dab dab; Dpa dpa; Dapa dapa; Dapb dapb; Dpapa dpapa; Dca dca; da = new Da(FTT); da = new Da(FCT); da = new Da(PT); daa = new Daa(FT); daa = new Daa(FTi); daa = new Daa(PTT); daa = new Daa(PST); dai = new Dai(FT); dai = new Dai(FTT); dai = new Dai(PTT); dai = new Dai(PST); dab = new Dab(FT); dab = new Dab(FTT); dab = new Dab(FTi); dab = new Dab(PTT); dab = new Dab(PST); dpa = new Dpa(FTT); dpa = new Dpa(FCT); dapa = new Dapa(FT); dapa = new Dapa(FTT); dapb = new Dapb(FT); dapb = new Dapb(FTT); dapb = new Dapb(PTT); dpapa = new Dpapa(FT); dpapa = new Dpapa(PTT); dca = new Dca(FTT); dca = new Dca(PT); RunG(null); } public static void RunG<T>(T t) { } } "; CreateCompilation(text).VerifyDiagnostics( // (44,14): error CS0123: No overload for 'FTT' matches delegate 'DelegateTest.Da' // da = new Da(FTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Da(FTT)").WithArguments("FTT", "DelegateTest.Da").WithLocation(44, 14), // (45,21): error CS0411: The type arguments for method 'DelegateTest.FCT<T>(C<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // da = new Da(FCT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FCT").WithArguments("DelegateTest.FCT<T>(C<T>)").WithLocation(45, 21), // (46,21): error CS0411: The type arguments for method 'DelegateTest.PT<T>(params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // da = new Da(PT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PT").WithArguments("DelegateTest.PT<T>(params T[])").WithLocation(46, 21), // (48,15): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Daa' // daa = new Daa(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Daa(FT)").WithArguments("FT", "DelegateTest.Daa").WithLocation(48, 15), // (49,15): error CS0123: No overload for 'FTi' matches delegate 'DelegateTest.Daa' // daa = new Daa(FTi); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Daa(FTi)").WithArguments("FTi", "DelegateTest.Daa").WithLocation(49, 15), // (50,15): error CS0123: No overload for 'PTT' matches delegate 'DelegateTest.Daa' // daa = new Daa(PTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Daa(PTT)").WithArguments("PTT", "DelegateTest.Daa").WithLocation(50, 15), // (51,23): error CS0411: The type arguments for method 'DelegateTest.PST<S, T>(S, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // daa = new Daa(PST); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PST").WithArguments("DelegateTest.PST<S, T>(S, params T[])").WithLocation(51, 23), // (53,15): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dai' // dai = new Dai(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dai(FT)").WithArguments("FT", "DelegateTest.Dai").WithLocation(53, 15), // (54,23): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dai = new Dai(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(54, 23), // (55,15): error CS0123: No overload for 'PTT' matches delegate 'DelegateTest.Dai' // dai = new Dai(PTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dai(PTT)").WithArguments("PTT", "DelegateTest.Dai").WithLocation(55, 15), // (56,23): error CS0411: The type arguments for method 'DelegateTest.PST<S, T>(S, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dai = new Dai(PST); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PST").WithArguments("DelegateTest.PST<S, T>(S, params T[])").WithLocation(56, 23), // (58,15): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dab' // dab = new Dab(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dab(FT)").WithArguments("FT", "DelegateTest.Dab").WithLocation(58, 15), // (59,23): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dab = new Dab(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(59, 23), // (60,15): error CS0123: No overload for 'FTi' matches delegate 'DelegateTest.Dab' // dab = new Dab(FTi); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dab(FTi)").WithArguments("FTi", "DelegateTest.Dab").WithLocation(60, 15), // (61,15): error CS0123: No overload for 'PTT' matches delegate 'DelegateTest.Dab' // dab = new Dab(PTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dab(PTT)").WithArguments("PTT", "DelegateTest.Dab").WithLocation(61, 15), // (62,23): error CS0411: The type arguments for method 'DelegateTest.PST<S, T>(S, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dab = new Dab(PST); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PST").WithArguments("DelegateTest.PST<S, T>(S, params T[])").WithLocation(62, 23), // (64,15): error CS0123: No overload for 'FTT' matches delegate 'DelegateTest.Dpa' // dpa = new Dpa(FTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dpa(FTT)").WithArguments("FTT", "DelegateTest.Dpa").WithLocation(64, 15), // (65,23): error CS0411: The type arguments for method 'DelegateTest.FCT<T>(C<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dpa = new Dpa(FCT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FCT").WithArguments("DelegateTest.FCT<T>(C<T>)").WithLocation(65, 23), // (67,16): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dapa' // dapa = new Dapa(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dapa(FT)").WithArguments("FT", "DelegateTest.Dapa").WithLocation(67, 16), // (68,25): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dapa = new Dapa(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(68, 25), // (70,16): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dapb' // dapb = new Dapb(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dapb(FT)").WithArguments("FT", "DelegateTest.Dapb").WithLocation(70, 16), // (71,25): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dapb = new Dapb(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(71, 25), // (72,25): error CS0411: The type arguments for method 'DelegateTest.PTT<T>(T, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dapb = new Dapb(PTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PTT").WithArguments("DelegateTest.PTT<T>(T, params T[])").WithLocation(72, 25), // (74,17): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dpapa' // dpapa = new Dpapa(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dpapa(FT)").WithArguments("FT", "DelegateTest.Dpapa").WithLocation(74, 17), // (75,27): error CS0411: The type arguments for method 'DelegateTest.PTT<T>(T, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dpapa = new Dpapa(PTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PTT").WithArguments("DelegateTest.PTT<T>(T, params T[])").WithLocation(75, 27), // (77,15): error CS0123: No overload for 'FTT' matches delegate 'DelegateTest.Dca' // dca = new Dca(FTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dca(FTT)").WithArguments("FTT", "DelegateTest.Dca").WithLocation(77, 15), // (78,23): error CS0411: The type arguments for method 'DelegateTest.PT<T>(params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dca = new Dca(PT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PT").WithArguments("DelegateTest.PT<T>(params T[])").WithLocation(78, 23), // (80,9): error CS0411: The type arguments for method 'DelegateTest.RunG<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // RunG(null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "RunG").WithArguments("DelegateTest.RunG<T>(T)").WithLocation(80, 9)); } [Fact] public void CastFromMulticastDelegate() { var source = @"using System; delegate void D(); class Program { public static void Main(string[] args) { MulticastDelegate d = null; D d2 = (D)d; } } "; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(634014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634014")] [Fact] public void DelegateTest634014() { var source = @"delegate void D(ref int x); class C { D d = async delegate { }; }"; CreateCompilation(source).VerifyDiagnostics( // (4,17): error CS1988: Async methods cannot have ref, in or out parameters // D d = async delegate { }; Diagnostic(ErrorCode.ERR_BadAsyncArgType, "delegate"), // (4,17): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // D d = async delegate { }; Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "delegate").WithLocation(4, 17)); } [Fact] public void RefReturningDelegate() { var source = @"delegate ref int D();"; var comp = CreateCompilationWithMscorlib45(source); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var d = global.GetMembers("D")[0] as NamedTypeSymbol; Assert.True(d.DelegateInvokeMethod.ReturnsByRef); Assert.False(d.DelegateInvokeMethod.ReturnsByRefReadonly); Assert.Equal(RefKind.Ref, d.DelegateInvokeMethod.RefKind); Assert.Equal(RefKind.Ref, ((MethodSymbol)d.GetMembers("EndInvoke").Single()).RefKind); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningDelegate() { var source = @"delegate ref readonly int D(in int arg);"; var comp = CreateCompilationWithMscorlib45(source); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var d = global.GetMembers("D")[0] as NamedTypeSymbol; Assert.False(d.DelegateInvokeMethod.ReturnsByRef); Assert.True(d.DelegateInvokeMethod.ReturnsByRefReadonly); Assert.Equal(RefKind.RefReadOnly, d.DelegateInvokeMethod.RefKind); Assert.Equal(RefKind.RefReadOnly, ((MethodSymbol)d.GetMembers("EndInvoke").Single()).RefKind); Assert.Equal(RefKind.In, d.DelegateInvokeMethod.Parameters[0].RefKind); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlysInlambda() { var source = @" class C { public delegate ref readonly T DD<T>(in T arg); public static void Main() { DD<int> d1 = (in int a) => ref a; DD<int> d2 = delegate(in int a){return ref a;}; } }"; var tree = SyntaxFactory.ParseSyntaxTree(source, options: TestOptions.Regular); var compilation = CreateCompilationWithMscorlib45(new SyntaxTree[] { tree }).VerifyDiagnostics(); var model = compilation.GetSemanticModel(tree); ExpressionSyntax lambdaSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var lambda = (IMethodSymbol)model.GetSymbolInfo(lambdaSyntax).Symbol; Assert.False(lambda.ReturnsByRef); Assert.True(lambda.ReturnsByRefReadonly); Assert.Equal(RefKind.In, lambda.Parameters[0].RefKind); lambdaSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single(); lambda = (IMethodSymbol)model.GetSymbolInfo(lambdaSyntax).Symbol; Assert.False(lambda.ReturnsByRef); Assert.True(lambda.ReturnsByRefReadonly); Assert.Equal(RefKind.In, lambda.Parameters[0].RefKind); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DelegateTests : CSharpTestBase { [Fact] public void MissingTypes() { var text = @" delegate void A(); "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // (2,15): error CS0518: Predefined type 'System.MulticastDelegate' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.MulticastDelegate"), // (2,10): error CS0518: Predefined type 'System.Void' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "void").WithArguments("System.Void"), // (2,1): error CS0518: Predefined type 'System.Void' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "delegate void A();").WithArguments("System.Void"), // (2,1): error CS0518: Predefined type 'System.Object' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "delegate void A();").WithArguments("System.Object"), // (2,1): error CS0518: Predefined type 'System.IntPtr' is not defined or imported // delegate void A(); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "delegate void A();").WithArguments("System.IntPtr") ); } [WorkItem(530363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530363")] [Fact] public void MissingAsyncTypes() { var source = "delegate void A();"; var comp = CreateEmptyCompilation( source: new[] { Parse(source) }, references: new[] { MinCorlibRef }); comp.VerifyDiagnostics(); } [Fact] public void Simple1() { var text = @" class A { delegate void D(); } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var d = a.GetMembers("D")[0] as NamedTypeSymbol; var tmp = d.GetMembers(); Assert.Equal(d.Locations[0], d.DelegateInvokeMethod.Locations[0], EqualityComparer<Location>.Default); Assert.Equal(d.Locations[0], d.InstanceConstructors[0].Locations[0], EqualityComparer<Location>.Default); } [Fact] public void Duplicate() { var text = @" delegate void D(int x); delegate void D(float y); "; var comp = CreateCompilation(text); var diags = comp.GetDeclarationDiagnostics(); Assert.Equal(1, diags.Count()); var global = comp.GlobalNamespace; var d = global.GetTypeMembers("D", 0); Assert.Equal(2, d.Length); } [Fact] public void MetadataDelegateField() { var text = @" class A { public System.Func<int> Field; } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var field = a.GetMembers("Field")[0] as FieldSymbol; var fieldType = field.Type as NamedTypeSymbol; Assert.Equal(TypeKind.Delegate, fieldType.TypeKind); var invoke = fieldType.DelegateInvokeMethod; Assert.Equal(MethodKind.DelegateInvoke, invoke.MethodKind); var ctor = fieldType.InstanceConstructors[0]; Assert.Equal(2, ctor.Parameters.Length); Assert.Equal(comp.GetSpecialType(SpecialType.System_Object), ctor.Parameters[0].Type); Assert.Equal(comp.GetSpecialType(SpecialType.System_IntPtr), ctor.Parameters[1].Type); } [WorkItem(537188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537188")] [Fact] public void SimpleDelegate() { var text = @"delegate void MyDel(int n);"; var comp = CreateCompilation(text); var v = comp.GlobalNamespace.GetTypeMembers("MyDel", 0).Single(); Assert.NotNull(v); Assert.Equal(SymbolKind.NamedType, v.Kind); Assert.Equal(TypeKind.Delegate, v.TypeKind); Assert.True(v.IsReferenceType); Assert.False(v.IsValueType); Assert.True(v.IsSealed); Assert.False(v.IsAbstract); Assert.Equal(0, v.Arity); // number of type parameters Assert.Equal(1, v.DelegateInvokeMethod.Parameters.Length); Assert.Equal(Accessibility.Internal, v.DeclaredAccessibility); Assert.Equal("System.MulticastDelegate", v.BaseType().ToTestDisplayString()); } [WorkItem(537188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537188")] [WorkItem(538707, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538707")] [Fact] public void BeginInvokeEndInvoke() { var text = @" delegate int MyDel(int x, ref int y, out int z); namespace System { interface IAsyncResult {} } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var myDel = global.GetTypeMembers("MyDel", 0).Single() as NamedTypeSymbol; var invoke = myDel.DelegateInvokeMethod; var beginInvoke = myDel.GetMembers("BeginInvoke").Single() as MethodSymbol; Assert.Equal(invoke.Parameters.Length + 2, beginInvoke.Parameters.Length); Assert.Equal(TypeKind.Interface, beginInvoke.ReturnType.TypeKind); Assert.Equal("System.IAsyncResult", beginInvoke.ReturnType.ToTestDisplayString()); for (int i = 0; i < invoke.Parameters.Length; i++) { Assert.Equal(invoke.Parameters[i].Type, beginInvoke.Parameters[i].Type); Assert.Equal(invoke.Parameters[i].RefKind, beginInvoke.Parameters[i].RefKind); } var lastParameterType = beginInvoke.Parameters[invoke.Parameters.Length].Type; Assert.Equal("System.AsyncCallback", lastParameterType.ToTestDisplayString()); Assert.Equal(SpecialType.System_AsyncCallback, lastParameterType.SpecialType); Assert.Equal("System.Object", beginInvoke.Parameters[invoke.Parameters.Length + 1].Type.ToTestDisplayString()); var endInvoke = myDel.GetMembers("EndInvoke").Single() as MethodSymbol; Assert.Equal(invoke.ReturnType, endInvoke.ReturnType); int k = 0; for (int i = 0; i < invoke.Parameters.Length; i++) { if (invoke.Parameters[i].RefKind != RefKind.None) { Assert.Equal(invoke.Parameters[i].Type, endInvoke.Parameters[k].Type); Assert.Equal(invoke.Parameters[i].RefKind, endInvoke.Parameters[k++].RefKind); } } lastParameterType = endInvoke.Parameters[k++].Type; Assert.Equal("System.IAsyncResult", lastParameterType.ToTestDisplayString()); Assert.Equal(SpecialType.System_IAsyncResult, lastParameterType.SpecialType); Assert.Equal(k, endInvoke.Parameters.Length); } [WorkItem(537188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537188")] [Fact] public void GenericDelegate() { var text = @"namespace NS { internal delegate void D<Q>(Q q); }"; var comp = CreateCompilation(text); var namespaceNS = comp.GlobalNamespace.GetMembers("NS").First() as NamespaceOrTypeSymbol; Assert.Equal(1, namespaceNS.GetTypeMembers().Length); var d = namespaceNS.GetTypeMembers("D").First(); Assert.Equal(namespaceNS, d.ContainingSymbol); Assert.Equal(SymbolKind.NamedType, d.Kind); Assert.Equal(TypeKind.Delegate, d.TypeKind); Assert.Equal(Accessibility.Internal, d.DeclaredAccessibility); Assert.Equal(1, d.TypeParameters.Length); Assert.Equal("Q", d.TypeParameters[0].Name); var q = d.TypeParameters[0]; Assert.Equal(q.ContainingSymbol, d); Assert.Equal(d.DelegateInvokeMethod.Parameters[0].Type, q); // same as type parameter Assert.Equal(1, d.TypeArguments().Length); } [WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")] [Fact] public void DelegateEscapedIdentifier() { var text = @" delegate void @out(); "; var comp = CreateCompilation(Parse(text)); NamedTypeSymbol dout = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("out").Single(); Assert.Equal("out", dout.Name); Assert.Equal("@out", dout.ToString()); } [Fact] public void DelegatesEverywhere() { var text = @" using System; delegate int Intf(int x); class C { Intf I; Intf Method(Intf f1) { Intf i = f1; i = f1; I = i; i = I; Delegate d1 = f1; MulticastDelegate m1 = f1; object o1 = f1; f1 = i; return f1; } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void DelegateCreation() { var text = @" namespace CSSample { class Program { static void Main(string[] args) { } delegate void D1(); delegate void D2(); delegate int D3(int x); static D1 d1; static D2 d2; static D3 d3; internal virtual void V() { } void M() { } static void S() { } static int M2(int x) { return x; } static void F(Program p) { // Good cases d2 = new D2(d1); d1 = new D1(d2); d1 = new D1(d2.Invoke); d1 = new D1(d1); d1 = new D1(p.V); d1 = new D1(p.M); d1 = new D1(S); } } } "; CreateCompilation(text).VerifyDiagnostics( // (17,19): warning CS0169: The field 'CSSample.Program.d3' is never used // static D3 d3; Diagnostic(ErrorCode.WRN_UnreferencedField, "d3").WithArguments("CSSample.Program.d3")); } [WorkItem(538722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538722")] [Fact] public void MulticastIsNotDelegate() { var text = @" using System; class Program { static void Main() { MulticastDelegate d = Main; } } "; CreateCompilation(text).VerifyDiagnostics( // (7,27): error CS0428: Cannot convert method group 'Main' to non-delegate type 'System.MulticastDelegate'. Did you intend to invoke the method? Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate")); } [WorkItem(538706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538706")] [Fact] public void DelegateMethodParameterNames() { var text = @" delegate int D(int x, ref int y, out int z); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(3, invokeParameters.Length); Assert.Equal("x", invokeParameters[0].Name); Assert.Equal("y", invokeParameters[1].Name); Assert.Equal("z", invokeParameters[2].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(5, beginInvokeParameters.Length); Assert.Equal("x", beginInvokeParameters[0].Name); Assert.Equal("y", beginInvokeParameters[1].Name); Assert.Equal("z", beginInvokeParameters[2].Name); Assert.Equal("callback", beginInvokeParameters[3].Name); Assert.Equal("object", beginInvokeParameters[4].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(3, endInvokeParameters.Length); Assert.Equal("y", endInvokeParameters[0].Name); Assert.Equal("z", endInvokeParameters[1].Name); Assert.Equal("result", endInvokeParameters[2].Name); } [WorkItem(541179, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541179")] [Fact] public void DelegateWithTypeParameterNamedInvoke() { var text = @" delegate void F<Invoke>(Invoke i); class Goo { void M(int i) { F<int> x = M; } } "; CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithOutParameterNamedResult() { var text = @" delegate void D(out int result); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(1, invokeParameters.Length); Assert.Equal("result", invokeParameters[0].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(3, beginInvokeParameters.Length); Assert.Equal("result", beginInvokeParameters[0].Name); Assert.Equal("callback", beginInvokeParameters[1].Name); Assert.Equal("object", beginInvokeParameters[2].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(2, endInvokeParameters.Length); Assert.Equal("result", endInvokeParameters[0].Name); Assert.Equal("__result", endInvokeParameters[1].Name); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithOutParameterNamedResult2() { var text = @" delegate void D(out int @__result); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(1, invokeParameters.Length); Assert.Equal("__result", invokeParameters[0].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(3, beginInvokeParameters.Length); Assert.Equal("__result", beginInvokeParameters[0].Name); Assert.Equal("callback", beginInvokeParameters[1].Name); Assert.Equal("object", beginInvokeParameters[2].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(2, endInvokeParameters.Length); Assert.Equal("__result", endInvokeParameters[0].Name); Assert.Equal("result", endInvokeParameters[1].Name); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithOutParameterNamedResult3() { var text = @" delegate void D(out int result, out int @__result); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(2, invokeParameters.Length); Assert.Equal("result", invokeParameters[0].Name); Assert.Equal("__result", invokeParameters[1].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(4, beginInvokeParameters.Length); Assert.Equal("result", invokeParameters[0].Name); Assert.Equal("__result", invokeParameters[1].Name); Assert.Equal("callback", beginInvokeParameters[2].Name); Assert.Equal("object", beginInvokeParameters[3].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(3, endInvokeParameters.Length); Assert.Equal("result", endInvokeParameters[0].Name); Assert.Equal("__result", endInvokeParameters[1].Name); Assert.Equal("____result", endInvokeParameters[2].Name); } [WorkItem(612002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612002")] [Fact] public void DelegateWithParametersNamedCallbackAndObject() { var text = @" delegate void D(int callback, int @object); "; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); NamedTypeSymbol d = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("D").Single(); MethodSymbol invoke = d.DelegateInvokeMethod; ImmutableArray<ParameterSymbol> invokeParameters = invoke.Parameters; Assert.Equal(2, invokeParameters.Length); Assert.Equal("callback", invokeParameters[0].Name); Assert.Equal("object", invokeParameters[1].Name); MethodSymbol beginInvoke = (MethodSymbol)d.GetMembers("BeginInvoke").Single(); ImmutableArray<ParameterSymbol> beginInvokeParameters = beginInvoke.Parameters; Assert.Equal(4, beginInvokeParameters.Length); Assert.Equal("callback", beginInvokeParameters[0].Name); Assert.Equal("object", beginInvokeParameters[1].Name); Assert.Equal("__callback", beginInvokeParameters[2].Name); Assert.Equal("__object", beginInvokeParameters[3].Name); MethodSymbol endInvoke = (MethodSymbol)d.GetMembers("EndInvoke").Single(); ImmutableArray<ParameterSymbol> endInvokeParameters = endInvoke.Parameters; Assert.Equal(1, endInvokeParameters.Length); Assert.Equal("result", endInvokeParameters[0].Name); } [Fact] public void DelegateConversion() { var text = @" public class A { } public class B { } public class C<T> { } public class DelegateTest { public static void FT<T>(T t) { } public static void FTT<T>(T t1, T t2) { } public static void FTi<T>(T t, int x) { } public static void FST<S, T>(S s, T t) { } public static void FCT<T>(C<T> c) { } public static void PT<T>(params T[] args) { } public static void PTT<T>(T t, params T[] arr) { } public static void PST<S, T>(S s, params T[] arr) { } public delegate void Da(A x); public delegate void Daa(A x, A y); public delegate void Dab(A x, B y); public delegate void Dai(A x, int y); public delegate void Dpa(A[] x); public delegate void Dapa(A x, A[] y); public delegate void Dapb(A x, B[] y); public delegate void Dpapa(A[] x, A[] y); public delegate void Dca(C<A> x); public delegate void D1<T>(T t); public static void Run() { Da da; Daa daa; Dai dai; Dab dab; Dpa dpa; Dapa dapa; Dapb dapb; Dpapa dpapa; Dca dca; da = new Da(FTT); da = new Da(FCT); da = new Da(PT); daa = new Daa(FT); daa = new Daa(FTi); daa = new Daa(PTT); daa = new Daa(PST); dai = new Dai(FT); dai = new Dai(FTT); dai = new Dai(PTT); dai = new Dai(PST); dab = new Dab(FT); dab = new Dab(FTT); dab = new Dab(FTi); dab = new Dab(PTT); dab = new Dab(PST); dpa = new Dpa(FTT); dpa = new Dpa(FCT); dapa = new Dapa(FT); dapa = new Dapa(FTT); dapb = new Dapb(FT); dapb = new Dapb(FTT); dapb = new Dapb(PTT); dpapa = new Dpapa(FT); dpapa = new Dpapa(PTT); dca = new Dca(FTT); dca = new Dca(PT); RunG(null); } public static void RunG<T>(T t) { } } "; CreateCompilation(text).VerifyDiagnostics( // (44,14): error CS0123: No overload for 'FTT' matches delegate 'DelegateTest.Da' // da = new Da(FTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Da(FTT)").WithArguments("FTT", "DelegateTest.Da").WithLocation(44, 14), // (45,21): error CS0411: The type arguments for method 'DelegateTest.FCT<T>(C<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // da = new Da(FCT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FCT").WithArguments("DelegateTest.FCT<T>(C<T>)").WithLocation(45, 21), // (46,21): error CS0411: The type arguments for method 'DelegateTest.PT<T>(params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // da = new Da(PT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PT").WithArguments("DelegateTest.PT<T>(params T[])").WithLocation(46, 21), // (48,15): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Daa' // daa = new Daa(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Daa(FT)").WithArguments("FT", "DelegateTest.Daa").WithLocation(48, 15), // (49,15): error CS0123: No overload for 'FTi' matches delegate 'DelegateTest.Daa' // daa = new Daa(FTi); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Daa(FTi)").WithArguments("FTi", "DelegateTest.Daa").WithLocation(49, 15), // (50,15): error CS0123: No overload for 'PTT' matches delegate 'DelegateTest.Daa' // daa = new Daa(PTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Daa(PTT)").WithArguments("PTT", "DelegateTest.Daa").WithLocation(50, 15), // (51,23): error CS0411: The type arguments for method 'DelegateTest.PST<S, T>(S, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // daa = new Daa(PST); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PST").WithArguments("DelegateTest.PST<S, T>(S, params T[])").WithLocation(51, 23), // (53,15): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dai' // dai = new Dai(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dai(FT)").WithArguments("FT", "DelegateTest.Dai").WithLocation(53, 15), // (54,23): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dai = new Dai(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(54, 23), // (55,15): error CS0123: No overload for 'PTT' matches delegate 'DelegateTest.Dai' // dai = new Dai(PTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dai(PTT)").WithArguments("PTT", "DelegateTest.Dai").WithLocation(55, 15), // (56,23): error CS0411: The type arguments for method 'DelegateTest.PST<S, T>(S, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dai = new Dai(PST); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PST").WithArguments("DelegateTest.PST<S, T>(S, params T[])").WithLocation(56, 23), // (58,15): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dab' // dab = new Dab(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dab(FT)").WithArguments("FT", "DelegateTest.Dab").WithLocation(58, 15), // (59,23): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dab = new Dab(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(59, 23), // (60,15): error CS0123: No overload for 'FTi' matches delegate 'DelegateTest.Dab' // dab = new Dab(FTi); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dab(FTi)").WithArguments("FTi", "DelegateTest.Dab").WithLocation(60, 15), // (61,15): error CS0123: No overload for 'PTT' matches delegate 'DelegateTest.Dab' // dab = new Dab(PTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dab(PTT)").WithArguments("PTT", "DelegateTest.Dab").WithLocation(61, 15), // (62,23): error CS0411: The type arguments for method 'DelegateTest.PST<S, T>(S, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dab = new Dab(PST); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PST").WithArguments("DelegateTest.PST<S, T>(S, params T[])").WithLocation(62, 23), // (64,15): error CS0123: No overload for 'FTT' matches delegate 'DelegateTest.Dpa' // dpa = new Dpa(FTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dpa(FTT)").WithArguments("FTT", "DelegateTest.Dpa").WithLocation(64, 15), // (65,23): error CS0411: The type arguments for method 'DelegateTest.FCT<T>(C<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dpa = new Dpa(FCT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FCT").WithArguments("DelegateTest.FCT<T>(C<T>)").WithLocation(65, 23), // (67,16): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dapa' // dapa = new Dapa(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dapa(FT)").WithArguments("FT", "DelegateTest.Dapa").WithLocation(67, 16), // (68,25): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dapa = new Dapa(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(68, 25), // (70,16): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dapb' // dapb = new Dapb(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dapb(FT)").WithArguments("FT", "DelegateTest.Dapb").WithLocation(70, 16), // (71,25): error CS0411: The type arguments for method 'DelegateTest.FTT<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dapb = new Dapb(FTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "FTT").WithArguments("DelegateTest.FTT<T>(T, T)").WithLocation(71, 25), // (72,25): error CS0411: The type arguments for method 'DelegateTest.PTT<T>(T, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dapb = new Dapb(PTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PTT").WithArguments("DelegateTest.PTT<T>(T, params T[])").WithLocation(72, 25), // (74,17): error CS0123: No overload for 'FT' matches delegate 'DelegateTest.Dpapa' // dpapa = new Dpapa(FT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dpapa(FT)").WithArguments("FT", "DelegateTest.Dpapa").WithLocation(74, 17), // (75,27): error CS0411: The type arguments for method 'DelegateTest.PTT<T>(T, params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dpapa = new Dpapa(PTT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PTT").WithArguments("DelegateTest.PTT<T>(T, params T[])").WithLocation(75, 27), // (77,15): error CS0123: No overload for 'FTT' matches delegate 'DelegateTest.Dca' // dca = new Dca(FTT); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Dca(FTT)").WithArguments("FTT", "DelegateTest.Dca").WithLocation(77, 15), // (78,23): error CS0411: The type arguments for method 'DelegateTest.PT<T>(params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // dca = new Dca(PT); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "PT").WithArguments("DelegateTest.PT<T>(params T[])").WithLocation(78, 23), // (80,9): error CS0411: The type arguments for method 'DelegateTest.RunG<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // RunG(null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "RunG").WithArguments("DelegateTest.RunG<T>(T)").WithLocation(80, 9)); } [Fact] public void CastFromMulticastDelegate() { var source = @"using System; delegate void D(); class Program { public static void Main(string[] args) { MulticastDelegate d = null; D d2 = (D)d; } } "; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(634014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634014")] [Fact] public void DelegateTest634014() { var source = @"delegate void D(ref int x); class C { D d = async delegate { }; }"; CreateCompilation(source).VerifyDiagnostics( // (4,17): error CS1988: Async methods cannot have ref, in or out parameters // D d = async delegate { }; Diagnostic(ErrorCode.ERR_BadAsyncArgType, "delegate"), // (4,17): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // D d = async delegate { }; Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "delegate").WithLocation(4, 17)); } [Fact] public void RefReturningDelegate() { var source = @"delegate ref int D();"; var comp = CreateCompilationWithMscorlib45(source); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var d = global.GetMembers("D")[0] as NamedTypeSymbol; Assert.True(d.DelegateInvokeMethod.ReturnsByRef); Assert.False(d.DelegateInvokeMethod.ReturnsByRefReadonly); Assert.Equal(RefKind.Ref, d.DelegateInvokeMethod.RefKind); Assert.Equal(RefKind.Ref, ((MethodSymbol)d.GetMembers("EndInvoke").Single()).RefKind); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningDelegate() { var source = @"delegate ref readonly int D(in int arg);"; var comp = CreateCompilationWithMscorlib45(source); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var d = global.GetMembers("D")[0] as NamedTypeSymbol; Assert.False(d.DelegateInvokeMethod.ReturnsByRef); Assert.True(d.DelegateInvokeMethod.ReturnsByRefReadonly); Assert.Equal(RefKind.RefReadOnly, d.DelegateInvokeMethod.RefKind); Assert.Equal(RefKind.RefReadOnly, ((MethodSymbol)d.GetMembers("EndInvoke").Single()).RefKind); Assert.Equal(RefKind.In, d.DelegateInvokeMethod.Parameters[0].RefKind); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlysInlambda() { var source = @" class C { public delegate ref readonly T DD<T>(in T arg); public static void Main() { DD<int> d1 = (in int a) => ref a; DD<int> d2 = delegate(in int a){return ref a;}; } }"; var tree = SyntaxFactory.ParseSyntaxTree(source, options: TestOptions.Regular); var compilation = CreateCompilationWithMscorlib45(new SyntaxTree[] { tree }).VerifyDiagnostics(); var model = compilation.GetSemanticModel(tree); ExpressionSyntax lambdaSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var lambda = (IMethodSymbol)model.GetSymbolInfo(lambdaSyntax).Symbol; Assert.False(lambda.ReturnsByRef); Assert.True(lambda.ReturnsByRefReadonly); Assert.Equal(RefKind.In, lambda.Parameters[0].RefKind); lambdaSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single(); lambda = (IMethodSymbol)model.GetSymbolInfo(lambdaSyntax).Symbol; Assert.False(lambda.ReturnsByRef); Assert.True(lambda.ReturnsByRefReadonly); Assert.Equal(RefKind.In, lambda.Parameters[0].RefKind); } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Features/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 System.Threading.Tasks; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens { /// <summary> /// Computes the semantic tokens for a whole document. /// </summary> /// <remarks> /// This handler is invoked when a user opens a file. Depending on the size of the file, the full token set may be /// slow to compute, so the <see cref="SemanticTokensRangeHandler"/> is also called when a file is opened in order /// to render UI results quickly until this handler finishes running. /// Unlike the range handler, the whole document handler may be called again if the LSP client finds an edit that /// is difficult to correctly apply to their tags cache. This allows for reliable recovery from errors and accounts /// for limitations in the edits application logic. /// </remarks> internal class SemanticTokensHandler : IRequestHandler<LSP.SemanticTokensParams, LSP.SemanticTokens> { private readonly SemanticTokensCache _tokensCache; public SemanticTokensHandler(SemanticTokensCache tokensCache) { _tokensCache = tokensCache; } public string Method => LSP.Methods.TextDocumentSemanticTokensFullName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.SemanticTokensParams request) { Contract.ThrowIfNull(request.TextDocument); return request.TextDocument; } public async Task<LSP.SemanticTokens> HandleRequestAsync( LSP.SemanticTokensParams request, RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(request.TextDocument, "TextDocument is null."); Contract.ThrowIfNull(context.Document, "Document is null."); var resultId = _tokensCache.GetNextResultId(); var tokensData = await SemanticTokensHelpers.ComputeSemanticTokensDataAsync( context.Document, SemanticTokensCache.TokenTypeToIndex, range: null, cancellationToken).ConfigureAwait(false); var tokens = new LSP.SemanticTokens { ResultId = resultId, Data = tokensData }; await _tokensCache.UpdateCacheAsync(request.TextDocument.Uri, tokens, cancellationToken).ConfigureAwait(false); return tokens; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 System.Threading.Tasks; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens { /// <summary> /// Computes the semantic tokens for a whole document. /// </summary> /// <remarks> /// This handler is invoked when a user opens a file. Depending on the size of the file, the full token set may be /// slow to compute, so the <see cref="SemanticTokensRangeHandler"/> is also called when a file is opened in order /// to render UI results quickly until this handler finishes running. /// Unlike the range handler, the whole document handler may be called again if the LSP client finds an edit that /// is difficult to correctly apply to their tags cache. This allows for reliable recovery from errors and accounts /// for limitations in the edits application logic. /// </remarks> internal class SemanticTokensHandler : IRequestHandler<LSP.SemanticTokensParams, LSP.SemanticTokens> { private readonly SemanticTokensCache _tokensCache; public SemanticTokensHandler(SemanticTokensCache tokensCache) { _tokensCache = tokensCache; } public string Method => LSP.Methods.TextDocumentSemanticTokensFullName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.SemanticTokensParams request) { Contract.ThrowIfNull(request.TextDocument); return request.TextDocument; } public async Task<LSP.SemanticTokens> HandleRequestAsync( LSP.SemanticTokensParams request, RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(request.TextDocument, "TextDocument is null."); Contract.ThrowIfNull(context.Document, "Document is null."); var resultId = _tokensCache.GetNextResultId(); var tokensData = await SemanticTokensHelpers.ComputeSemanticTokensDataAsync( context.Document, SemanticTokensCache.TokenTypeToIndex, range: null, cancellationToken).ConfigureAwait(false); var tokens = new LSP.SemanticTokens { ResultId = resultId, Data = tokensData }; await _tokensCache.UpdateCacheAsync(request.TextDocument.Uri, tokens, cancellationToken).ConfigureAwait(false); return tokens; } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Features/LanguageServer/Protocol/Handler/CodeActions/CodeActionResolveHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.LanguageServer.Handler.CodeActions; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Newtonsoft.Json.Linq; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { /// <summary> /// Resolves a code action by filling out its Edit and/or Command property. /// The handler is triggered only when a user hovers over a code action. This /// system allows the basic code action data to be computed quickly, and the /// complex data, such as edits and commands, to be computed only when necessary /// (i.e. when hovering/previewing a code action). /// </summary> internal class CodeActionResolveHandler : IRequestHandler<LSP.CodeAction, LSP.CodeAction> { private readonly CodeActionsCache _codeActionsCache; private readonly ICodeFixService _codeFixService; private readonly ICodeRefactoringService _codeRefactoringService; public CodeActionResolveHandler( CodeActionsCache codeActionsCache, ICodeFixService codeFixService, ICodeRefactoringService codeRefactoringService) { _codeActionsCache = codeActionsCache; _codeFixService = codeFixService; _codeRefactoringService = codeRefactoringService; } public string Method => LSP.Methods.CodeActionResolveName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CodeAction request) => ((JToken)request.Data!).ToObject<CodeActionResolveData>().TextDocument; public async Task<LSP.CodeAction> HandleRequestAsync(LSP.CodeAction codeAction, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; Contract.ThrowIfNull(document); var data = ((JToken)codeAction.Data!).ToObject<CodeActionResolveData>(); var codeActions = await CodeActionHelpers.GetCodeActionsAsync( _codeActionsCache, document, data.Range, _codeFixService, _codeRefactoringService, cancellationToken).ConfigureAwait(false); var codeActionToResolve = CodeActionHelpers.GetCodeActionToResolve( data.UniqueIdentifier, codeActions); Contract.ThrowIfNull(codeActionToResolve); var operations = await codeActionToResolve.GetOperationsAsync(cancellationToken).ConfigureAwait(false); if (operations.IsEmpty) { return codeAction; } // If we have all non-ApplyChangesOperations, set up to run as command on the server // instead of using WorkspaceEdits. if (operations.All(operation => !(operation is ApplyChangesOperation))) { codeAction.Command = SetCommand(codeAction.Title, data); return codeAction; } // TO-DO: We currently must execute code actions which add new documents on the server as commands, // since there is no LSP support for adding documents yet. In the future, we should move these actions // to execute on the client. // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1147293/ // Add workspace edits var applyChangesOperations = operations.OfType<ApplyChangesOperation>(); if (applyChangesOperations.Any()) { var solution = document.Project.Solution; var textDiffService = solution.Workspace.Services.GetService<IDocumentTextDifferencingService>(); using var _ = ArrayBuilder<TextDocumentEdit>.GetInstance(out var textDocumentEdits); foreach (var applyChangesOperation in applyChangesOperations) { var changes = applyChangesOperation.ChangedSolution.GetChanges(solution); var projectChanges = changes.GetProjectChanges(); // TO-DO: If the change involves adding or removing a document, execute via command instead of WorkspaceEdit // until adding/removing documents is supported in LSP: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1147293/ // After support is added, remove the below if-statement and add code to support adding/removing documents. var addedDocuments = projectChanges.SelectMany( pc => pc.GetAddedDocuments().Concat(pc.GetAddedAdditionalDocuments().Concat(pc.GetAddedAnalyzerConfigDocuments()))); var removedDocuments = projectChanges.SelectMany( pc => pc.GetRemovedDocuments().Concat(pc.GetRemovedAdditionalDocuments().Concat(pc.GetRemovedAnalyzerConfigDocuments()))); if (addedDocuments.Any() || removedDocuments.Any()) { codeAction.Command = SetCommand(codeAction.Title, data); return codeAction; } // TO-DO: If the change involves adding or removing a project reference, execute via command instead of // WorkspaceEdit until adding/removing project references is supported in LSP: // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1166040 var projectReferences = projectChanges.SelectMany( pc => pc.GetAddedProjectReferences().Concat(pc.GetRemovedProjectReferences())); if (projectReferences.Any()) { codeAction.Command = SetCommand(codeAction.Title, data); return codeAction; } var changedDocuments = projectChanges.SelectMany(pc => pc.GetChangedDocuments()); var changedAnalyzerConfigDocuments = projectChanges.SelectMany(pc => pc.GetChangedAnalyzerConfigDocuments()); var changedAdditionalDocuments = projectChanges.SelectMany(pc => pc.GetChangedAdditionalDocuments()); // Changed documents await AddTextDocumentEditsAsync( textDocumentEdits, changedDocuments, applyChangesOperation.ChangedSolution.GetDocument, solution.GetDocument, textDiffService, cancellationToken).ConfigureAwait(false); // Changed analyzer config documents await AddTextDocumentEditsAsync( textDocumentEdits, changedAnalyzerConfigDocuments, applyChangesOperation.ChangedSolution.GetAnalyzerConfigDocument, solution.GetAnalyzerConfigDocument, textDiffService: null, cancellationToken).ConfigureAwait(false); // Changed additional documents await AddTextDocumentEditsAsync( textDocumentEdits, changedAdditionalDocuments, applyChangesOperation.ChangedSolution.GetAdditionalDocument, solution.GetAdditionalDocument, textDiffService: null, cancellationToken).ConfigureAwait(false); } codeAction.Edit = new LSP.WorkspaceEdit { DocumentChanges = textDocumentEdits.ToArray() }; } return codeAction; // Local functions static LSP.Command SetCommand(string title, CodeActionResolveData data) => new LSP.Command { CommandIdentifier = CodeActionsHandler.RunCodeActionCommandName, Title = title, Arguments = new object[] { data } }; static async Task AddTextDocumentEditsAsync<T>( ArrayBuilder<TextDocumentEdit> textDocumentEdits, IEnumerable<DocumentId> changedDocuments, Func<DocumentId, T?> getNewDocumentFunc, Func<DocumentId, T?> getOldDocumentFunc, IDocumentTextDifferencingService? textDiffService, CancellationToken cancellationToken) where T : TextDocument { foreach (var docId in changedDocuments) { var newTextDoc = getNewDocumentFunc(docId); var oldTextDoc = getOldDocumentFunc(docId); Contract.ThrowIfNull(oldTextDoc); Contract.ThrowIfNull(newTextDoc); var oldText = await oldTextDoc.GetTextAsync(cancellationToken).ConfigureAwait(false); IEnumerable<TextChange> textChanges; // Normal documents have a unique service for calculating minimal text edits. If we used the standard 'GetTextChanges' // method instead, we would get a change that spans the entire document, which we ideally want to avoid. if (newTextDoc is Document newDoc && oldTextDoc is Document oldDoc) { Contract.ThrowIfNull(textDiffService); textChanges = await textDiffService.GetTextChangesAsync(oldDoc, newDoc, cancellationToken).ConfigureAwait(false); } else { var newText = await newTextDoc.GetTextAsync(cancellationToken).ConfigureAwait(false); textChanges = newText.GetTextChanges(oldText); } var edits = textChanges.Select(tc => ProtocolConversions.TextChangeToTextEdit(tc, oldText)).ToArray(); var documentIdentifier = new OptionalVersionedTextDocumentIdentifier { Uri = newTextDoc.GetURI() }; textDocumentEdits.Add(new TextDocumentEdit { TextDocument = documentIdentifier, Edits = edits.ToArray() }); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.LanguageServer.Handler.CodeActions; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Newtonsoft.Json.Linq; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { /// <summary> /// Resolves a code action by filling out its Edit and/or Command property. /// The handler is triggered only when a user hovers over a code action. This /// system allows the basic code action data to be computed quickly, and the /// complex data, such as edits and commands, to be computed only when necessary /// (i.e. when hovering/previewing a code action). /// </summary> internal class CodeActionResolveHandler : IRequestHandler<LSP.CodeAction, LSP.CodeAction> { private readonly CodeActionsCache _codeActionsCache; private readonly ICodeFixService _codeFixService; private readonly ICodeRefactoringService _codeRefactoringService; public CodeActionResolveHandler( CodeActionsCache codeActionsCache, ICodeFixService codeFixService, ICodeRefactoringService codeRefactoringService) { _codeActionsCache = codeActionsCache; _codeFixService = codeFixService; _codeRefactoringService = codeRefactoringService; } public string Method => LSP.Methods.CodeActionResolveName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CodeAction request) => ((JToken)request.Data!).ToObject<CodeActionResolveData>().TextDocument; public async Task<LSP.CodeAction> HandleRequestAsync(LSP.CodeAction codeAction, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; Contract.ThrowIfNull(document); var data = ((JToken)codeAction.Data!).ToObject<CodeActionResolveData>(); var codeActions = await CodeActionHelpers.GetCodeActionsAsync( _codeActionsCache, document, data.Range, _codeFixService, _codeRefactoringService, cancellationToken).ConfigureAwait(false); var codeActionToResolve = CodeActionHelpers.GetCodeActionToResolve( data.UniqueIdentifier, codeActions); Contract.ThrowIfNull(codeActionToResolve); var operations = await codeActionToResolve.GetOperationsAsync(cancellationToken).ConfigureAwait(false); if (operations.IsEmpty) { return codeAction; } // If we have all non-ApplyChangesOperations, set up to run as command on the server // instead of using WorkspaceEdits. if (operations.All(operation => !(operation is ApplyChangesOperation))) { codeAction.Command = SetCommand(codeAction.Title, data); return codeAction; } // TO-DO: We currently must execute code actions which add new documents on the server as commands, // since there is no LSP support for adding documents yet. In the future, we should move these actions // to execute on the client. // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1147293/ // Add workspace edits var applyChangesOperations = operations.OfType<ApplyChangesOperation>(); if (applyChangesOperations.Any()) { var solution = document.Project.Solution; var textDiffService = solution.Workspace.Services.GetService<IDocumentTextDifferencingService>(); using var _ = ArrayBuilder<TextDocumentEdit>.GetInstance(out var textDocumentEdits); foreach (var applyChangesOperation in applyChangesOperations) { var changes = applyChangesOperation.ChangedSolution.GetChanges(solution); var projectChanges = changes.GetProjectChanges(); // TO-DO: If the change involves adding or removing a document, execute via command instead of WorkspaceEdit // until adding/removing documents is supported in LSP: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1147293/ // After support is added, remove the below if-statement and add code to support adding/removing documents. var addedDocuments = projectChanges.SelectMany( pc => pc.GetAddedDocuments().Concat(pc.GetAddedAdditionalDocuments().Concat(pc.GetAddedAnalyzerConfigDocuments()))); var removedDocuments = projectChanges.SelectMany( pc => pc.GetRemovedDocuments().Concat(pc.GetRemovedAdditionalDocuments().Concat(pc.GetRemovedAnalyzerConfigDocuments()))); if (addedDocuments.Any() || removedDocuments.Any()) { codeAction.Command = SetCommand(codeAction.Title, data); return codeAction; } // TO-DO: If the change involves adding or removing a project reference, execute via command instead of // WorkspaceEdit until adding/removing project references is supported in LSP: // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1166040 var projectReferences = projectChanges.SelectMany( pc => pc.GetAddedProjectReferences().Concat(pc.GetRemovedProjectReferences())); if (projectReferences.Any()) { codeAction.Command = SetCommand(codeAction.Title, data); return codeAction; } var changedDocuments = projectChanges.SelectMany(pc => pc.GetChangedDocuments()); var changedAnalyzerConfigDocuments = projectChanges.SelectMany(pc => pc.GetChangedAnalyzerConfigDocuments()); var changedAdditionalDocuments = projectChanges.SelectMany(pc => pc.GetChangedAdditionalDocuments()); // Changed documents await AddTextDocumentEditsAsync( textDocumentEdits, changedDocuments, applyChangesOperation.ChangedSolution.GetDocument, solution.GetDocument, textDiffService, cancellationToken).ConfigureAwait(false); // Changed analyzer config documents await AddTextDocumentEditsAsync( textDocumentEdits, changedAnalyzerConfigDocuments, applyChangesOperation.ChangedSolution.GetAnalyzerConfigDocument, solution.GetAnalyzerConfigDocument, textDiffService: null, cancellationToken).ConfigureAwait(false); // Changed additional documents await AddTextDocumentEditsAsync( textDocumentEdits, changedAdditionalDocuments, applyChangesOperation.ChangedSolution.GetAdditionalDocument, solution.GetAdditionalDocument, textDiffService: null, cancellationToken).ConfigureAwait(false); } codeAction.Edit = new LSP.WorkspaceEdit { DocumentChanges = textDocumentEdits.ToArray() }; } return codeAction; // Local functions static LSP.Command SetCommand(string title, CodeActionResolveData data) => new LSP.Command { CommandIdentifier = CodeActionsHandler.RunCodeActionCommandName, Title = title, Arguments = new object[] { data } }; static async Task AddTextDocumentEditsAsync<T>( ArrayBuilder<TextDocumentEdit> textDocumentEdits, IEnumerable<DocumentId> changedDocuments, Func<DocumentId, T?> getNewDocumentFunc, Func<DocumentId, T?> getOldDocumentFunc, IDocumentTextDifferencingService? textDiffService, CancellationToken cancellationToken) where T : TextDocument { foreach (var docId in changedDocuments) { var newTextDoc = getNewDocumentFunc(docId); var oldTextDoc = getOldDocumentFunc(docId); Contract.ThrowIfNull(oldTextDoc); Contract.ThrowIfNull(newTextDoc); var oldText = await oldTextDoc.GetTextAsync(cancellationToken).ConfigureAwait(false); IEnumerable<TextChange> textChanges; // Normal documents have a unique service for calculating minimal text edits. If we used the standard 'GetTextChanges' // method instead, we would get a change that spans the entire document, which we ideally want to avoid. if (newTextDoc is Document newDoc && oldTextDoc is Document oldDoc) { Contract.ThrowIfNull(textDiffService); textChanges = await textDiffService.GetTextChangesAsync(oldDoc, newDoc, cancellationToken).ConfigureAwait(false); } else { var newText = await newTextDoc.GetTextAsync(cancellationToken).ConfigureAwait(false); textChanges = newText.GetTextChanges(oldText); } var edits = textChanges.Select(tc => ProtocolConversions.TextChangeToTextEdit(tc, oldText)).ToArray(); var documentIdentifier = new OptionalVersionedTextDocumentIdentifier { Uri = newTextDoc.GetURI() }; textDocumentEdits.Add(new TextDocumentEdit { TextDocument = documentIdentifier, Edits = edits.ToArray() }); } } } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Compilers/Core/Portable/Symbols/IPointerTypeSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a pointer type such as "int *". Pointer types /// are used only in unsafe code. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IPointerTypeSymbol : ITypeSymbol { /// <summary> /// Gets the type of the storage location that an instance of the pointer type points to. /// </summary> ITypeSymbol PointedAtType { get; } /// <summary> /// Custom modifiers associated with the pointer type, or an empty array if there are none. /// </summary> /// <remarks> /// Some managed languages may represent special information about the pointer type /// as a custom modifier on either the pointer type or the element type, or /// both. /// </remarks> ImmutableArray<CustomModifier> CustomModifiers { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a pointer type such as "int *". Pointer types /// are used only in unsafe code. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IPointerTypeSymbol : ITypeSymbol { /// <summary> /// Gets the type of the storage location that an instance of the pointer type points to. /// </summary> ITypeSymbol PointedAtType { get; } /// <summary> /// Custom modifiers associated with the pointer type, or an empty array if there are none. /// </summary> /// <remarks> /// Some managed languages may represent special information about the pointer type /// as a custom modifier on either the pointer type or the element type, or /// both. /// </remarks> ImmutableArray<CustomModifier> CustomModifiers { get; } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/EditorFeatures/CSharpTest2/Recommendations/UncheckedKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 UncheckedKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"var q = $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTypeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDefault() { await VerifyAbsenceAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInSizeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [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.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class UncheckedKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"var q = $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTypeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDefault() { await VerifyAbsenceAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInSizeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Features/Core/Portable/CommentSelection/AbstractCommentSelectionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CommentSelection { internal abstract class AbstractCommentSelectionService : ICommentSelectionService { public abstract string BlockCommentEndString { get; } public abstract string BlockCommentStartString { get; } public abstract string SingleLineCommentString { get; } public abstract bool SupportsBlockComment { get; } public Task<Document> FormatAsync(Document document, ImmutableArray<TextSpan> changes, CancellationToken cancellationToken) { var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken); var formattingSpans = changes.Select(s => CommonFormattingHelpers.GetFormattingSpan(root, s)); return Formatter.FormatAsync(document, formattingSpans, cancellationToken: cancellationToken); } public Task<CommentSelectionInfo> GetInfoAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) => Task.FromResult(SupportsBlockComment ? new CommentSelectionInfo(true, SupportsBlockComment, SingleLineCommentString, BlockCommentStartString, BlockCommentEndString) : new CommentSelectionInfo(true, SupportsBlockComment, SingleLineCommentString, "", "")); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CommentSelection { internal abstract class AbstractCommentSelectionService : ICommentSelectionService { public abstract string BlockCommentEndString { get; } public abstract string BlockCommentStartString { get; } public abstract string SingleLineCommentString { get; } public abstract bool SupportsBlockComment { get; } public Task<Document> FormatAsync(Document document, ImmutableArray<TextSpan> changes, CancellationToken cancellationToken) { var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken); var formattingSpans = changes.Select(s => CommonFormattingHelpers.GetFormattingSpan(root, s)); return Formatter.FormatAsync(document, formattingSpans, cancellationToken: cancellationToken); } public Task<CommentSelectionInfo> GetInfoAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) => Task.FromResult(SupportsBlockComment ? new CommentSelectionInfo(true, SupportsBlockComment, SingleLineCommentString, BlockCommentStartString, BlockCommentEndString) : new CommentSelectionInfo(true, SupportsBlockComment, SingleLineCommentString, "", "")); } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Compilers/Test/Core/PDB/DeterministicBuildCompilationTestHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Security.Cryptography; using System.Text; using Microsoft.Cci; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Roslyn.Test.Utilities.PDB { internal static partial class DeterministicBuildCompilationTestHelpers { public static void VerifyPdbOption<T>(this ImmutableDictionary<string, string> pdbOptions, string pdbName, T expectedValue, Func<T, bool> isDefault = null, Func<T, string> toString = null) { bool expectedIsDefault = (isDefault != null) ? isDefault(expectedValue) : EqualityComparer<T>.Default.Equals(expectedValue, default); var expectedValueString = expectedIsDefault ? null : (toString != null) ? toString(expectedValue) : expectedValue.ToString(); pdbOptions.TryGetValue(pdbName, out var actualValueString); Assert.Equal(expectedValueString, actualValueString); } public static IEnumerable<EmitOptions> GetEmitOptions() { var emitOptions = new EmitOptions( debugInformationFormat: DebugInformationFormat.Embedded, pdbChecksumAlgorithm: HashAlgorithmName.SHA256, defaultSourceFileEncoding: Encoding.UTF32); yield return emitOptions; yield return emitOptions.WithDefaultSourceFileEncoding(Encoding.ASCII); yield return emitOptions.WithDefaultSourceFileEncoding(null).WithFallbackSourceFileEncoding(Encoding.Unicode); yield return emitOptions.WithFallbackSourceFileEncoding(Encoding.Unicode).WithDefaultSourceFileEncoding(Encoding.ASCII); } internal static void AssertCommonOptions(EmitOptions emitOptions, CompilationOptions compilationOptions, Compilation compilation, ImmutableDictionary<string, string> pdbOptions) { pdbOptions.VerifyPdbOption("version", 2); pdbOptions.VerifyPdbOption("fallback-encoding", emitOptions.FallbackSourceFileEncoding, toString: v => v.WebName); pdbOptions.VerifyPdbOption("default-encoding", emitOptions.DefaultSourceFileEncoding, toString: v => v.WebName); int portabilityPolicy = 0; if (compilationOptions.AssemblyIdentityComparer is DesktopAssemblyIdentityComparer identityComparer) { portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightLibraryAssembliesPortability ? 0b1 : 0; portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightPlatformAssembliesPortability ? 0b10 : 0; } pdbOptions.VerifyPdbOption("portability-policy", portabilityPolicy); var compilerVersion = typeof(Compilation).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion; Assert.Equal(compilerVersion.ToString(), pdbOptions["compiler-version"]); var runtimeVersion = typeof(object).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion; Assert.Equal(runtimeVersion, pdbOptions[CompilationOptionNames.RuntimeVersion]); pdbOptions.VerifyPdbOption( "optimization", (compilationOptions.OptimizationLevel, compilationOptions.DebugPlusMode), toString: v => v.OptimizationLevel.ToPdbSerializedString(v.DebugPlusMode)); Assert.Equal(compilation.Language, pdbOptions["language"]); } public static void VerifyReferenceInfo(TestMetadataReferenceInfo[] references, TargetFramework targetFramework, BlobReader metadataReferenceReader) { var frameworkReferences = TargetFrameworkUtil.GetReferences(targetFramework); var count = 0; while (metadataReferenceReader.RemainingBytes > 0) { var info = ParseMetadataReferenceInfo(ref metadataReferenceReader); if (frameworkReferences.Any(x => x.GetModuleVersionId() == info.Mvid)) { count++; continue; } var testReference = references.Single(x => x.MetadataReferenceInfo.Mvid == info.Mvid); testReference.MetadataReferenceInfo.AssertEqual(info); count++; } Assert.Equal(references.Length + frameworkReferences.Length, count); } public static BlobReader GetSingleBlob(Guid infoGuid, MetadataReader pdbReader) { return (from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition) let cdi = pdbReader.GetCustomDebugInformation(cdiHandle) where pdbReader.GetGuid(cdi.Kind) == infoGuid select pdbReader.GetBlobReader(cdi.Value)).Single(); } public static MetadataReferenceInfo ParseMetadataReferenceInfo(ref BlobReader blobReader) { // Order of information // File name (null terminated string): A.exe // Extern Alias (null terminated string): a1,a2,a3 // EmbedInteropTypes/MetadataImageKind (byte) // COFF header Timestamp field (4 byte int) // COFF header SizeOfImage field (4 byte int) // MVID (Guid, 24 bytes) var terminatorIndex = blobReader.IndexOf(0); Assert.NotEqual(-1, terminatorIndex); var name = blobReader.ReadUTF8(terminatorIndex); // Skip the null terminator blobReader.ReadByte(); terminatorIndex = blobReader.IndexOf(0); Assert.NotEqual(-1, terminatorIndex); var externAliases = blobReader.ReadUTF8(terminatorIndex); blobReader.ReadByte(); var embedInteropTypesAndKind = blobReader.ReadByte(); var embedInteropTypes = (embedInteropTypesAndKind & 0b10) == 0b10; var kind = (embedInteropTypesAndKind & 0b1) == 0b1 ? MetadataImageKind.Assembly : MetadataImageKind.Module; var timestamp = blobReader.ReadInt32(); var imageSize = blobReader.ReadInt32(); var mvid = blobReader.ReadGuid(); return new MetadataReferenceInfo( timestamp, imageSize, name, mvid, string.IsNullOrEmpty(externAliases) ? ImmutableArray<string>.Empty : externAliases.Split(',').ToImmutableArray(), kind, embedInteropTypes); } public static ImmutableDictionary<string, string> ParseCompilationOptions(BlobReader blobReader) { // Compiler flag bytes are UTF-8 null-terminated key-value pairs string key = null; Dictionary<string, string> kvp = new Dictionary<string, string>(); for (; ; ) { var nullIndex = blobReader.IndexOf(0); if (nullIndex == -1) { break; } var value = blobReader.ReadUTF8(nullIndex); // Skip the null terminator blobReader.ReadByte(); if (key is null) { key = value; } else { kvp[key] = value; key = null; } } Assert.Null(key); Assert.Equal(0, blobReader.RemainingBytes); return kvp.ToImmutableDictionary(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Security.Cryptography; using System.Text; using Microsoft.Cci; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Roslyn.Test.Utilities.PDB { internal static partial class DeterministicBuildCompilationTestHelpers { public static void VerifyPdbOption<T>(this ImmutableDictionary<string, string> pdbOptions, string pdbName, T expectedValue, Func<T, bool> isDefault = null, Func<T, string> toString = null) { bool expectedIsDefault = (isDefault != null) ? isDefault(expectedValue) : EqualityComparer<T>.Default.Equals(expectedValue, default); var expectedValueString = expectedIsDefault ? null : (toString != null) ? toString(expectedValue) : expectedValue.ToString(); pdbOptions.TryGetValue(pdbName, out var actualValueString); Assert.Equal(expectedValueString, actualValueString); } public static IEnumerable<EmitOptions> GetEmitOptions() { var emitOptions = new EmitOptions( debugInformationFormat: DebugInformationFormat.Embedded, pdbChecksumAlgorithm: HashAlgorithmName.SHA256, defaultSourceFileEncoding: Encoding.UTF32); yield return emitOptions; yield return emitOptions.WithDefaultSourceFileEncoding(Encoding.ASCII); yield return emitOptions.WithDefaultSourceFileEncoding(null).WithFallbackSourceFileEncoding(Encoding.Unicode); yield return emitOptions.WithFallbackSourceFileEncoding(Encoding.Unicode).WithDefaultSourceFileEncoding(Encoding.ASCII); } internal static void AssertCommonOptions(EmitOptions emitOptions, CompilationOptions compilationOptions, Compilation compilation, ImmutableDictionary<string, string> pdbOptions) { pdbOptions.VerifyPdbOption("version", 2); pdbOptions.VerifyPdbOption("fallback-encoding", emitOptions.FallbackSourceFileEncoding, toString: v => v.WebName); pdbOptions.VerifyPdbOption("default-encoding", emitOptions.DefaultSourceFileEncoding, toString: v => v.WebName); int portabilityPolicy = 0; if (compilationOptions.AssemblyIdentityComparer is DesktopAssemblyIdentityComparer identityComparer) { portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightLibraryAssembliesPortability ? 0b1 : 0; portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightPlatformAssembliesPortability ? 0b10 : 0; } pdbOptions.VerifyPdbOption("portability-policy", portabilityPolicy); var compilerVersion = typeof(Compilation).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion; Assert.Equal(compilerVersion.ToString(), pdbOptions["compiler-version"]); var runtimeVersion = typeof(object).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion; Assert.Equal(runtimeVersion, pdbOptions[CompilationOptionNames.RuntimeVersion]); pdbOptions.VerifyPdbOption( "optimization", (compilationOptions.OptimizationLevel, compilationOptions.DebugPlusMode), toString: v => v.OptimizationLevel.ToPdbSerializedString(v.DebugPlusMode)); Assert.Equal(compilation.Language, pdbOptions["language"]); } public static void VerifyReferenceInfo(TestMetadataReferenceInfo[] references, TargetFramework targetFramework, BlobReader metadataReferenceReader) { var frameworkReferences = TargetFrameworkUtil.GetReferences(targetFramework); var count = 0; while (metadataReferenceReader.RemainingBytes > 0) { var info = ParseMetadataReferenceInfo(ref metadataReferenceReader); if (frameworkReferences.Any(x => x.GetModuleVersionId() == info.Mvid)) { count++; continue; } var testReference = references.Single(x => x.MetadataReferenceInfo.Mvid == info.Mvid); testReference.MetadataReferenceInfo.AssertEqual(info); count++; } Assert.Equal(references.Length + frameworkReferences.Length, count); } public static BlobReader GetSingleBlob(Guid infoGuid, MetadataReader pdbReader) { return (from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition) let cdi = pdbReader.GetCustomDebugInformation(cdiHandle) where pdbReader.GetGuid(cdi.Kind) == infoGuid select pdbReader.GetBlobReader(cdi.Value)).Single(); } public static MetadataReferenceInfo ParseMetadataReferenceInfo(ref BlobReader blobReader) { // Order of information // File name (null terminated string): A.exe // Extern Alias (null terminated string): a1,a2,a3 // EmbedInteropTypes/MetadataImageKind (byte) // COFF header Timestamp field (4 byte int) // COFF header SizeOfImage field (4 byte int) // MVID (Guid, 24 bytes) var terminatorIndex = blobReader.IndexOf(0); Assert.NotEqual(-1, terminatorIndex); var name = blobReader.ReadUTF8(terminatorIndex); // Skip the null terminator blobReader.ReadByte(); terminatorIndex = blobReader.IndexOf(0); Assert.NotEqual(-1, terminatorIndex); var externAliases = blobReader.ReadUTF8(terminatorIndex); blobReader.ReadByte(); var embedInteropTypesAndKind = blobReader.ReadByte(); var embedInteropTypes = (embedInteropTypesAndKind & 0b10) == 0b10; var kind = (embedInteropTypesAndKind & 0b1) == 0b1 ? MetadataImageKind.Assembly : MetadataImageKind.Module; var timestamp = blobReader.ReadInt32(); var imageSize = blobReader.ReadInt32(); var mvid = blobReader.ReadGuid(); return new MetadataReferenceInfo( timestamp, imageSize, name, mvid, string.IsNullOrEmpty(externAliases) ? ImmutableArray<string>.Empty : externAliases.Split(',').ToImmutableArray(), kind, embedInteropTypes); } public static ImmutableDictionary<string, string> ParseCompilationOptions(BlobReader blobReader) { // Compiler flag bytes are UTF-8 null-terminated key-value pairs string key = null; Dictionary<string, string> kvp = new Dictionary<string, string>(); for (; ; ) { var nullIndex = blobReader.IndexOf(0); if (nullIndex == -1) { break; } var value = blobReader.ReadUTF8(nullIndex); // Skip the null terminator blobReader.ReadByte(); if (key is null) { key = value; } else { kvp[key] = value; key = null; } } Assert.Null(key); Assert.Equal(0, blobReader.RemainingBytes); return kvp.ToImmutableDictionary(); } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/EditorFeatures/Core/ReferenceHighlighting/Tags/WrittenReferenceHighlightTag.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.Shared.Tagging; namespace Microsoft.CodeAnalysis.Editor.ReferenceHighlighting { internal class WrittenReferenceHighlightTag : NavigableHighlightTag { internal const string TagId = "MarkerFormatDefinition/HighlightedWrittenReference"; public static readonly WrittenReferenceHighlightTag Instance = new(); private WrittenReferenceHighlightTag() : base(TagId) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.Shared.Tagging; namespace Microsoft.CodeAnalysis.Editor.ReferenceHighlighting { internal class WrittenReferenceHighlightTag : NavigableHighlightTag { internal const string TagId = "MarkerFormatDefinition/HighlightedWrittenReference"; public static readonly WrittenReferenceHighlightTag Instance = new(); private WrittenReferenceHighlightTag() : base(TagId) { } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Compilers/CSharp/Portable/Errors/XmlSyntaxDiagnosticInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Globalization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class XmlSyntaxDiagnosticInfo : SyntaxDiagnosticInfo { static XmlSyntaxDiagnosticInfo() { ObjectBinder.RegisterTypeReader(typeof(XmlSyntaxDiagnosticInfo), r => new XmlSyntaxDiagnosticInfo(r)); } private readonly XmlParseErrorCode _xmlErrorCode; internal XmlSyntaxDiagnosticInfo(XmlParseErrorCode code, params object[] args) : this(0, 0, code, args) { } internal XmlSyntaxDiagnosticInfo(int offset, int width, XmlParseErrorCode code, params object[] args) : base(offset, width, ErrorCode.WRN_XMLParseError, args) { _xmlErrorCode = code; } #region Serialization protected override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteUInt32((uint)_xmlErrorCode); } private XmlSyntaxDiagnosticInfo(ObjectReader reader) : base(reader) { _xmlErrorCode = (XmlParseErrorCode)reader.ReadUInt32(); } #endregion public override string GetMessage(IFormatProvider formatProvider = null) { var culture = formatProvider as CultureInfo; string messagePrefix = this.MessageProvider.LoadMessage(this.Code, culture); string message = ErrorFacts.GetMessage(_xmlErrorCode, culture); System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(message)); if (this.Arguments == null || this.Arguments.Length == 0) { return String.Format(formatProvider, messagePrefix, message); } return String.Format(formatProvider, String.Format(formatProvider, messagePrefix, message), GetArgumentsToUse(formatProvider)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Globalization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class XmlSyntaxDiagnosticInfo : SyntaxDiagnosticInfo { static XmlSyntaxDiagnosticInfo() { ObjectBinder.RegisterTypeReader(typeof(XmlSyntaxDiagnosticInfo), r => new XmlSyntaxDiagnosticInfo(r)); } private readonly XmlParseErrorCode _xmlErrorCode; internal XmlSyntaxDiagnosticInfo(XmlParseErrorCode code, params object[] args) : this(0, 0, code, args) { } internal XmlSyntaxDiagnosticInfo(int offset, int width, XmlParseErrorCode code, params object[] args) : base(offset, width, ErrorCode.WRN_XMLParseError, args) { _xmlErrorCode = code; } #region Serialization protected override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteUInt32((uint)_xmlErrorCode); } private XmlSyntaxDiagnosticInfo(ObjectReader reader) : base(reader) { _xmlErrorCode = (XmlParseErrorCode)reader.ReadUInt32(); } #endregion public override string GetMessage(IFormatProvider formatProvider = null) { var culture = formatProvider as CultureInfo; string messagePrefix = this.MessageProvider.LoadMessage(this.Code, culture); string message = ErrorFacts.GetMessage(_xmlErrorCode, culture); System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(message)); if (this.Arguments == null || this.Arguments.Length == 0) { return String.Format(formatProvider, messagePrefix, message); } return String.Format(formatProvider, String.Format(formatProvider, messagePrefix, message), GetArgumentsToUse(formatProvider)); } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_Security.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_Security : WellKnownAttributesTestBase { #region Functional Tests [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void HostProtectionSecurityAttribute() { string source = @" [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public struct EventDescriptor { }"; Func<bool, Action<ModuleSymbol>> attributeValidator = isFromSource => (ModuleSymbol module) => { var assembly = module.ContainingAssembly; var type = (Cci.ITypeDefinition)module.GlobalNamespace.GetMember("EventDescriptor").GetCciAdapter(); if (isFromSource) { var sourceAssembly = (SourceAssemblySymbol)assembly; var compilation = sourceAssembly.DeclaringCompilation; Assert.True(type.HasDeclarativeSecurity); IEnumerable<Cci.SecurityAttribute> typeSecurityAttributes = type.SecurityAttributes; // Get System.Security.Permissions.HostProtection var emittedName = MetadataTypeName.FromNamespaceAndTypeName("System.Security.Permissions", "HostProtectionAttribute"); NamedTypeSymbol hostProtectionAttr = sourceAssembly.CorLibrary.LookupTopLevelMetadataType(ref emittedName, true); Assert.NotNull(hostProtectionAttr); // Verify type security attributes Assert.Equal(1, typeSecurityAttributes.Count()); // Verify [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] var securityAttribute = typeSecurityAttributes.First(); Assert.Equal(DeclarativeSecurityAction.LinkDemand, securityAttribute.Action); var typeAttribute = (CSharpAttributeData)securityAttribute.Attribute; Assert.Equal(hostProtectionAttr, typeAttribute.AttributeClass); Assert.Equal(0, typeAttribute.CommonConstructorArguments.Length); typeAttribute.VerifyNamedArgumentValue(0, "MayLeakOnAbort", TypedConstantKind.Primitive, true); } }; CompileAndVerifyWithMscorlib40(source, symbolValidator: attributeValidator(false), sourceSymbolValidator: attributeValidator(true)); } [Fact, WorkItem(544956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544956")] public void SuppressUnmanagedCodeSecurityAttribute() { string source = @" [System.Security.SuppressUnmanagedCodeSecurityAttribute] class Goo { [System.Security.SuppressUnmanagedCodeSecurityAttribute] public static void Main() {} }"; CompileAndVerify(source); } [WorkItem(544929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544929")] [Fact] public void PrincipalPermissionAttribute() { string source = @" using System.Security.Permissions; class Program { [PrincipalPermission((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [PrincipalPermission(SecurityAction.Assert)] [PrincipalPermission(SecurityAction.Demand)] [PrincipalPermission(SecurityAction.Deny)] [PrincipalPermission(SecurityAction.InheritanceDemand)] // CS7052 [PrincipalPermission(SecurityAction.LinkDemand)] // CS7052 [PrincipalPermission(SecurityAction.PermitOnly)] static void Main(string[] args) { } }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (9,26): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PrincipalPermission(SecurityAction.Deny)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (10,26): error CS7052: SecurityAction value 'SecurityAction.InheritanceDemand' is invalid for PrincipalPermission attribute // [PrincipalPermission(SecurityAction.InheritanceDemand)] // CS7052 Diagnostic(ErrorCode.ERR_PrincipalPermissionInvalidAction, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"), // (11,26): error CS7052: SecurityAction value 'SecurityAction.LinkDemand' is invalid for PrincipalPermission attribute // [PrincipalPermission(SecurityAction.LinkDemand)] // CS7052 Diagnostic(ErrorCode.ERR_PrincipalPermissionInvalidAction, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand")); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7048ERR_SecurityAttributeMissingAction() { string source = @" using System.Security; using System.Security.Permissions; class MySecurityAttribute : CodeAccessSecurityAttribute { public bool Field; public bool Prop { get; set; } public override IPermission CreatePermission() { return null; } public MySecurityAttribute() : base(SecurityAction.Assert) { } public MySecurityAttribute(int x, SecurityAction a1) : base(a1) { } } [MySecurityAttribute()] [MySecurityAttribute(Field = true)] [MySecurityAttribute(Field = true, Prop = true)] [MySecurityAttribute(Prop = true)] [MySecurityAttribute(Prop = true, Field = true)] [MySecurityAttribute(x: 0, a1: SecurityAction.Assert)] [MySecurityAttribute(a1: SecurityAction.Assert, x: 0)] public class C {} "; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (15,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute()] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (16,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Field = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (17,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Field = true, Prop = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (18,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Prop = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (19,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Prop = true, Field = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (20,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(x: 0, a1: SecurityAction.Assert)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (21,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(a1: SecurityAction.Assert, x: 0)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute")); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7049ERR_SecurityAttributeInvalidAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission((SecurityAction)0)] // Invalid attribute argument [PrincipalPermission((SecurityAction)11)] // Invalid attribute argument [PrincipalPermission((SecurityAction)(-1))] // Invalid attribute argument [PrincipalPermission()] // Invalid attribute constructor public class C { [PrincipalPermission(SecurityAction.Demand)] // Invalid attribute target public int x; } }"; var compilation = CreateCompilationWithMscorlib40(source); compilation.VerifyDiagnostics( // (9,6): error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'System.Security.Permissions.PrincipalPermissionAttribute.PrincipalPermissionAttribute(System.Security.Permissions.SecurityAction)' // [PrincipalPermission()] // Invalid attribute constructor Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "PrincipalPermission()").WithArguments("action", "System.Security.Permissions.PrincipalPermissionAttribute.PrincipalPermissionAttribute(System.Security.Permissions.SecurityAction)").WithLocation(9, 6), // (6,26): error CS7049: Security attribute 'PrincipalPermission' has an invalid SecurityAction value '(SecurityAction)0' // [PrincipalPermission((SecurityAction)0)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)0").WithArguments("PrincipalPermission", "(SecurityAction)0").WithLocation(6, 26), // (7,26): error CS7049: Security attribute 'PrincipalPermission' has an invalid SecurityAction value '(SecurityAction)11' // [PrincipalPermission((SecurityAction)11)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)11").WithArguments("PrincipalPermission", "(SecurityAction)11").WithLocation(7, 26), // (8,26): error CS7049: Security attribute 'PrincipalPermission' has an invalid SecurityAction value '(SecurityAction)(-1)' // [PrincipalPermission((SecurityAction)(-1))] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)(-1)").WithArguments("PrincipalPermission", "(SecurityAction)(-1)").WithLocation(8, 26), // (12,10): error CS0592: Attribute 'PrincipalPermission' is not valid on this declaration type. It is only valid on 'class, method' declarations. // [PrincipalPermission(SecurityAction.Demand)] // Invalid attribute target Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "PrincipalPermission").WithArguments("PrincipalPermission", "class, method").WithLocation(12, 10)); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7049ERR_SecurityAttributeInvalidAction_02() { string source = @" using System.Security.Permissions; public class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction action): base(action) {} public override System.Security.IPermission CreatePermission() { return null; } } namespace N { [MySecurityAttribute((SecurityAction)0)] // Invalid attribute argument [MySecurityAttribute((SecurityAction)11)] // Invalid attribute argument [MySecurityAttribute((SecurityAction)(-1))] // Invalid attribute argument [MySecurityAttribute()] // Invalid attribute constructor public class C { [MySecurityAttribute(SecurityAction.Demand)] // Invalid attribute target public int x; } }"; var compilation = CreateCompilationWithMscorlib40(source); compilation.VerifyDiagnostics( // (12,26): error CS7049: Security attribute 'MySecurityAttribute' has an invalid SecurityAction value '(SecurityAction)0' // [MySecurityAttribute((SecurityAction)0)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)0").WithArguments("MySecurityAttribute", "(SecurityAction)0").WithLocation(12, 26), // (13,26): error CS7049: Security attribute 'MySecurityAttribute' has an invalid SecurityAction value '(SecurityAction)11' // [MySecurityAttribute((SecurityAction)11)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)11").WithArguments("MySecurityAttribute", "(SecurityAction)11").WithLocation(13, 26), // (14,26): error CS7049: Security attribute 'MySecurityAttribute' has an invalid SecurityAction value '(SecurityAction)(-1)' // [MySecurityAttribute((SecurityAction)(-1))] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)(-1)").WithArguments("MySecurityAttribute", "(SecurityAction)(-1)").WithLocation(14, 26), // (15,6): error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'MySecurityAttribute.MySecurityAttribute(System.Security.Permissions.SecurityAction)' // [MySecurityAttribute()] // Invalid attribute constructor Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "MySecurityAttribute()").WithArguments("action", "MySecurityAttribute.MySecurityAttribute(System.Security.Permissions.SecurityAction)").WithLocation(15, 6), // (18,10): error CS0592: Attribute 'MySecurityAttribute' is not valid on this declaration type. It is only valid on 'assembly, class, struct, constructor, method' declarations. // [MySecurityAttribute(SecurityAction.Demand)] // Invalid attribute target Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "MySecurityAttribute").WithArguments("MySecurityAttribute", "assembly, class, struct, constructor, method").WithLocation(18, 10)); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void ValidSecurityAttributeActionsForAssembly() { string source = @" using System; using System.Security; using System.Security.Permissions; [assembly: MySecurityAttribute(SecurityAction.RequestMinimum)] [assembly: MySecurityAttribute(SecurityAction.RequestOptional)] [assembly: MySecurityAttribute(SecurityAction.RequestRefuse)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } public static void Main() {} } "; CompileAndVerify(source); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7050ERR_SecurityAttributeInvalidActionAssembly() { string source = @" using System.Security; using System.Security.Permissions; [assembly: MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [assembly: MySecurityAttribute(SecurityAction.Assert)] [assembly: MySecurityAttribute(SecurityAction.Demand)] [assembly: MySecurityAttribute(SecurityAction.Deny)] [assembly: MySecurityAttribute(SecurityAction.InheritanceDemand)] [assembly: MySecurityAttribute(SecurityAction.LinkDemand)] [assembly: MySecurityAttribute(SecurityAction.PermitOnly)] [assembly: MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Assert)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Demand)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Deny)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } public static void Main() {} }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (8,32): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: MySecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (16,42): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,32): error CS7050: SecurityAction value '(SecurityAction)1' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "(SecurityAction)1").WithArguments("(SecurityAction)1"), // (6,32): error CS7050: SecurityAction value 'SecurityAction.Assert' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.Assert)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Assert").WithArguments("SecurityAction.Assert"), // (7,32): error CS7050: SecurityAction value 'SecurityAction.Demand' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.Demand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Demand").WithArguments("SecurityAction.Demand"), // (8,32): error CS7050: SecurityAction value 'SecurityAction.Deny' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Deny").WithArguments("SecurityAction.Deny"), // (9,32): error CS7050: SecurityAction value 'SecurityAction.InheritanceDemand' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.InheritanceDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"), // (10,32): error CS7050: SecurityAction value 'SecurityAction.LinkDemand' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.LinkDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand"), // (11,32): error CS7050: SecurityAction value 'SecurityAction.PermitOnly' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.PermitOnly)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.PermitOnly").WithArguments("SecurityAction.PermitOnly"), // (13,42): error CS7050: SecurityAction value '(SecurityAction)1' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "(SecurityAction)1").WithArguments("(SecurityAction)1"), // (14,42): error CS7050: SecurityAction value 'SecurityAction.Assert' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Assert)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Assert").WithArguments("SecurityAction.Assert"), // (15,42): error CS7050: SecurityAction value 'SecurityAction.Demand' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Demand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Demand").WithArguments("SecurityAction.Demand"), // (16,42): error CS7050: SecurityAction value 'SecurityAction.Deny' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Deny").WithArguments("SecurityAction.Deny"), // (17,42): error CS7050: SecurityAction value 'SecurityAction.InheritanceDemand' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"), // (18,42): error CS7050: SecurityAction value 'SecurityAction.LinkDemand' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand"), // (19,42): error CS7050: SecurityAction value 'SecurityAction.PermitOnly' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.PermitOnly").WithArguments("SecurityAction.PermitOnly")); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void ValidSecurityAttributeActionsForTypeOrMethod() { string source = @" using System; using System.Security; using System.Security.Permissions; class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } [MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MySecurityAttribute(SecurityAction.Assert)] [MySecurityAttribute(SecurityAction.Demand)] [MySecurityAttribute(SecurityAction.Deny)] [MySecurityAttribute(SecurityAction.InheritanceDemand)] [MySecurityAttribute(SecurityAction.LinkDemand)] [MySecurityAttribute(SecurityAction.PermitOnly)] [MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MyCodeAccessSecurityAttribute(SecurityAction.Assert)] [MyCodeAccessSecurityAttribute(SecurityAction.Demand)] [MyCodeAccessSecurityAttribute(SecurityAction.Deny)] [MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] class Test { [MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MySecurityAttribute(SecurityAction.Assert)] [MySecurityAttribute(SecurityAction.Demand)] [MySecurityAttribute(SecurityAction.Deny)] [MySecurityAttribute(SecurityAction.InheritanceDemand)] [MySecurityAttribute(SecurityAction.LinkDemand)] [MySecurityAttribute(SecurityAction.PermitOnly)] [MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MyCodeAccessSecurityAttribute(SecurityAction.Assert)] [MyCodeAccessSecurityAttribute(SecurityAction.Demand)] [MyCodeAccessSecurityAttribute(SecurityAction.Deny)] [MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] public static void Main() {} } "; CompileAndVerify(source); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7051ERR_SecurityAttributeInvalidActionTypeOrMethod() { string source = @" using System.Security; using System.Security.Permissions; class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } [MySecurityAttribute(SecurityAction.RequestMinimum)] [MySecurityAttribute(SecurityAction.RequestOptional)] [MySecurityAttribute(SecurityAction.RequestRefuse)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] class Test { [MySecurityAttribute(SecurityAction.RequestMinimum)] [MySecurityAttribute(SecurityAction.RequestOptional)] [MySecurityAttribute(SecurityAction.RequestRefuse)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] public static void Main() {} }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (17,22): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (18,22): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (19,22): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (20,32): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (21,32): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (22,32): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (17,22): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (18,22): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (19,22): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"), // (20,32): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (21,32): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (22,32): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"), // (25,26): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (26,26): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (27,26): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (28,36): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (29,36): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (30,36): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (25,26): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (26,26): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (27,26): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"), // (28,36): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (29,36): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (30,36): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse")); } [WorkItem(546623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546623")] [Fact] public void CS7070ERR_SecurityAttributeInvalidTarget() { string source = @" using System; using System.Security; using System.Security.Permissions; class Program { [MyPermission(SecurityAction.Demand)] public int x = 0; } [AttributeUsage(AttributeTargets.All)] class MyPermissionAttribute : CodeAccessSecurityAttribute { public MyPermissionAttribute(SecurityAction action) : base(action) { } public override IPermission CreatePermission() { return null; } }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (8,6): error CS7070: Security attribute 'MyPermission' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations. // [MyPermission(SecurityAction.Demand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidTarget, "MyPermission").WithArguments("MyPermission")); } [WorkItem(546056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546056")] [Fact] public void TestMissingCodeAccessSecurityAttributeGeneratesNoErrors() { string source = @" namespace System { public enum AttributeTargets { All = 32767, } public class AttributeUsageAttribute : Attribute { public AttributeUsageAttribute(AttributeTargets targets) { } } [AttributeUsage(AttributeTargets.All)] public class MyAttr : Attribute { } [MyAttr()] // error here public class C { } } // following are the minimum code to make Dev11 pass when using /nostdlib option namespace System { public class Object { } public abstract class ValueType { } public class Enum { } public class String { } public struct Byte { } public struct Int16 { } public struct Int32 { } public struct Int64 { } public struct Single { } public struct Double { } public struct Char { } public struct Boolean { } public struct SByte { } public struct UInt16 { } public struct UInt32 { } public struct UInt64 { } public struct IntPtr { } public struct UIntPtr { } public class Delegate { } public class MulticastDelegate : Delegate { } public class Array { } public class Exception { } public class Type { } public struct Void { } public interface IDisposable { void Dispose(); } public class Attribute { } public class ParamArrayAttribute : Attribute { } public struct RuntimeTypeHandle { } public struct RuntimeFieldHandle { } namespace Runtime.InteropServices { public class OutAttribute : Attribute { } } namespace Reflection { public class DefaultMemberAttribute { } } namespace Collections { public interface IEnumerable { } public interface IEnumerator { } } } "; var comp = CreateEmptyCompilation(source); comp.EmitToArray(options: new EmitOptions(runtimeMetadataVersion: "v4.0.31019"), expectedWarnings: new DiagnosticDescription[0]); } #endregion #region Metadata validation tests [Fact] public void CheckSecurityAttributeOnType() { string source = @" using System.Security; using System.Security.Permissions; class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [MySecurityAttribute(SecurityAction.Assert)] public class C { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll, assemblyName: "Test"); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0050" + // length of UTF-8 string "MySecurityAttribute, Test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" + // attr type name "\u0001" + // number of bytes in the encoding of the named arguments "\u0000" // number of named arguments }); }); } [Fact] public void CheckSecurityAttributeOnMethod() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckSecurityAttributeOnLocalFunction() { string source = @" using System.Security.Permissions; namespace N { public class C { void M() { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] static void local1() {} } } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"<M>g__local1|0_0", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckSecurityAttributeOnLambda() { string source = @"using System; using System.Security.Permissions; class Program { static void Main() { Action a = [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] () => { }; } }"; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"<Main>b__0_0", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameType_SameAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1" + // argument value (@"User1") "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameMethod_SameAction() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1" + // argument value (@"User1") "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameType_DifferentAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Assert, Role=@""User2"")] public class C { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameMethod_DifferentAction() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Assert, Role=@""User2"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }); }); } [Fact] public void CheckMultipleSecurityAttributes_DifferentType_SameAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { } } namespace N2 { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C2 { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C2", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_DifferentMethod_SameAction() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo1() {} [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo2() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo1", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo2", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_Assembly_Type_Method() { string source = @" using System.Security.Permissions; [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (4,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestOptional, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u001a" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0015" + // length of UTF-8 string (small enough to fit in 1 byte) "RemotingConfiguration" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0012" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u000d" + // length of UTF-8 string (small enough to fit in 1 byte) "UnmanagedCode" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_Type_Method_UnsafeDll() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.UnsafeReleaseDll); CompileAndVerify(compilation, verify: Verification.Passes, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void GetSecurityAttributes_Type_Method_Assembly() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Assert, Role=@""User2"")] public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Demand, Role=@""User2"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.UnsafeReleaseDll); CompileAndVerify(compilation, verify: Verification.Passes, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1" + // argument value (@"User1") "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }); }); } [WorkItem(545084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545084"), WorkItem(529492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529492")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void PermissionSetAttribute_Fixup() { var tempDir = Temp.CreateDirectory(); var tempFile = tempDir.CreateFile("pset.xml"); string text = @" <PermissionSet class=""System.Security.PermissionSet"" version=""1""> <Permission class=""System.Security.Permissions.FileIOPermission, mscorlib"" version=""1""><AllWindows/></Permission> <Permission class=""System.Security.Permissions.RegistryPermission, mscorlib"" version=""1""><Unrestricted/></Permission> </PermissionSet>"; tempFile.WriteAllText(text); string hexFileContent = PermissionSetAttributeWithFileReference.ConvertToHex(new MemoryStream(Encoding.UTF8.GetBytes(text))); string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""pset.xml"")] public class MyClass { public static void Main() { typeof(MyClass).GetCustomAttributes(false); } }"; var syntaxTree = Parse(source); var resolver = new XmlFileResolver(tempDir.Path); var compilation = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithXmlReferenceResolver(resolver)); compilation.VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"pset.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Deny, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"MyClass", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u007f" + // length of string "System.Security.Permissions.PermissionSetAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0082" + "\u008f" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0003" + // length of string (small enough to fit in 1 byte) "Hex" + // property name "\u0082" + "\u0086" + // length of string hexFileContent // argument value }); }); } [WorkItem(545084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545084"), WorkItem(529492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529492")] [Fact] public void CS7056ERR_PermissionSetAttributeInvalidFile() { string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""NonExistentFile.xml"")] [PermissionSetAttribute(SecurityAction.Deny, File = null)] public class MyClass { }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (4,46): error CS7056: Unable to resolve file path 'NonExistentFile.xml' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, @"File = @""NonExistentFile.xml""").WithArguments("NonExistentFile.xml", "File").WithLocation(4, 46), // (5,46): error CS7056: Unable to resolve file path '<null>' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, "File = null").WithArguments("<null>", "File").WithLocation(5, 46)); } [Fact] public void CS7056ERR_PermissionSetAttributeInvalidFile_WithXmlReferenceResolver() { var tempDir = Temp.CreateDirectory(); var tempFile = tempDir.CreateFile("pset.xml"); string text = @" <PermissionSet class=""System.Security.PermissionSet"" version=""1""> </PermissionSet>"; tempFile.WriteAllText(text); string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""NonExistentFile.xml"")] [PermissionSetAttribute(SecurityAction.Deny, File = null)] public class MyClass { }"; var resolver = new XmlFileResolver(tempDir.Path); CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll.WithXmlReferenceResolver(resolver)).VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (4,46): error CS7056: Unable to resolve file path 'NonExistentFile.xml' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, @"File = @""NonExistentFile.xml""").WithArguments("NonExistentFile.xml", "File").WithLocation(4, 46), // (5,46): error CS7056: Unable to resolve file path '<null>' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, "File = null").WithArguments("<null>", "File").WithLocation(5, 46)); } [WorkItem(545084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545084"), WorkItem(529492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529492")] [Fact] public void CS7057ERR_PermissionSetAttributeFileReadError() { var tempDir = Temp.CreateDirectory(); string filePath = Path.Combine(tempDir.Path, "pset_01.xml"); string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""pset_01.xml"")] public class MyClass { public static void Main() { typeof(MyClass).GetCustomAttributes(false); } }"; var syntaxTree = Parse(source); CSharpCompilation comp; // create file with no file sharing allowed and verify ERR_PermissionSetAttributeFileReadError during emit using (var fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None)) { comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithXmlReferenceResolver(new XmlFileResolver(tempDir.Path))); comp.VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"pset_01.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); using (var output = new MemoryStream()) { var emitResult = comp.Emit(output); Assert.False(emitResult.Success); emitResult.Diagnostics.VerifyErrorCodes( Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr), Diagnostic(ErrorCode.ERR_PermissionSetAttributeFileReadError)); } } // emit succeeds now since we closed the file: using (var output = new MemoryStream()) { var emitResult = comp.Emit(output); Assert.True(emitResult.Success); } } #endregion [Fact] [WorkItem(1034429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1034429")] public void CrashOnParamsInSecurityAttribute() { const string source = @" using System.Security.Permissions; class Program { [A(SecurityAction.Assert)] static void Main() { } } public class A : CodeAccessSecurityAttribute { public A(params SecurityAction a) { } }"; CreateCompilationWithMscorlib46(source).GetDiagnostics(); } [Fact] [WorkItem(1036339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036339")] public void CrashOnOptionalParameterInSecurityAttribute() { const string source = @" using System.Security.Permissions; [A] [A()] class A : CodeAccessSecurityAttribute { public A(SecurityAction a = 0) : base(a) { } }"; CreateCompilationWithMscorlib46(source).VerifyDiagnostics( // (4,2): error CS7049: Security attribute 'A' has an invalid SecurityAction value '0' // [A] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "A").WithArguments("A", "0").WithLocation(4, 2), // (5,2): error CS7049: Security attribute 'A' has an invalid SecurityAction value '0' // [A()] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "A()").WithArguments("A", "0").WithLocation(5, 2), // (6,7): error CS0534: 'A' does not implement inherited abstract member 'SecurityAttribute.CreatePermission()' // class A : CodeAccessSecurityAttribute Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "A").WithArguments("A", "System.Security.Permissions.SecurityAttribute.CreatePermission()").WithLocation(6, 7)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_Security : WellKnownAttributesTestBase { #region Functional Tests [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void HostProtectionSecurityAttribute() { string source = @" [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public struct EventDescriptor { }"; Func<bool, Action<ModuleSymbol>> attributeValidator = isFromSource => (ModuleSymbol module) => { var assembly = module.ContainingAssembly; var type = (Cci.ITypeDefinition)module.GlobalNamespace.GetMember("EventDescriptor").GetCciAdapter(); if (isFromSource) { var sourceAssembly = (SourceAssemblySymbol)assembly; var compilation = sourceAssembly.DeclaringCompilation; Assert.True(type.HasDeclarativeSecurity); IEnumerable<Cci.SecurityAttribute> typeSecurityAttributes = type.SecurityAttributes; // Get System.Security.Permissions.HostProtection var emittedName = MetadataTypeName.FromNamespaceAndTypeName("System.Security.Permissions", "HostProtectionAttribute"); NamedTypeSymbol hostProtectionAttr = sourceAssembly.CorLibrary.LookupTopLevelMetadataType(ref emittedName, true); Assert.NotNull(hostProtectionAttr); // Verify type security attributes Assert.Equal(1, typeSecurityAttributes.Count()); // Verify [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] var securityAttribute = typeSecurityAttributes.First(); Assert.Equal(DeclarativeSecurityAction.LinkDemand, securityAttribute.Action); var typeAttribute = (CSharpAttributeData)securityAttribute.Attribute; Assert.Equal(hostProtectionAttr, typeAttribute.AttributeClass); Assert.Equal(0, typeAttribute.CommonConstructorArguments.Length); typeAttribute.VerifyNamedArgumentValue(0, "MayLeakOnAbort", TypedConstantKind.Primitive, true); } }; CompileAndVerifyWithMscorlib40(source, symbolValidator: attributeValidator(false), sourceSymbolValidator: attributeValidator(true)); } [Fact, WorkItem(544956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544956")] public void SuppressUnmanagedCodeSecurityAttribute() { string source = @" [System.Security.SuppressUnmanagedCodeSecurityAttribute] class Goo { [System.Security.SuppressUnmanagedCodeSecurityAttribute] public static void Main() {} }"; CompileAndVerify(source); } [WorkItem(544929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544929")] [Fact] public void PrincipalPermissionAttribute() { string source = @" using System.Security.Permissions; class Program { [PrincipalPermission((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [PrincipalPermission(SecurityAction.Assert)] [PrincipalPermission(SecurityAction.Demand)] [PrincipalPermission(SecurityAction.Deny)] [PrincipalPermission(SecurityAction.InheritanceDemand)] // CS7052 [PrincipalPermission(SecurityAction.LinkDemand)] // CS7052 [PrincipalPermission(SecurityAction.PermitOnly)] static void Main(string[] args) { } }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (9,26): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PrincipalPermission(SecurityAction.Deny)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (10,26): error CS7052: SecurityAction value 'SecurityAction.InheritanceDemand' is invalid for PrincipalPermission attribute // [PrincipalPermission(SecurityAction.InheritanceDemand)] // CS7052 Diagnostic(ErrorCode.ERR_PrincipalPermissionInvalidAction, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"), // (11,26): error CS7052: SecurityAction value 'SecurityAction.LinkDemand' is invalid for PrincipalPermission attribute // [PrincipalPermission(SecurityAction.LinkDemand)] // CS7052 Diagnostic(ErrorCode.ERR_PrincipalPermissionInvalidAction, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand")); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7048ERR_SecurityAttributeMissingAction() { string source = @" using System.Security; using System.Security.Permissions; class MySecurityAttribute : CodeAccessSecurityAttribute { public bool Field; public bool Prop { get; set; } public override IPermission CreatePermission() { return null; } public MySecurityAttribute() : base(SecurityAction.Assert) { } public MySecurityAttribute(int x, SecurityAction a1) : base(a1) { } } [MySecurityAttribute()] [MySecurityAttribute(Field = true)] [MySecurityAttribute(Field = true, Prop = true)] [MySecurityAttribute(Prop = true)] [MySecurityAttribute(Prop = true, Field = true)] [MySecurityAttribute(x: 0, a1: SecurityAction.Assert)] [MySecurityAttribute(a1: SecurityAction.Assert, x: 0)] public class C {} "; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (15,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute()] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (16,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Field = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (17,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Field = true, Prop = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (18,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Prop = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (19,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Prop = true, Field = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (20,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(x: 0, a1: SecurityAction.Assert)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (21,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(a1: SecurityAction.Assert, x: 0)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute")); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7049ERR_SecurityAttributeInvalidAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission((SecurityAction)0)] // Invalid attribute argument [PrincipalPermission((SecurityAction)11)] // Invalid attribute argument [PrincipalPermission((SecurityAction)(-1))] // Invalid attribute argument [PrincipalPermission()] // Invalid attribute constructor public class C { [PrincipalPermission(SecurityAction.Demand)] // Invalid attribute target public int x; } }"; var compilation = CreateCompilationWithMscorlib40(source); compilation.VerifyDiagnostics( // (9,6): error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'System.Security.Permissions.PrincipalPermissionAttribute.PrincipalPermissionAttribute(System.Security.Permissions.SecurityAction)' // [PrincipalPermission()] // Invalid attribute constructor Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "PrincipalPermission()").WithArguments("action", "System.Security.Permissions.PrincipalPermissionAttribute.PrincipalPermissionAttribute(System.Security.Permissions.SecurityAction)").WithLocation(9, 6), // (6,26): error CS7049: Security attribute 'PrincipalPermission' has an invalid SecurityAction value '(SecurityAction)0' // [PrincipalPermission((SecurityAction)0)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)0").WithArguments("PrincipalPermission", "(SecurityAction)0").WithLocation(6, 26), // (7,26): error CS7049: Security attribute 'PrincipalPermission' has an invalid SecurityAction value '(SecurityAction)11' // [PrincipalPermission((SecurityAction)11)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)11").WithArguments("PrincipalPermission", "(SecurityAction)11").WithLocation(7, 26), // (8,26): error CS7049: Security attribute 'PrincipalPermission' has an invalid SecurityAction value '(SecurityAction)(-1)' // [PrincipalPermission((SecurityAction)(-1))] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)(-1)").WithArguments("PrincipalPermission", "(SecurityAction)(-1)").WithLocation(8, 26), // (12,10): error CS0592: Attribute 'PrincipalPermission' is not valid on this declaration type. It is only valid on 'class, method' declarations. // [PrincipalPermission(SecurityAction.Demand)] // Invalid attribute target Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "PrincipalPermission").WithArguments("PrincipalPermission", "class, method").WithLocation(12, 10)); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7049ERR_SecurityAttributeInvalidAction_02() { string source = @" using System.Security.Permissions; public class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction action): base(action) {} public override System.Security.IPermission CreatePermission() { return null; } } namespace N { [MySecurityAttribute((SecurityAction)0)] // Invalid attribute argument [MySecurityAttribute((SecurityAction)11)] // Invalid attribute argument [MySecurityAttribute((SecurityAction)(-1))] // Invalid attribute argument [MySecurityAttribute()] // Invalid attribute constructor public class C { [MySecurityAttribute(SecurityAction.Demand)] // Invalid attribute target public int x; } }"; var compilation = CreateCompilationWithMscorlib40(source); compilation.VerifyDiagnostics( // (12,26): error CS7049: Security attribute 'MySecurityAttribute' has an invalid SecurityAction value '(SecurityAction)0' // [MySecurityAttribute((SecurityAction)0)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)0").WithArguments("MySecurityAttribute", "(SecurityAction)0").WithLocation(12, 26), // (13,26): error CS7049: Security attribute 'MySecurityAttribute' has an invalid SecurityAction value '(SecurityAction)11' // [MySecurityAttribute((SecurityAction)11)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)11").WithArguments("MySecurityAttribute", "(SecurityAction)11").WithLocation(13, 26), // (14,26): error CS7049: Security attribute 'MySecurityAttribute' has an invalid SecurityAction value '(SecurityAction)(-1)' // [MySecurityAttribute((SecurityAction)(-1))] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)(-1)").WithArguments("MySecurityAttribute", "(SecurityAction)(-1)").WithLocation(14, 26), // (15,6): error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'MySecurityAttribute.MySecurityAttribute(System.Security.Permissions.SecurityAction)' // [MySecurityAttribute()] // Invalid attribute constructor Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "MySecurityAttribute()").WithArguments("action", "MySecurityAttribute.MySecurityAttribute(System.Security.Permissions.SecurityAction)").WithLocation(15, 6), // (18,10): error CS0592: Attribute 'MySecurityAttribute' is not valid on this declaration type. It is only valid on 'assembly, class, struct, constructor, method' declarations. // [MySecurityAttribute(SecurityAction.Demand)] // Invalid attribute target Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "MySecurityAttribute").WithArguments("MySecurityAttribute", "assembly, class, struct, constructor, method").WithLocation(18, 10)); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void ValidSecurityAttributeActionsForAssembly() { string source = @" using System; using System.Security; using System.Security.Permissions; [assembly: MySecurityAttribute(SecurityAction.RequestMinimum)] [assembly: MySecurityAttribute(SecurityAction.RequestOptional)] [assembly: MySecurityAttribute(SecurityAction.RequestRefuse)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } public static void Main() {} } "; CompileAndVerify(source); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7050ERR_SecurityAttributeInvalidActionAssembly() { string source = @" using System.Security; using System.Security.Permissions; [assembly: MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [assembly: MySecurityAttribute(SecurityAction.Assert)] [assembly: MySecurityAttribute(SecurityAction.Demand)] [assembly: MySecurityAttribute(SecurityAction.Deny)] [assembly: MySecurityAttribute(SecurityAction.InheritanceDemand)] [assembly: MySecurityAttribute(SecurityAction.LinkDemand)] [assembly: MySecurityAttribute(SecurityAction.PermitOnly)] [assembly: MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Assert)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Demand)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Deny)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } public static void Main() {} }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (8,32): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: MySecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (16,42): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,32): error CS7050: SecurityAction value '(SecurityAction)1' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "(SecurityAction)1").WithArguments("(SecurityAction)1"), // (6,32): error CS7050: SecurityAction value 'SecurityAction.Assert' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.Assert)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Assert").WithArguments("SecurityAction.Assert"), // (7,32): error CS7050: SecurityAction value 'SecurityAction.Demand' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.Demand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Demand").WithArguments("SecurityAction.Demand"), // (8,32): error CS7050: SecurityAction value 'SecurityAction.Deny' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Deny").WithArguments("SecurityAction.Deny"), // (9,32): error CS7050: SecurityAction value 'SecurityAction.InheritanceDemand' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.InheritanceDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"), // (10,32): error CS7050: SecurityAction value 'SecurityAction.LinkDemand' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.LinkDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand"), // (11,32): error CS7050: SecurityAction value 'SecurityAction.PermitOnly' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.PermitOnly)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.PermitOnly").WithArguments("SecurityAction.PermitOnly"), // (13,42): error CS7050: SecurityAction value '(SecurityAction)1' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "(SecurityAction)1").WithArguments("(SecurityAction)1"), // (14,42): error CS7050: SecurityAction value 'SecurityAction.Assert' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Assert)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Assert").WithArguments("SecurityAction.Assert"), // (15,42): error CS7050: SecurityAction value 'SecurityAction.Demand' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Demand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Demand").WithArguments("SecurityAction.Demand"), // (16,42): error CS7050: SecurityAction value 'SecurityAction.Deny' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Deny").WithArguments("SecurityAction.Deny"), // (17,42): error CS7050: SecurityAction value 'SecurityAction.InheritanceDemand' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"), // (18,42): error CS7050: SecurityAction value 'SecurityAction.LinkDemand' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand"), // (19,42): error CS7050: SecurityAction value 'SecurityAction.PermitOnly' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.PermitOnly").WithArguments("SecurityAction.PermitOnly")); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void ValidSecurityAttributeActionsForTypeOrMethod() { string source = @" using System; using System.Security; using System.Security.Permissions; class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } [MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MySecurityAttribute(SecurityAction.Assert)] [MySecurityAttribute(SecurityAction.Demand)] [MySecurityAttribute(SecurityAction.Deny)] [MySecurityAttribute(SecurityAction.InheritanceDemand)] [MySecurityAttribute(SecurityAction.LinkDemand)] [MySecurityAttribute(SecurityAction.PermitOnly)] [MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MyCodeAccessSecurityAttribute(SecurityAction.Assert)] [MyCodeAccessSecurityAttribute(SecurityAction.Demand)] [MyCodeAccessSecurityAttribute(SecurityAction.Deny)] [MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] class Test { [MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MySecurityAttribute(SecurityAction.Assert)] [MySecurityAttribute(SecurityAction.Demand)] [MySecurityAttribute(SecurityAction.Deny)] [MySecurityAttribute(SecurityAction.InheritanceDemand)] [MySecurityAttribute(SecurityAction.LinkDemand)] [MySecurityAttribute(SecurityAction.PermitOnly)] [MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MyCodeAccessSecurityAttribute(SecurityAction.Assert)] [MyCodeAccessSecurityAttribute(SecurityAction.Demand)] [MyCodeAccessSecurityAttribute(SecurityAction.Deny)] [MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] public static void Main() {} } "; CompileAndVerify(source); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7051ERR_SecurityAttributeInvalidActionTypeOrMethod() { string source = @" using System.Security; using System.Security.Permissions; class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } [MySecurityAttribute(SecurityAction.RequestMinimum)] [MySecurityAttribute(SecurityAction.RequestOptional)] [MySecurityAttribute(SecurityAction.RequestRefuse)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] class Test { [MySecurityAttribute(SecurityAction.RequestMinimum)] [MySecurityAttribute(SecurityAction.RequestOptional)] [MySecurityAttribute(SecurityAction.RequestRefuse)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] public static void Main() {} }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (17,22): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (18,22): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (19,22): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (20,32): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (21,32): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (22,32): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (17,22): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (18,22): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (19,22): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"), // (20,32): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (21,32): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (22,32): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"), // (25,26): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (26,26): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (27,26): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (28,36): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (29,36): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (30,36): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (25,26): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (26,26): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (27,26): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"), // (28,36): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (29,36): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (30,36): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse")); } [WorkItem(546623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546623")] [Fact] public void CS7070ERR_SecurityAttributeInvalidTarget() { string source = @" using System; using System.Security; using System.Security.Permissions; class Program { [MyPermission(SecurityAction.Demand)] public int x = 0; } [AttributeUsage(AttributeTargets.All)] class MyPermissionAttribute : CodeAccessSecurityAttribute { public MyPermissionAttribute(SecurityAction action) : base(action) { } public override IPermission CreatePermission() { return null; } }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (8,6): error CS7070: Security attribute 'MyPermission' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations. // [MyPermission(SecurityAction.Demand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidTarget, "MyPermission").WithArguments("MyPermission")); } [WorkItem(546056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546056")] [Fact] public void TestMissingCodeAccessSecurityAttributeGeneratesNoErrors() { string source = @" namespace System { public enum AttributeTargets { All = 32767, } public class AttributeUsageAttribute : Attribute { public AttributeUsageAttribute(AttributeTargets targets) { } } [AttributeUsage(AttributeTargets.All)] public class MyAttr : Attribute { } [MyAttr()] // error here public class C { } } // following are the minimum code to make Dev11 pass when using /nostdlib option namespace System { public class Object { } public abstract class ValueType { } public class Enum { } public class String { } public struct Byte { } public struct Int16 { } public struct Int32 { } public struct Int64 { } public struct Single { } public struct Double { } public struct Char { } public struct Boolean { } public struct SByte { } public struct UInt16 { } public struct UInt32 { } public struct UInt64 { } public struct IntPtr { } public struct UIntPtr { } public class Delegate { } public class MulticastDelegate : Delegate { } public class Array { } public class Exception { } public class Type { } public struct Void { } public interface IDisposable { void Dispose(); } public class Attribute { } public class ParamArrayAttribute : Attribute { } public struct RuntimeTypeHandle { } public struct RuntimeFieldHandle { } namespace Runtime.InteropServices { public class OutAttribute : Attribute { } } namespace Reflection { public class DefaultMemberAttribute { } } namespace Collections { public interface IEnumerable { } public interface IEnumerator { } } } "; var comp = CreateEmptyCompilation(source); comp.EmitToArray(options: new EmitOptions(runtimeMetadataVersion: "v4.0.31019"), expectedWarnings: new DiagnosticDescription[0]); } #endregion #region Metadata validation tests [Fact] public void CheckSecurityAttributeOnType() { string source = @" using System.Security; using System.Security.Permissions; class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [MySecurityAttribute(SecurityAction.Assert)] public class C { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll, assemblyName: "Test"); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0050" + // length of UTF-8 string "MySecurityAttribute, Test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" + // attr type name "\u0001" + // number of bytes in the encoding of the named arguments "\u0000" // number of named arguments }); }); } [Fact] public void CheckSecurityAttributeOnMethod() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckSecurityAttributeOnLocalFunction() { string source = @" using System.Security.Permissions; namespace N { public class C { void M() { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] static void local1() {} } } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"<M>g__local1|0_0", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckSecurityAttributeOnLambda() { string source = @"using System; using System.Security.Permissions; class Program { static void Main() { Action a = [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] () => { }; } }"; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"<Main>b__0_0", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameType_SameAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1" + // argument value (@"User1") "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameMethod_SameAction() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1" + // argument value (@"User1") "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameType_DifferentAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Assert, Role=@""User2"")] public class C { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameMethod_DifferentAction() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Assert, Role=@""User2"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }); }); } [Fact] public void CheckMultipleSecurityAttributes_DifferentType_SameAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { } } namespace N2 { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C2 { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C2", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_DifferentMethod_SameAction() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo1() {} [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo2() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo1", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo2", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_Assembly_Type_Method() { string source = @" using System.Security.Permissions; [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (4,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestOptional, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u001a" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0015" + // length of UTF-8 string (small enough to fit in 1 byte) "RemotingConfiguration" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0012" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u000d" + // length of UTF-8 string (small enough to fit in 1 byte) "UnmanagedCode" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_Type_Method_UnsafeDll() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.UnsafeReleaseDll); CompileAndVerify(compilation, verify: Verification.Passes, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void GetSecurityAttributes_Type_Method_Assembly() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Assert, Role=@""User2"")] public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Demand, Role=@""User2"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.UnsafeReleaseDll); CompileAndVerify(compilation, verify: Verification.Passes, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1" + // argument value (@"User1") "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }); }); } [WorkItem(545084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545084"), WorkItem(529492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529492")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void PermissionSetAttribute_Fixup() { var tempDir = Temp.CreateDirectory(); var tempFile = tempDir.CreateFile("pset.xml"); string text = @" <PermissionSet class=""System.Security.PermissionSet"" version=""1""> <Permission class=""System.Security.Permissions.FileIOPermission, mscorlib"" version=""1""><AllWindows/></Permission> <Permission class=""System.Security.Permissions.RegistryPermission, mscorlib"" version=""1""><Unrestricted/></Permission> </PermissionSet>"; tempFile.WriteAllText(text); string hexFileContent = PermissionSetAttributeWithFileReference.ConvertToHex(new MemoryStream(Encoding.UTF8.GetBytes(text))); string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""pset.xml"")] public class MyClass { public static void Main() { typeof(MyClass).GetCustomAttributes(false); } }"; var syntaxTree = Parse(source); var resolver = new XmlFileResolver(tempDir.Path); var compilation = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithXmlReferenceResolver(resolver)); compilation.VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"pset.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Deny, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"MyClass", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u007f" + // length of string "System.Security.Permissions.PermissionSetAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0082" + "\u008f" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0003" + // length of string (small enough to fit in 1 byte) "Hex" + // property name "\u0082" + "\u0086" + // length of string hexFileContent // argument value }); }); } [WorkItem(545084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545084"), WorkItem(529492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529492")] [Fact] public void CS7056ERR_PermissionSetAttributeInvalidFile() { string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""NonExistentFile.xml"")] [PermissionSetAttribute(SecurityAction.Deny, File = null)] public class MyClass { }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (4,46): error CS7056: Unable to resolve file path 'NonExistentFile.xml' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, @"File = @""NonExistentFile.xml""").WithArguments("NonExistentFile.xml", "File").WithLocation(4, 46), // (5,46): error CS7056: Unable to resolve file path '<null>' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, "File = null").WithArguments("<null>", "File").WithLocation(5, 46)); } [Fact] public void CS7056ERR_PermissionSetAttributeInvalidFile_WithXmlReferenceResolver() { var tempDir = Temp.CreateDirectory(); var tempFile = tempDir.CreateFile("pset.xml"); string text = @" <PermissionSet class=""System.Security.PermissionSet"" version=""1""> </PermissionSet>"; tempFile.WriteAllText(text); string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""NonExistentFile.xml"")] [PermissionSetAttribute(SecurityAction.Deny, File = null)] public class MyClass { }"; var resolver = new XmlFileResolver(tempDir.Path); CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll.WithXmlReferenceResolver(resolver)).VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (4,46): error CS7056: Unable to resolve file path 'NonExistentFile.xml' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, @"File = @""NonExistentFile.xml""").WithArguments("NonExistentFile.xml", "File").WithLocation(4, 46), // (5,46): error CS7056: Unable to resolve file path '<null>' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, "File = null").WithArguments("<null>", "File").WithLocation(5, 46)); } [WorkItem(545084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545084"), WorkItem(529492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529492")] [Fact] public void CS7057ERR_PermissionSetAttributeFileReadError() { var tempDir = Temp.CreateDirectory(); string filePath = Path.Combine(tempDir.Path, "pset_01.xml"); string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""pset_01.xml"")] public class MyClass { public static void Main() { typeof(MyClass).GetCustomAttributes(false); } }"; var syntaxTree = Parse(source); CSharpCompilation comp; // create file with no file sharing allowed and verify ERR_PermissionSetAttributeFileReadError during emit using (var fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None)) { comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithXmlReferenceResolver(new XmlFileResolver(tempDir.Path))); comp.VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"pset_01.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); using (var output = new MemoryStream()) { var emitResult = comp.Emit(output); Assert.False(emitResult.Success); emitResult.Diagnostics.VerifyErrorCodes( Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr), Diagnostic(ErrorCode.ERR_PermissionSetAttributeFileReadError)); } } // emit succeeds now since we closed the file: using (var output = new MemoryStream()) { var emitResult = comp.Emit(output); Assert.True(emitResult.Success); } } #endregion [Fact] [WorkItem(1034429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1034429")] public void CrashOnParamsInSecurityAttribute() { const string source = @" using System.Security.Permissions; class Program { [A(SecurityAction.Assert)] static void Main() { } } public class A : CodeAccessSecurityAttribute { public A(params SecurityAction a) { } }"; CreateCompilationWithMscorlib46(source).GetDiagnostics(); } [Fact] [WorkItem(1036339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036339")] public void CrashOnOptionalParameterInSecurityAttribute() { const string source = @" using System.Security.Permissions; [A] [A()] class A : CodeAccessSecurityAttribute { public A(SecurityAction a = 0) : base(a) { } }"; CreateCompilationWithMscorlib46(source).VerifyDiagnostics( // (4,2): error CS7049: Security attribute 'A' has an invalid SecurityAction value '0' // [A] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "A").WithArguments("A", "0").WithLocation(4, 2), // (5,2): error CS7049: Security attribute 'A' has an invalid SecurityAction value '0' // [A()] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "A()").WithArguments("A", "0").WithLocation(5, 2), // (6,7): error CS0534: 'A' does not implement inherited abstract member 'SecurityAttribute.CreatePermission()' // class A : CodeAccessSecurityAttribute Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "A").WithArguments("A", "System.Security.Permissions.SecurityAttribute.CreatePermission()").WithLocation(6, 7)); } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Workspaces/Core/Portable/ExtensionManager/IInfoBarService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Extensions { internal interface IInfoBarService : IWorkspaceService { /// <summary> /// Show global info bar /// </summary> void ShowInfoBar(string message, params InfoBarUI[] items); } internal struct InfoBarUI { public readonly string? Title; public readonly UIKind Kind; public readonly Action Action; public readonly bool CloseAfterAction; public InfoBarUI(string title, UIKind kind, Action action, bool closeAfterAction = true) { Contract.ThrowIfNull(title); Title = title; Kind = kind; Action = action; CloseAfterAction = closeAfterAction; } [MemberNotNullWhen(false, nameof(Title))] public bool IsDefault => Title == null; internal enum UIKind { Button, HyperLink, Close } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Extensions { internal interface IInfoBarService : IWorkspaceService { /// <summary> /// Show global info bar /// </summary> void ShowInfoBar(string message, params InfoBarUI[] items); } internal struct InfoBarUI { public readonly string? Title; public readonly UIKind Kind; public readonly Action Action; public readonly bool CloseAfterAction; public InfoBarUI(string title, UIKind kind, Action action, bool closeAfterAction = true) { Contract.ThrowIfNull(title); Title = title; Kind = kind; Action = action; CloseAfterAction = closeAfterAction; } [MemberNotNullWhen(false, nameof(Title))] public bool IsDefault => Title == null; internal enum UIKind { Button, HyperLink, Close } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Features/Core/Portable/QuickInfo/ExportQuickInfoProviderAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; namespace Microsoft.CodeAnalysis.QuickInfo { /// <summary> /// Use this attribute to export a <see cref="QuickInfoProvider"/> so that it will /// be found and used by the per language associated <see cref="QuickInfoService"/>. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal sealed class ExportQuickInfoProviderAttribute : ExportAttribute { public string Name { get; } public string Language { get; } public ExportQuickInfoProviderAttribute(string name, string language) : base(typeof(QuickInfoProvider)) { Name = name ?? throw new ArgumentNullException(nameof(name)); Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; namespace Microsoft.CodeAnalysis.QuickInfo { /// <summary> /// Use this attribute to export a <see cref="QuickInfoProvider"/> so that it will /// be found and used by the per language associated <see cref="QuickInfoService"/>. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal sealed class ExportQuickInfoProviderAttribute : ExportAttribute { public string Name { get; } public string Language { get; } public ExportQuickInfoProviderAttribute(string name, string language) : base(typeof(QuickInfoProvider)) { Name = name ?? throw new ArgumentNullException(nameof(name)); Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/VisualStudio/Core/Impl/Options/Style/NamingPreferences/NamingStyles/NamingStyleViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences { internal class NamingStyleViewModel : AbstractNotifyPropertyChanged, INamingStylesInfoDialogViewModel { private readonly MutableNamingStyle _style; private readonly INotificationService _notificationService; public NamingStyleViewModel(MutableNamingStyle style, bool canBeDeleted, INotificationService notificationService) { _notificationService = notificationService; _style = style; ID = style.ID; RequiredPrefix = style.Prefix; RequiredSuffix = style.Suffix; WordSeparator = style.WordSeparator; ItemName = style.Name; CanBeDeleted = canBeDeleted; CapitalizationSchemes = new List<CapitalizationDisplay> { new CapitalizationDisplay(Capitalization.PascalCase, ServicesVSResources.Pascal_Case_Name), new CapitalizationDisplay(Capitalization.CamelCase, ServicesVSResources.camel_Case_Name), new CapitalizationDisplay(Capitalization.FirstUpper, ServicesVSResources.First_word_upper), new CapitalizationDisplay(Capitalization.AllUpper, ServicesVSResources.ALL_UPPER), new CapitalizationDisplay(Capitalization.AllLower, ServicesVSResources.all_lower) }; CapitalizationSchemeIndex = CapitalizationSchemes.IndexOf(CapitalizationSchemes.Single(s => s.Capitalization == style.CapitalizationScheme)); } public IList<CapitalizationDisplay> CapitalizationSchemes { get; set; } private int _capitalizationSchemeIndex; public int CapitalizationSchemeIndex { get { return _capitalizationSchemeIndex; } set { _style.CapitalizationScheme = CapitalizationSchemes[value].Capitalization; if (SetProperty(ref _capitalizationSchemeIndex, value)) { NotifyPropertyChanged(nameof(CurrentConfiguration)); } } } public Guid ID { get; } private string _itemName; public string ItemName { get { return _itemName; } set { SetProperty(ref _itemName, value); } } public string CurrentConfiguration { get { return _style.NamingStyle.CreateName(ImmutableArray.Create(ServicesVSResources.example, ServicesVSResources.identifier)); } set { } } private string _requiredPrefix; public string RequiredPrefix { get { return _requiredPrefix; } set { _style.Prefix = value; if (SetProperty(ref _requiredPrefix, value)) { NotifyPropertyChanged(nameof(CurrentConfiguration)); } } } private string _requiredSuffix; public string RequiredSuffix { get { return _requiredSuffix; } set { _style.Suffix = value; if (SetProperty(ref _requiredSuffix, value)) { NotifyPropertyChanged(nameof(CurrentConfiguration)); } } } private string _wordSeparator; public string WordSeparator { get { return _wordSeparator; } set { _style.WordSeparator = value; if (SetProperty(ref _wordSeparator, value)) { NotifyPropertyChanged(nameof(CurrentConfiguration)); } } } public bool CanBeDeleted { get; set; } internal bool TrySubmit() { if (string.IsNullOrWhiteSpace(ItemName)) { _notificationService.SendNotification(ServicesVSResources.Enter_a_title_for_this_Naming_Style); return false; } return true; } internal MutableNamingStyle GetNamingStyle() { _style.Name = ItemName; return _style; } // For screen readers public override string ToString() => ItemName; public class CapitalizationDisplay { public Capitalization Capitalization { get; set; } public string Name { get; set; } public CapitalizationDisplay(Capitalization capitalization, string name) { Capitalization = capitalization; Name = name; } // For screen readers public override string ToString() => Name; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences { internal class NamingStyleViewModel : AbstractNotifyPropertyChanged, INamingStylesInfoDialogViewModel { private readonly MutableNamingStyle _style; private readonly INotificationService _notificationService; public NamingStyleViewModel(MutableNamingStyle style, bool canBeDeleted, INotificationService notificationService) { _notificationService = notificationService; _style = style; ID = style.ID; RequiredPrefix = style.Prefix; RequiredSuffix = style.Suffix; WordSeparator = style.WordSeparator; ItemName = style.Name; CanBeDeleted = canBeDeleted; CapitalizationSchemes = new List<CapitalizationDisplay> { new CapitalizationDisplay(Capitalization.PascalCase, ServicesVSResources.Pascal_Case_Name), new CapitalizationDisplay(Capitalization.CamelCase, ServicesVSResources.camel_Case_Name), new CapitalizationDisplay(Capitalization.FirstUpper, ServicesVSResources.First_word_upper), new CapitalizationDisplay(Capitalization.AllUpper, ServicesVSResources.ALL_UPPER), new CapitalizationDisplay(Capitalization.AllLower, ServicesVSResources.all_lower) }; CapitalizationSchemeIndex = CapitalizationSchemes.IndexOf(CapitalizationSchemes.Single(s => s.Capitalization == style.CapitalizationScheme)); } public IList<CapitalizationDisplay> CapitalizationSchemes { get; set; } private int _capitalizationSchemeIndex; public int CapitalizationSchemeIndex { get { return _capitalizationSchemeIndex; } set { _style.CapitalizationScheme = CapitalizationSchemes[value].Capitalization; if (SetProperty(ref _capitalizationSchemeIndex, value)) { NotifyPropertyChanged(nameof(CurrentConfiguration)); } } } public Guid ID { get; } private string _itemName; public string ItemName { get { return _itemName; } set { SetProperty(ref _itemName, value); } } public string CurrentConfiguration { get { return _style.NamingStyle.CreateName(ImmutableArray.Create(ServicesVSResources.example, ServicesVSResources.identifier)); } set { } } private string _requiredPrefix; public string RequiredPrefix { get { return _requiredPrefix; } set { _style.Prefix = value; if (SetProperty(ref _requiredPrefix, value)) { NotifyPropertyChanged(nameof(CurrentConfiguration)); } } } private string _requiredSuffix; public string RequiredSuffix { get { return _requiredSuffix; } set { _style.Suffix = value; if (SetProperty(ref _requiredSuffix, value)) { NotifyPropertyChanged(nameof(CurrentConfiguration)); } } } private string _wordSeparator; public string WordSeparator { get { return _wordSeparator; } set { _style.WordSeparator = value; if (SetProperty(ref _wordSeparator, value)) { NotifyPropertyChanged(nameof(CurrentConfiguration)); } } } public bool CanBeDeleted { get; set; } internal bool TrySubmit() { if (string.IsNullOrWhiteSpace(ItemName)) { _notificationService.SendNotification(ServicesVSResources.Enter_a_title_for_this_Naming_Style); return false; } return true; } internal MutableNamingStyle GetNamingStyle() { _style.Name = ItemName; return _style; } // For screen readers public override string ToString() => ItemName; public class CapitalizationDisplay { public Capitalization Capitalization { get; set; } public string Name { get; set; } public CapitalizationDisplay(Capitalization capitalization, string name) { Capitalization = capitalization; Name = name; } // For screen readers public override string ToString() => Name; } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Compilers/Test/Resources/Core/SymbolsTests/Versioning/AR_SA.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. [assembly: System.Reflection.AssemblyCultureAttribute("ar-SA")] public class arSA { }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. [assembly: System.Reflection.AssemblyCultureAttribute("ar-SA")] public class arSA { }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/EditorFeatures/TestUtilities/AutomaticCompletion/AbstractAutomaticBraceCompletionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.BraceCompletion; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion { [UseExportProvider] public abstract class AbstractAutomaticBraceCompletionTests { internal static void CheckStart(IBraceCompletionSession session, bool expectValidSession = true) { Type(session, session.OpeningBrace.ToString()); session.Start(); if (expectValidSession) { var closingPoint = session.ClosingPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot).Subtract(1); Assert.Equal(closingPoint.GetChar(), session.ClosingBrace); } else { Assert.Null(session.OpeningPoint); Assert.Null(session.ClosingPoint); } } internal static void CheckBackspace(IBraceCompletionSession session) { session.TextView.TryMoveCaretToAndEnsureVisible(session.OpeningPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot).Add(1)); session.PreBackspace(out var handled); if (!handled) { session.PostBackspace(); } Assert.Null(session.OpeningPoint); Assert.Null(session.ClosingPoint); } internal static void CheckTab(IBraceCompletionSession session, bool allowTab = true) { session.PreTab(out var handled); if (!handled) { session.PostTab(); } var caret = session.TextView.GetCaretPoint(session.SubjectBuffer).Value; if (allowTab) { Assert.Equal(session.ClosingPoint.GetPosition(session.SubjectBuffer.CurrentSnapshot), caret.Position); } else { Assert.True(caret.Position < session.ClosingPoint.GetPosition(session.SubjectBuffer.CurrentSnapshot)); } } internal static void CheckReturn(IBraceCompletionSession session, int indentation, string result = null) { session.PreReturn(out var handled); Type(session, Environment.NewLine); if (!handled) { session.PostReturn(); } var virtualCaret = session.TextView.GetVirtualCaretPoint(session.SubjectBuffer).Value; Assert.True(indentation == virtualCaret.VirtualSpaces, $"Expected indentation was {indentation}, but the actual indentation was {virtualCaret.VirtualSpaces}"); if (result != null) { AssertEx.EqualOrDiff(result, session.SubjectBuffer.CurrentSnapshot.GetText()); } } internal static void CheckText(IBraceCompletionSession session, string result) => Assert.Equal(result, session.SubjectBuffer.CurrentSnapshot.GetText()); internal static void CheckReturnOnNonEmptyLine(IBraceCompletionSession session, int expectedVirtualSpace) { session.PreReturn(out var handled); Type(session, Environment.NewLine); if (!handled) { session.PostReturn(); } var virtualCaret = session.TextView.GetVirtualCaretPoint(session.SubjectBuffer).Value; Assert.Equal(expectedVirtualSpace, virtualCaret.VirtualSpaces); } internal static void CheckOverType(IBraceCompletionSession session, bool allowOverType = true) { var preClosingPoint = session.ClosingPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot); Assert.Equal(session.ClosingBrace, preClosingPoint.Subtract(1).GetChar()); session.PreOverType(out var handled); if (!handled) { session.PostOverType(); } var postClosingPoint = session.ClosingPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot); Assert.Equal(postClosingPoint.Subtract(1).GetChar(), session.ClosingBrace); var caret = session.TextView.GetCaretPoint(session.SubjectBuffer).Value; if (allowOverType) { Assert.Equal(postClosingPoint.Position, caret.Position); } else { Assert.True(caret.Position < postClosingPoint.Position); } } internal static void Type(IBraceCompletionSession session, string text) { var buffer = session.SubjectBuffer; var caret = session.TextView.GetCaretPoint(buffer).Value; using (var edit = buffer.CreateEdit()) { edit.Insert(caret.Position, text); edit.Apply(); } } internal static Holder CreateSession(TestWorkspace workspace, char opening, char closing, Dictionary<OptionKey2, object> changedOptionSet = null) { if (changedOptionSet != null) { var options = workspace.Options; foreach (var entry in changedOptionSet) { options = options.WithChangedOption(entry.Key, entry.Value); } workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options)); } var document = workspace.Documents.First(); var provider = Assert.IsType<BraceCompletionSessionProvider>(workspace.ExportProvider.GetExportedValue<IBraceCompletionSessionProvider>()); var openingPoint = new SnapshotPoint(document.GetTextBuffer().CurrentSnapshot, document.CursorPosition.Value); if (provider.TryCreateSession(document.GetTextView(), openingPoint, opening, closing, out var session)) { return new Holder(workspace, session); } workspace.Dispose(); return null; } internal class Holder : IDisposable { public TestWorkspace Workspace { get; } public IBraceCompletionSession Session { get; } public Holder(TestWorkspace workspace, IBraceCompletionSession session) { this.Workspace = workspace; this.Session = session; } public void Dispose() => this.Workspace.Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.BraceCompletion; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion { [UseExportProvider] public abstract class AbstractAutomaticBraceCompletionTests { internal static void CheckStart(IBraceCompletionSession session, bool expectValidSession = true) { Type(session, session.OpeningBrace.ToString()); session.Start(); if (expectValidSession) { var closingPoint = session.ClosingPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot).Subtract(1); Assert.Equal(closingPoint.GetChar(), session.ClosingBrace); } else { Assert.Null(session.OpeningPoint); Assert.Null(session.ClosingPoint); } } internal static void CheckBackspace(IBraceCompletionSession session) { session.TextView.TryMoveCaretToAndEnsureVisible(session.OpeningPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot).Add(1)); session.PreBackspace(out var handled); if (!handled) { session.PostBackspace(); } Assert.Null(session.OpeningPoint); Assert.Null(session.ClosingPoint); } internal static void CheckTab(IBraceCompletionSession session, bool allowTab = true) { session.PreTab(out var handled); if (!handled) { session.PostTab(); } var caret = session.TextView.GetCaretPoint(session.SubjectBuffer).Value; if (allowTab) { Assert.Equal(session.ClosingPoint.GetPosition(session.SubjectBuffer.CurrentSnapshot), caret.Position); } else { Assert.True(caret.Position < session.ClosingPoint.GetPosition(session.SubjectBuffer.CurrentSnapshot)); } } internal static void CheckReturn(IBraceCompletionSession session, int indentation, string result = null) { session.PreReturn(out var handled); Type(session, Environment.NewLine); if (!handled) { session.PostReturn(); } var virtualCaret = session.TextView.GetVirtualCaretPoint(session.SubjectBuffer).Value; Assert.True(indentation == virtualCaret.VirtualSpaces, $"Expected indentation was {indentation}, but the actual indentation was {virtualCaret.VirtualSpaces}"); if (result != null) { AssertEx.EqualOrDiff(result, session.SubjectBuffer.CurrentSnapshot.GetText()); } } internal static void CheckText(IBraceCompletionSession session, string result) => Assert.Equal(result, session.SubjectBuffer.CurrentSnapshot.GetText()); internal static void CheckReturnOnNonEmptyLine(IBraceCompletionSession session, int expectedVirtualSpace) { session.PreReturn(out var handled); Type(session, Environment.NewLine); if (!handled) { session.PostReturn(); } var virtualCaret = session.TextView.GetVirtualCaretPoint(session.SubjectBuffer).Value; Assert.Equal(expectedVirtualSpace, virtualCaret.VirtualSpaces); } internal static void CheckOverType(IBraceCompletionSession session, bool allowOverType = true) { var preClosingPoint = session.ClosingPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot); Assert.Equal(session.ClosingBrace, preClosingPoint.Subtract(1).GetChar()); session.PreOverType(out var handled); if (!handled) { session.PostOverType(); } var postClosingPoint = session.ClosingPoint.GetPoint(session.SubjectBuffer.CurrentSnapshot); Assert.Equal(postClosingPoint.Subtract(1).GetChar(), session.ClosingBrace); var caret = session.TextView.GetCaretPoint(session.SubjectBuffer).Value; if (allowOverType) { Assert.Equal(postClosingPoint.Position, caret.Position); } else { Assert.True(caret.Position < postClosingPoint.Position); } } internal static void Type(IBraceCompletionSession session, string text) { var buffer = session.SubjectBuffer; var caret = session.TextView.GetCaretPoint(buffer).Value; using (var edit = buffer.CreateEdit()) { edit.Insert(caret.Position, text); edit.Apply(); } } internal static Holder CreateSession(TestWorkspace workspace, char opening, char closing, Dictionary<OptionKey2, object> changedOptionSet = null) { if (changedOptionSet != null) { var options = workspace.Options; foreach (var entry in changedOptionSet) { options = options.WithChangedOption(entry.Key, entry.Value); } workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options)); } var document = workspace.Documents.First(); var provider = Assert.IsType<BraceCompletionSessionProvider>(workspace.ExportProvider.GetExportedValue<IBraceCompletionSessionProvider>()); var openingPoint = new SnapshotPoint(document.GetTextBuffer().CurrentSnapshot, document.CursorPosition.Value); if (provider.TryCreateSession(document.GetTextView(), openingPoint, opening, closing, out var session)) { return new Holder(workspace, session); } workspace.Dispose(); return null; } internal class Holder : IDisposable { public TestWorkspace Workspace { get; } public IBraceCompletionSession Session { get; } public Holder(TestWorkspace workspace, IBraceCompletionSession session) { this.Workspace = workspace; this.Session = session; } public void Dispose() => this.Workspace.Dispose(); } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Compilers/CSharp/Test/Symbol/BadSymbolReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class BadSymbolReference : CSharpTestBase { //CreateCompilationWithMscorlib(text).VerifyDiagnostics( // // (6,17): error CS0023: Operator '.' cannot be applied to operand of type '<null>' // Diagnostic(ErrorCode.ERR_BadUnaryOp, @"null.Length").WithArguments(".", "<null>")); [Fact] public void MissingTypes1() { var cl2 = TestReferences.SymbolsTests.MissingTypes.CL2; var cl3 = TestReferences.SymbolsTests.MissingTypes.CL3; var compilation1 = CreateCompilation( @" class Module1 { void Main() { CL3_C1 x1; x1 = null; } }", new MetadataReference[] { cl2, cl3 }); var a_cs = @" class Module1 { private CL3_C1 f1; void Main() { CL3_C1 x1; x1 = null; } void Test1() { CL3_C3 x2; x2 = null; } void Test2() { System.Action<CL3_C3> x3; x3 = null; } void Test3() { CL3_C1.Test1(); } void Test4() { global::CL3_C1.Test1(); } void Test5() { C1<CL3_C1>.Test1(); } void Test6() { global::C1<CL3_C1>.Test1(); } void Test7() { object x1; x1 = new CL3_C1(); } void Test8() { CL3_C3[] x4; x4 = null; } void Test9() { object x4; x4 = new CL3_C3[] {}; } void Test10() { C1<CL3_C1> x5; x5 = null; } void Test11() { object x5; x5 = new C1<CL3_C1>(); } void Test() { var v = new CL3_C4(); } void Test12() { var w = new CL3_C5(); } void Test13() { CL3_C2 y = null; object z = y.x; } void Test15() { CL3_C2 y = null; object z; z = y.u; } void Test16() { CL3_C2 y = null; object z; z = y.y; } void Test17() { CL3_C2 y = null; object z; z = y.z; } void Test18() { CL3_C2 y=null; object z; z = y.v; } void Test19() { object z; z = f1; } class C2 : CL3_C1 { } class C3 : System.Collections.Generic.List<CL3_C1> { } class C4 : CL3_S1 { } interface I2 : CL3_I1, I1<CL3_I1> {} class C5 : CL3_I1, I1<CL3_I1> {} void Test20() { CL3_S1? x6; x6 = null; } void Test21() { CL3_C2.Test1(); } void Test22() { CL3_C2.Test1(1); } void Test23() { CL3_C2.Test3(); } void Test24() { CL3_C2.Test4(); } void Test24_1() { CL3_C2.Test4(null); } void Test25() { CL3_C2 y = null; y.Test1(); } void Test26() { CL3_C2 y = null; y.Test1(1); } void Test27() { CL3_C2 y = null; y.Test2(2); } void Test28() { CL3_C2 y = null; CL3_D1 d1 = y.Test2; } void Test29() { CL3_C2 y = null; y.v(null); } void Test30() { CL3_C2 y = null; y.w(null); } void Test31() { CL3_D1 u = (uuu) => System.Console.WriteLine(); } void Test32() { CL3_C2 y = null; object zz = y.P2; } } class C1<T> { public static void Test1() { } } interface I1<T> {} "; DiagnosticDescription[] errors = { // (140,11): error CS0012: The type 'CL2_I1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C5 : CL3_I1, I1<CL3_I1> Diagnostic(ErrorCode.ERR_NoTypeDef, "C5").WithArguments("CL2_I1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(140, 11), // (125,16): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C2 : CL3_C1 Diagnostic(ErrorCode.ERR_NoTypeDef, "CL3_C1").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(125, 16), // (133,16): error CS0509: 'Module1.C4': cannot derive from sealed type 'CL3_S1' // class C4 : CL3_S1 Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "CL3_S1").WithArguments("Module1.C4", "CL3_S1").WithLocation(133, 16), // (137,15): error CS0012: The type 'CL2_I1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // interface I2 : CL3_I1, I1<CL3_I1> Diagnostic(ErrorCode.ERR_NoTypeDef, "I2").WithArguments("CL2_I1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(137, 15), // (9,16): warning CS0219: The variable 'x1' is assigned but its value is never used // CL3_C1 x1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(9, 16), // (15,16): warning CS0219: The variable 'x2' is assigned but its value is never used // CL3_C3 x2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(15, 16), // (21,31): warning CS0219: The variable 'x3' is assigned but its value is never used // System.Action<CL3_C3> x3; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(21, 31), // (27,16): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CL3_C1.Test1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "Test1").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(27, 16), // (32,24): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // global::CL3_C1.Test1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "Test1").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(32, 24), // (53,18): warning CS0219: The variable 'x4' is assigned but its value is never used // CL3_C3[] x4; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x4").WithArguments("x4").WithLocation(53, 18), // (65,20): warning CS0219: The variable 'x5' is assigned but its value is never used // C1<CL3_C1> x5; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(65, 20), // (88,22): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // object z = y.x; Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(88, 22), // (145,17): warning CS0219: The variable 'x6' is assigned but its value is never used // CL3_S1? x6; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(145, 17), // (151,9): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CL3_C2.Test1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "CL3_C2.Test1").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(151, 9), // (156,9): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CL3_C2.Test1(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "CL3_C2.Test1").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(156, 9), // (156,9): error CS0120: An object reference is required for the non-static field, method, or property 'CL3_C2.Test1(int)' // CL3_C2.Test1(1); Diagnostic(ErrorCode.ERR_ObjectRequired, "CL3_C2.Test1").WithArguments("CL3_C2.Test1(int)").WithLocation(156, 9), // (161,9): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CL3_C2.Test3(); Diagnostic(ErrorCode.ERR_NoTypeDef, "CL3_C2.Test3").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(161, 9), // (166,16): error CS1501: No overload for method 'Test4' takes 0 arguments // CL3_C2.Test4(); Diagnostic(ErrorCode.ERR_BadArgCount, "Test4").WithArguments("Test4", "0").WithLocation(166, 16), // (171,9): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CL3_C2.Test4(null); Diagnostic(ErrorCode.ERR_NoTypeDef, "CL3_C2.Test4").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(171, 9), // (171,16): error CS0121: The call is ambiguous between the following methods or properties: 'CL3_C2.Test4(CL3_C1)' and 'CL3_C2.Test4(CL3_C3)' // CL3_C2.Test4(null); Diagnostic(ErrorCode.ERR_AmbigCall, "Test4").WithArguments("CL3_C2.Test4(CL3_C1)", "CL3_C2.Test4(CL3_C3)").WithLocation(171, 16), // (177,9): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // y.Test1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "y.Test1").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(177, 9), // (195,23): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CL3_D1 d1 = y.Test2; Diagnostic(ErrorCode.ERR_NoTypeDef, "Test2").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(195, 23), // (207,9): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // y.w(null); Diagnostic(ErrorCode.ERR_NoTypeDef, "y.w(null)").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(207, 9), // (212,20): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CL3_D1 u = (uuu) => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NoTypeDef, "(uuu) => System.Console.WriteLine()").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(212, 20), // (5,20): warning CS0649: Field 'Module1.f1' is never assigned to, and will always have its default value null // private CL3_C1 f1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "f1").WithArguments("Module1.f1", "null").WithLocation(5, 20) }; var compilation2 = CreateCompilation(a_cs, new MetadataReference[] { cl3 }); compilation2.VerifyDiagnostics(errors); string cl3Source = @" public class CL3_C1 : CL2_C1 { public static object Test1() { return null; } public static CL2_C1 Test2() { return null; } public CL2_C1 Test3() { return null; } } public class CL3_C2 { public static CL2_C1 Test1() { return null; } public CL2_C1 x; public void Test1(int x) { } public void Test2(int x) { } public static CL2_C1 Test3() { return null; } public static void Test4(CL3_C1 x) { } public static void Test4(CL3_C3 x) { } public CL3_C3 y; public CL3_C4 z; public CL3_C5[] u; public System.Action<CL3_C5> v; public CL3_D1 w; public static CL3_C2 Test5() { return null; } public CL3_C1 P2 { get { return null; } set { } } } public class CL3_C3 : CL2_I1, CL2_I2 { } public class CL3_C4 : CL3_C1 {} public class CL3_C5 : CL3_C3 {} public delegate void CL3_D1(CL2_C1 x); public struct CL3_S1: CL2_I1 {} public interface CL3_I1 : CL2_I1 {} "; var cl3Compilation = CreateCompilation(cl3Source, new MetadataReference[] { cl2 }); cl3Compilation.VerifyDiagnostics(); var compilation3 = CreateCompilation(a_cs, new MetadataReference[] { new CSharpCompilationReference(cl3Compilation) }); compilation3.VerifyDiagnostics(errors); var cl3BadCompilation1 = CreateCompilation(cl3Source, new MetadataReference[] { cl3 }); var compilation4 = CreateCompilation(a_cs, new MetadataReference[] { new CSharpCompilationReference(cl3BadCompilation1) }); DiagnosticDescription[] errors2 = { // (140,11): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // class C5 : CL3_I1, I1<CL3_I1> Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C5").WithArguments("CL2_I1").WithLocation(140, 11), // (125,16): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // class C2 : CL3_C1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL3_C1").WithArguments("CL2_C1").WithLocation(125, 16), // (133,16): error CS0509: 'Module1.C4': cannot derive from sealed type 'CL3_S1' // class C4 : CL3_S1 Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "CL3_S1").WithArguments("Module1.C4", "CL3_S1").WithLocation(133, 16), // (137,15): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // interface I2 : CL3_I1, I1<CL3_I1> Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("CL2_I1").WithLocation(137, 15), // (9,16): warning CS0219: The variable 'x1' is assigned but its value is never used // CL3_C1 x1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(9, 16), // (15,16): warning CS0219: The variable 'x2' is assigned but its value is never used // CL3_C3 x2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(15, 16), // (21,31): warning CS0219: The variable 'x3' is assigned but its value is never used // System.Action<CL3_C3> x3; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(21, 31), // (27,16): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // CL3_C1.Test1(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Test1").WithArguments("CL2_C1").WithLocation(27, 16), // (32,24): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // global::CL3_C1.Test1(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Test1").WithArguments("CL2_C1").WithLocation(32, 24), // (53,18): warning CS0219: The variable 'x4' is assigned but its value is never used // CL3_C3[] x4; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x4").WithArguments("x4").WithLocation(53, 18), // (65,20): warning CS0219: The variable 'x5' is assigned but its value is never used // C1<CL3_C1> x5; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(65, 20), // (88,22): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // object z = y.x; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("CL2_C1").WithLocation(88, 22), // (145,17): warning CS0219: The variable 'x6' is assigned but its value is never used // CL3_S1? x6; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(145, 17), // (151,9): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // CL3_C2.Test1(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL3_C2.Test1").WithArguments("CL2_C1").WithLocation(151, 9), // (156,9): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // CL3_C2.Test1(1); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL3_C2.Test1").WithArguments("CL2_C1").WithLocation(156, 9), // (156,9): error CS0120: An object reference is required for the non-static field, method, or property 'CL3_C2.Test1(int)' // CL3_C2.Test1(1); Diagnostic(ErrorCode.ERR_ObjectRequired, "CL3_C2.Test1").WithArguments("CL3_C2.Test1(int)").WithLocation(156, 9), // (161,9): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // CL3_C2.Test3(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL3_C2.Test3").WithArguments("CL2_C1").WithLocation(161, 9), // (166,16): error CS1501: No overload for method 'Test4' takes 0 arguments // CL3_C2.Test4(); Diagnostic(ErrorCode.ERR_BadArgCount, "Test4").WithArguments("Test4", "0").WithLocation(166, 16), // (171,9): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // CL3_C2.Test4(null); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL3_C2.Test4").WithArguments("CL2_C1").WithLocation(171, 9), // (171,9): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // CL3_C2.Test4(null); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL3_C2.Test4").WithArguments("CL2_I1").WithLocation(171, 9), // (171,16): error CS0121: The call is ambiguous between the following methods or properties: 'CL3_C2.Test4(CL3_C1)' and 'CL3_C2.Test4(CL3_C3)' // CL3_C2.Test4(null); Diagnostic(ErrorCode.ERR_AmbigCall, "Test4").WithArguments("CL3_C2.Test4(CL3_C1)", "CL3_C2.Test4(CL3_C3)").WithLocation(171, 16), // (177,9): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // y.Test1(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "y.Test1").WithArguments("CL2_C1").WithLocation(177, 9), // (195,23): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // CL3_D1 d1 = y.Test2; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Test2").WithArguments("CL2_C1").WithLocation(195, 23), // (207,9): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // y.w(null); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "y.w(null)").WithArguments("CL2_C1").WithLocation(207, 9), // (212,20): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // CL3_D1 u = (uuu) => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "(uuu) => System.Console.WriteLine()").WithArguments("CL2_C1").WithLocation(212, 20), // (5,20): warning CS0649: Field 'Module1.f1' is never assigned to, and will always have its default value null // private CL3_C1 f1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "f1").WithArguments("Module1.f1", "null").WithLocation(5, 20) }; compilation4.VerifyDiagnostics(errors2); var cl3BadCompilation2 = CreateCompilation(cl3Source); DiagnosticDescription[] errors3 = { // (2,23): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public class CL3_C1 : CL2_C1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1"), // (9,19): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public static CL2_C1 Test2() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1"), // (14,12): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public CL2_C1 Test3() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1"), // (22,19): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public static CL2_C1 Test1() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1"), // (37,19): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public static CL2_C1 Test3() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1"), // (27,12): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public CL2_C1 x; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1"), // (76,23): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // public class CL3_C3 : CL2_I1, CL2_I2 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I1").WithArguments("CL2_I1"), // (76,31): error CS0246: The type or namespace name 'CL2_I2' could not be found (are you missing a using directive or an assembly reference?) // public class CL3_C3 : CL2_I1, CL2_I2 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I2").WithArguments("CL2_I2"), // (87,29): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public delegate void CL3_D1(CL2_C1 x); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1"), // (89,23): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // public struct CL3_S1: CL2_I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I1").WithArguments("CL2_I1"), // (92,27): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // public interface CL3_I1 : CL2_I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I1").WithArguments("CL2_I1") }; cl3BadCompilation2.VerifyDiagnostics(errors3); var compilation5 = CreateCompilation(a_cs, new MetadataReference[] { new CSharpCompilationReference(cl3BadCompilation2) }); DiagnosticDescription[] errors5 = { // (133,16): error CS0509: 'Module1.C4': cannot derive from sealed type 'CL3_S1' // class C4 : CL3_S1 Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "CL3_S1").WithArguments("Module1.C4", "CL3_S1").WithLocation(133, 16), // (9,16): warning CS0219: The variable 'x1' is assigned but its value is never used // CL3_C1 x1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(9, 16), // (15,16): warning CS0219: The variable 'x2' is assigned but its value is never used // CL3_C3 x2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(15, 16), // (21,31): warning CS0219: The variable 'x3' is assigned but its value is never used // System.Action<CL3_C3> x3; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(21, 31), // (53,18): warning CS0219: The variable 'x4' is assigned but its value is never used // CL3_C3[] x4; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x4").WithArguments("x4").WithLocation(53, 18), // (65,20): warning CS0219: The variable 'x5' is assigned but its value is never used // C1<CL3_C1> x5; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(65, 20), // (145,17): warning CS0219: The variable 'x6' is assigned but its value is never used // CL3_S1? x6; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(145, 17), // (156,9): error CS0120: An object reference is required for the non-static field, method, or property 'CL3_C2.Test1(int)' // CL3_C2.Test1(1); Diagnostic(ErrorCode.ERR_ObjectRequired, "CL3_C2.Test1").WithArguments("CL3_C2.Test1(int)").WithLocation(156, 9), // (166,16): error CS1501: No overload for method 'Test4' takes 0 arguments // CL3_C2.Test4(); Diagnostic(ErrorCode.ERR_BadArgCount, "Test4").WithArguments("Test4", "0").WithLocation(166, 16), // (171,16): error CS0121: The call is ambiguous between the following methods or properties: 'CL3_C2.Test4(CL3_C1)' and 'CL3_C2.Test4(CL3_C3)' // CL3_C2.Test4(null); Diagnostic(ErrorCode.ERR_AmbigCall, "Test4").WithArguments("CL3_C2.Test4(CL3_C1)", "CL3_C2.Test4(CL3_C3)").WithLocation(171, 16), // (177,9): error CS0176: Member 'CL3_C2.Test1()' cannot be accessed with an instance reference; qualify it with a type name instead // y.Test1(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "y.Test1").WithArguments("CL3_C2.Test1()").WithLocation(177, 9), // (195,23): error CS0123: No overload for 'Test2' matches delegate 'CL3_D1' // CL3_D1 d1 = y.Test2; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "Test2").WithArguments("Test2", "CL3_D1").WithLocation(195, 23), // (5,20): warning CS0649: Field 'Module1.f1' is never assigned to, and will always have its default value null // private CL3_C1 f1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "f1").WithArguments("Module1.f1", "null").WithLocation(5, 20) }; compilation5.VerifyDiagnostics(errors5); string cl4Source = a_cs + cl3Source; var compilation6 = CreateCompilation(cl4Source); DiagnosticDescription[] errors6 = { // (232,23): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public class CL3_C1 : CL2_C1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1").WithLocation(232, 23), // (306,23): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // public class CL3_C3 : CL2_I1, CL2_I2 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I1").WithArguments("CL2_I1").WithLocation(306, 23), // (306,31): error CS0246: The type or namespace name 'CL2_I2' could not be found (are you missing a using directive or an assembly reference?) // public class CL3_C3 : CL2_I1, CL2_I2 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I2").WithArguments("CL2_I2").WithLocation(306, 31), // (319,23): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // public struct CL3_S1: CL2_I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I1").WithArguments("CL2_I1").WithLocation(319, 23), // (239,19): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public static CL2_C1 Test2() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1").WithLocation(239, 19), // (322,27): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // public interface CL3_I1 : CL2_I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I1").WithArguments("CL2_I1").WithLocation(322, 27), // (317,29): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public delegate void CL3_D1(CL2_C1 x); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1").WithLocation(317, 29), // (244,12): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public CL2_C1 Test3() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1").WithLocation(244, 12), // (267,19): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public static CL2_C1 Test3() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1").WithLocation(267, 19), // (252,19): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public static CL2_C1 Test1() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1").WithLocation(252, 19), // (257,12): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public CL2_C1 x; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1").WithLocation(257, 12), // (133,16): error CS0509: 'Module1.C4': cannot derive from sealed type 'CL3_S1' // class C4 : CL3_S1 Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "CL3_S1").WithArguments("Module1.C4", "CL3_S1").WithLocation(133, 16), // (9,16): warning CS0219: The variable 'x1' is assigned but its value is never used // CL3_C1 x1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(9, 16), // (15,16): warning CS0219: The variable 'x2' is assigned but its value is never used // CL3_C3 x2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(15, 16), // (21,31): warning CS0219: The variable 'x3' is assigned but its value is never used // System.Action<CL3_C3> x3; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(21, 31), // (53,18): warning CS0219: The variable 'x4' is assigned but its value is never used // CL3_C3[] x4; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x4").WithArguments("x4").WithLocation(53, 18), // (65,20): warning CS0219: The variable 'x5' is assigned but its value is never used // C1<CL3_C1> x5; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(65, 20), // (145,17): warning CS0219: The variable 'x6' is assigned but its value is never used // CL3_S1? x6; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(145, 17), // (156,9): error CS0120: An object reference is required for the non-static field, method, or property 'CL3_C2.Test1(int)' // CL3_C2.Test1(1); Diagnostic(ErrorCode.ERR_ObjectRequired, "CL3_C2.Test1").WithArguments("CL3_C2.Test1(int)").WithLocation(156, 9), // (166,16): error CS1501: No overload for method 'Test4' takes 0 arguments // CL3_C2.Test4(); Diagnostic(ErrorCode.ERR_BadArgCount, "Test4").WithArguments("Test4", "0").WithLocation(166, 16), // (171,16): error CS0121: The call is ambiguous between the following methods or properties: 'CL3_C2.Test4(CL3_C1)' and 'CL3_C2.Test4(CL3_C3)' // CL3_C2.Test4(null); Diagnostic(ErrorCode.ERR_AmbigCall, "Test4").WithArguments("CL3_C2.Test4(CL3_C1)", "CL3_C2.Test4(CL3_C3)").WithLocation(171, 16), // (177,9): error CS0176: Member 'CL3_C2.Test1()' cannot be accessed with an instance reference; qualify it with a type name instead // y.Test1(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "y.Test1").WithArguments("CL3_C2.Test1()").WithLocation(177, 9), // (195,23): error CS0123: No overload for 'Test2' matches delegate 'CL3_D1' // CL3_D1 d1 = y.Test2; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "Test2").WithArguments("Test2", "CL3_D1").WithLocation(195, 23), // (5,20): warning CS0649: Field 'Module1.f1' is never assigned to, and will always have its default value null // private CL3_C1 f1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "f1").WithArguments("Module1.f1", "null").WithLocation(5, 20) }; compilation6.VerifyDiagnostics(errors6); compilation1.VerifyDiagnostics( // (6,16): warning CS0219: The variable 'x1' is assigned but its value is never used // CL3_C1 x1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1") ); } [Fact] public void MissingTypes3() { var cl2 = TestReferences.SymbolsTests.MissingTypes.CL2; var cl3 = TestReferences.SymbolsTests.MissingTypes.CL3; var references = new[] { MscorlibRef, TestMetadata.Net451.SystemData, TestMetadata.Net451.System, cl2, cl3 }; var compilation1 = CreateEmptyCompilation( @" class Program { static void Main(string[] args) { new System.Data.DataSet(); } } ", references); compilation1.VerifyDiagnostics(); } [Fact] [WorkItem(612417, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612417")] public void Repro612417() { var libSource = @" namespace System.Drawing { public class Point { } } "; var project1Source = @" using System.Drawing; public interface I { void Goo(Point p); } "; var project2Source = @" using System.Drawing; public class C { public void Goo(Point p) { } } "; var project3Source = @" class D : C, I { } "; var libRef = CreateEmptyCompilation(libSource, new[] { MscorlibRef }, assemblyName: "System.Drawing").EmitToImageReference(); var comp1 = CreateEmptyCompilation(project1Source, new[] { MscorlibRef, libRef }, assemblyName: "Project1"); comp1.VerifyDiagnostics(); var comp2 = CreateEmptyCompilation(project2Source, new[] { MscorlibRef, libRef }, assemblyName: "Project2"); comp2.VerifyDiagnostics(); // Scenario 1: Projects 1, 2, and 3 are in source; project 3 does not reference lib. { var comp3 = CreateEmptyCompilation(project3Source, new[] { MscorlibRef, comp1.ToMetadataReference(), comp2.ToMetadataReference() }, assemblyName: "Project3"); comp3.VerifyDiagnostics( // (2,7): error CS0012: The type 'System.Drawing.Point' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Drawing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class D : C, I { } Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("System.Drawing.Point", "System.Drawing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } // Scenario 2: Projects 1 and 2 are metadata, and project 3 is in source; project 3 does not reference lib. { var comp3 = CreateEmptyCompilation(project3Source, new[] { MscorlibRef, comp1.EmitToImageReference(), comp2.EmitToImageReference() }, assemblyName: "Project3"); comp3.VerifyDiagnostics( // (2,7): error CS0012: The type 'System.Drawing.Point' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Drawing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class D : C, I { } Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("System.Drawing.Point", "System.Drawing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } } [ClrOnlyFact] public void MissingTypeInTypeArgumentsOfImplementedInterface() { var lib1 = CreateCompilation(@" namespace ErrorTest { public interface I1<out T1> {} public interface I2 {} public interface I6<in T1> {} public class C10<T> where T : I1<I2> {} }", options: TestOptions.ReleaseDll, assemblyName: "MissingTypeInTypeArgumentsOfImplementedInterface1"); var lib1Ref = new CSharpCompilationReference(lib1); var lib2 = CreateCompilation(@" namespace ErrorTest { public interface I3 : I2 {} }", new[] { lib1Ref }, TestOptions.ReleaseDll, assemblyName: "MissingTypeInTypeArgumentsOfImplementedInterface2"); var lib2Ref = new CSharpCompilationReference(lib2); var lib3 = CreateCompilation(@" namespace ErrorTest { public class C4 : I1<I3> {} public interface I5 : I1<I3> {} public class C8<T> where T : I6<I3> {} }", new[] { lib1Ref, lib2Ref }, TestOptions.ReleaseDll, assemblyName: "MissingTypeInTypeArgumentsOfImplementedInterface3"); var lib3Ref = new CSharpCompilationReference(lib3); var lib4Def = @" namespace ErrorTest { class Test { void _Test(C4 y) { I1<I2> x = y; } } public class C6 : I5 {} public class C7 : C4 {} class Test3<T> where T : C4 { void Test(T y3) { I1<I2> x = y3; } } class Test4<T> where T : I5 { void Test(T y4) { I1<I2> x = y4; } } class Test5 { void Test(I5 y5) { I1<I2> x = y5; } } public class C9 : C8<I6<I2>> {} public class C11 : C10<C4> {} public class C12 : C10<I5> {} class Test6 { void Test(C8<I6<I2>> x) {} void Test(C10<C4> x) {} void Test(C10<I5> x) {} } }"; var lib4 = CreateCompilation(lib4Def, new[] { lib1Ref, lib3Ref }, TestOptions.ReleaseDll); DiagnosticDescription[] expectedErrors = { // (52,18): error CS0311: The type 'ErrorTest.I5' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C10<T>'. There is no implicit reference conversion from 'ErrorTest.I5' to 'ErrorTest.I1<ErrorTest.I2>'. // public class C12 Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "C12").WithArguments("ErrorTest.C10<T>", "ErrorTest.I1<ErrorTest.I2>", "T", "ErrorTest.I5"), // (52,18): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C12 Diagnostic(ErrorCode.ERR_NoTypeDef, "C12").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (44,18): error CS0311: The type 'ErrorTest.I6<ErrorTest.I2>' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C8<T>'. There is no implicit reference conversion from 'ErrorTest.I6<ErrorTest.I2>' to 'ErrorTest.I6<ErrorTest.I3>'. // public class C9 Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "C9").WithArguments("ErrorTest.C8<T>", "ErrorTest.I6<ErrorTest.I3>", "T", "ErrorTest.I6<ErrorTest.I2>"), // (44,18): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C9 Diagnostic(ErrorCode.ERR_NoTypeDef, "C9").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (48,18): error CS0311: The type 'ErrorTest.C4' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C10<T>'. There is no implicit reference conversion from 'ErrorTest.C4' to 'ErrorTest.I1<ErrorTest.I2>'. // public class C11 Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "C11").WithArguments("ErrorTest.C10<T>", "ErrorTest.I1<ErrorTest.I2>", "T", "ErrorTest.C4"), // (48,18): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C11 Diagnostic(ErrorCode.ERR_NoTypeDef, "C11").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (12,18): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C6 Diagnostic(ErrorCode.ERR_NoTypeDef, "C6").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (60,27): error CS0311: The type 'ErrorTest.C4' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C10<T>'. There is no implicit reference conversion from 'ErrorTest.C4' to 'ErrorTest.I1<ErrorTest.I2>'. // void Test(C10<C4> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "x").WithArguments("ErrorTest.C10<T>", "ErrorTest.I1<ErrorTest.I2>", "T", "ErrorTest.C4"), // (60,27): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C10<C4> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (62,27): error CS0311: The type 'ErrorTest.I5' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C10<T>'. There is no implicit reference conversion from 'ErrorTest.I5' to 'ErrorTest.I1<ErrorTest.I2>'. // void Test(C10<I5> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "x").WithArguments("ErrorTest.C10<T>", "ErrorTest.I1<ErrorTest.I2>", "T", "ErrorTest.I5"), // (62,27): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C10<I5> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (58,30): error CS0311: The type 'ErrorTest.I6<ErrorTest.I2>' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C8<T>'. There is no implicit reference conversion from 'ErrorTest.I6<ErrorTest.I2>' to 'ErrorTest.I6<ErrorTest.I3>'. // void Test(C8<I6<I2>> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "x").WithArguments("ErrorTest.C8<T>", "ErrorTest.I6<ErrorTest.I3>", "T", "ErrorTest.I6<ErrorTest.I2>"), // (58,30): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C8<I6<I2>> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (32,24): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1<I2> x = y4; Diagnostic(ErrorCode.ERR_NoTypeDef, "y4").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (32,24): error CS0266: Cannot implicitly convert type 'T' to 'ErrorTest.I1<ErrorTest.I2>'. An explicit conversion exists (are you missing a cast?) // I1<I2> x = y4; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y4").WithArguments("T", "ErrorTest.I1<ErrorTest.I2>"), // (40,24): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1<I2> x = y5; Diagnostic(ErrorCode.ERR_NoTypeDef, "y5").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (40,24): error CS0266: Cannot implicitly convert type 'ErrorTest.I5' to 'ErrorTest.I1<ErrorTest.I2>'. An explicit conversion exists (are you missing a cast?) // I1<I2> x = y5; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y5").WithArguments("ErrorTest.I5", "ErrorTest.I1<ErrorTest.I2>"), // (24,24): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1<I2> x = y3; Diagnostic(ErrorCode.ERR_NoTypeDef, "y3").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (24,24): error CS0266: Cannot implicitly convert type 'T' to 'ErrorTest.I1<ErrorTest.I2>'. An explicit conversion exists (are you missing a cast?) // I1<I2> x = y3; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y3").WithArguments("T", "ErrorTest.I1<ErrorTest.I2>"), // (8,24): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1<I2> x = y; Diagnostic(ErrorCode.ERR_NoTypeDef, "y").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,24): error CS0266: Cannot implicitly convert type 'ErrorTest.C4' to 'ErrorTest.I1<ErrorTest.I2>'. An explicit conversion exists (are you missing a cast?) // I1<I2> x = y; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("ErrorTest.C4", "ErrorTest.I1<ErrorTest.I2>") }; lib4.VerifyDiagnostics(expectedErrors); lib4 = CreateCompilation(lib4Def, new[] { lib1Ref, lib2Ref, lib3Ref }, TestOptions.ReleaseDll); CompileAndVerify(lib4).VerifyDiagnostics(); lib4 = CreateCompilation(lib4Def, new[] { lib1.EmitToImageReference(), lib3.EmitToImageReference() }, TestOptions.ReleaseDll); lib4.VerifyDiagnostics(expectedErrors); } [Fact()] public void MissingImplementedInterface() { var lib1 = CreateCompilation(@" namespace ErrorTest { public interface I1 { void M1(); } public class C9<T> where T : I1 { } } ", options: TestOptions.ReleaseDll, assemblyName: "MissingImplementedInterface1"); var lib1Ref = new CSharpCompilationReference(lib1); var lib2 = CreateCompilation(@" namespace ErrorTest { public interface I2 : I1 {} public class C12 : I2 { private void M1() //Implements I1.M1 {} void I1.M1() { } } } ", new[] { lib1Ref }, TestOptions.ReleaseDll, assemblyName: "MissingImplementedInterface2"); var lib2Ref = new CSharpCompilationReference(lib2); var lib3 = CreateCompilation(@" namespace ErrorTest { public class C4 : I2 { private void M1() //Implements I1.M1 {} void I1.M1() { } } public interface I5 : I2 {} public class C13 : C12 { } } ", new[] { lib1Ref, lib2Ref }, TestOptions.ReleaseDll, assemblyName: "MissingImplementedInterface3"); var lib3Ref = new CSharpCompilationReference(lib3); var lib4Def = @" namespace ErrorTest { class Test { void _Test(C4 y) { I1 x = y; } } public class C6 : I5 { void I1.M1() {} } public class C7 : C4 {} class Test2 { void _Test2(I5 x, C4 y) { x.M1(); y.M1(); } } class Test3<T> where T : C4 { void Test(T y3) { I1 x = y3; y3.M1(); } } class Test4<T> where T : I5 { void Test(T y4) { I1 x = y4; y4.M1(); } } public class C8 : I5 { void I1.M1() {} } public class C10 : C9<C4> {} public class C11 : C9<I5> {} class Test5 { void Test(C9<C4> x) { } void Test(C9<I5> x) { } void Test(C13 c13) { I1 x = c13; } } } "; var lib4 = CreateCompilation(lib4Def, new[] { lib1Ref, lib3Ref }, TestOptions.ReleaseDll); lib4.VerifyDiagnostics( // (48,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C8 : I5 Diagnostic(ErrorCode.ERR_NoTypeDef, "C8").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (12,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C6 : I5 Diagnostic(ErrorCode.ERR_NoTypeDef, "C6").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (50,14): error CS0540: 'ErrorTest.C8.ErrorTest.I1.M1()': containing type does not implement interface 'ErrorTest.I1' // void I1.M1() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("ErrorTest.C8.ErrorTest.I1.M1()", "ErrorTest.I1"), // (14,14): error CS0540: 'ErrorTest.C6.ErrorTest.I1.M1()': containing type does not implement interface 'ErrorTest.I1' // void I1.M1() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("ErrorTest.C6.ErrorTest.I1.M1()", "ErrorTest.I1"), // (54,18): error CS0311: The type 'ErrorTest.C4' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C9<T>'. There is no implicit reference conversion from 'ErrorTest.C4' to 'ErrorTest.I1'. // public class C10 : C9<C4> Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "C10").WithArguments("ErrorTest.C9<T>", "ErrorTest.I1", "T", "ErrorTest.C4"), // (54,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C10 : C9<C4> Diagnostic(ErrorCode.ERR_NoTypeDef, "C10").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (57,18): error CS0311: The type 'ErrorTest.I5' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C9<T>'. There is no implicit reference conversion from 'ErrorTest.I5' to 'ErrorTest.I1'. // public class C11 : C9<I5> Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "C11").WithArguments("ErrorTest.C9<T>", "ErrorTest.I1", "T", "ErrorTest.I5"), // (57,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C11 : C9<I5> Diagnostic(ErrorCode.ERR_NoTypeDef, "C11").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (64,26): error CS0311: The type 'ErrorTest.I5' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C9<T>'. There is no implicit reference conversion from 'ErrorTest.I5' to 'ErrorTest.I1'. // void Test(C9<I5> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "x").WithArguments("ErrorTest.C9<T>", "ErrorTest.I1", "T", "ErrorTest.I5"), // (64,26): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C9<I5> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (62,26): error CS0311: The type 'ErrorTest.C4' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C9<T>'. There is no implicit reference conversion from 'ErrorTest.C4' to 'ErrorTest.I1'. // void Test(C9<C4> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "x").WithArguments("ErrorTest.C9<T>", "ErrorTest.I1", "T", "ErrorTest.C4"), // (62,26): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C9<C4> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (69,20): error CS0012: The type 'ErrorTest.C12' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = c13; Diagnostic(ErrorCode.ERR_NoTypeDef, "c13").WithArguments("ErrorTest.C12", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (69,20): error CS0266: Cannot implicitly convert type 'ErrorTest.C13' to 'ErrorTest.I1'. An explicit conversion exists (are you missing a cast?) // I1 x = c13; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "c13").WithArguments("ErrorTest.C13", "ErrorTest.I1"), // (8,20): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = y; Diagnostic(ErrorCode.ERR_NoTypeDef, "y").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,20): error CS0266: Cannot implicitly convert type 'ErrorTest.C4' to 'ErrorTest.I1'. An explicit conversion exists (are you missing a cast?) // I1 x = y; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("ErrorTest.C4", "ErrorTest.I1"), // (34,20): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = y3; Diagnostic(ErrorCode.ERR_NoTypeDef, "y3").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (34,20): error CS0266: Cannot implicitly convert type 'T' to 'ErrorTest.I1'. An explicit conversion exists (are you missing a cast?) // I1 x = y3; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y3").WithArguments("T", "ErrorTest.I1"), // (35,16): error CS0122: 'ErrorTest.C4.M1()' is inaccessible due to its protection level // y3.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("ErrorTest.C4.M1()"), // (25,15): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // x.M1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "M1").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (25,15): error CS1061: 'ErrorTest.I5' does not contain a definition for 'M1' and no extension method 'M1' accepting a first argument of type 'ErrorTest.I5' could be found (are you missing a using directive or an assembly reference?) // x.M1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("ErrorTest.I5", "M1"), // (26,15): error CS0122: 'ErrorTest.C4.M1()' is inaccessible due to its protection level // y.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("ErrorTest.C4.M1()"), // (43,20): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = y4; Diagnostic(ErrorCode.ERR_NoTypeDef, "y4").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (43,20): error CS0266: Cannot implicitly convert type 'T' to 'ErrorTest.I1'. An explicit conversion exists (are you missing a cast?) // I1 x = y4; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y4").WithArguments("T", "ErrorTest.I1"), // (44,16): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // y4.M1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "M1").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (44,16): error CS1061: 'T' does not contain a definition for 'M1' and no extension method 'M1' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // y4.M1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("T", "M1") ); lib4 = CreateCompilation(lib4Def, new[] { lib1Ref, lib2Ref, lib3Ref }, TestOptions.ReleaseDll); lib4.VerifyDiagnostics( // (35,16): error CS0122: 'ErrorTest.C4.M1()' is inaccessible due to its protection level // y3.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("ErrorTest.C4.M1()"), // (26,15): error CS0122: 'ErrorTest.C4.M1()' is inaccessible due to its protection level // y.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("ErrorTest.C4.M1()") ); lib4 = CreateCompilation(lib4Def, new[] { lib1.EmitToImageReference(), lib3.EmitToImageReference() }, TestOptions.ReleaseDll); lib4.VerifyDiagnostics( // (12,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C6 : I5 Diagnostic(ErrorCode.ERR_NoTypeDef, "C6").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (48,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C8 : I5 Diagnostic(ErrorCode.ERR_NoTypeDef, "C8").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (64,26): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C9<I5> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (62,26): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C9<C4> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (54,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C10 : C9<C4> Diagnostic(ErrorCode.ERR_NoTypeDef, "C10").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (57,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C11 : C9<I5> Diagnostic(ErrorCode.ERR_NoTypeDef, "C11").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,20): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = y; Diagnostic(ErrorCode.ERR_NoTypeDef, "y").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (69,20): error CS0012: The type 'ErrorTest.C12' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = c13; Diagnostic(ErrorCode.ERR_NoTypeDef, "c13").WithArguments("ErrorTest.C12", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (69,20): error CS0266: Cannot implicitly convert type 'ErrorTest.C13' to 'ErrorTest.I1'. An explicit conversion exists (are you missing a cast?) // I1 x = c13; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "c13").WithArguments("ErrorTest.C13", "ErrorTest.I1"), // (34,20): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = y3; Diagnostic(ErrorCode.ERR_NoTypeDef, "y3").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (35,16): error CS1061: 'T' does not contain a definition for 'M1' and no extension method 'M1' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // y3.M1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("T", "M1"), // (43,20): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = y4; Diagnostic(ErrorCode.ERR_NoTypeDef, "y4").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (44,16): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // y4.M1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "M1").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (25,15): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // x.M1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "M1").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (26,15): error CS1061: 'ErrorTest.C4' does not contain a definition for 'M1' and no extension method 'M1' accepting a first argument of type 'ErrorTest.C4' could be found (are you missing a using directive or an assembly reference?) // y.M1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("ErrorTest.C4", "M1") ); } [ClrOnlyFact] public void MissingBaseClass() { var lib1 = CreateCompilation(@" namespace ErrorTest { public class C1 { public void M1() {} } public class C6<T> where T : C1 {} }", options: TestOptions.ReleaseDll, assemblyName: "MissingBaseClass1"); var lib1Ref = new CSharpCompilationReference(lib1); var lib2 = CreateCompilation(@" namespace ErrorTest { public class C2 : C1 {} }", new[] { lib1Ref }, TestOptions.ReleaseDll, assemblyName: "MissingBaseClass2"); var lib2Ref = new CSharpCompilationReference(lib2); var lib3 = CreateCompilation(@" namespace ErrorTest { public class C4 : C2 {} }", new[] { lib1Ref, lib2Ref }, TestOptions.ReleaseDll, assemblyName: "MissingBaseClass3"); var lib3Ref = new CSharpCompilationReference(lib3); var lib4Def = @" namespace ErrorTest { class Test { void _Test(C4 y) { C1 x = y; } } public class C5 : C4 {} class Test2 { void _Test2(C4 y) { y.M1(); } } class Test3<T> where T : C4 { void Test(T y3) { C1 x = y3; y3.M1(); } } public class C7 : C6<C4> {} class Test4 { void Test(C6<C4> x) { } } }"; var lib4 = CreateCompilation(lib4Def, new[] { lib1Ref, lib3Ref }, TestOptions.ReleaseDll); DiagnosticDescription[] expectedErrors = { // (12,23): error CS0012: The type 'ErrorTest.C2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C5 : C4 Diagnostic(ErrorCode.ERR_NoTypeDef, "C4").WithArguments("ErrorTest.C2", "MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (32,18): error CS0311: The type 'ErrorTest.C4' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C6<T>'. There is no implicit reference conversion from 'ErrorTest.C4' to 'ErrorTest.C1'. // public class C7 : C6<C4> Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "C7").WithArguments("ErrorTest.C6<T>", "ErrorTest.C1", "T", "ErrorTest.C4"), // (32,18): error CS0012: The type 'ErrorTest.C2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C7 : C6<C4> Diagnostic(ErrorCode.ERR_NoTypeDef, "C7").WithArguments("ErrorTest.C2", "MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (37,26): error CS0311: The type 'ErrorTest.C4' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C6<T>'. There is no implicit reference conversion from 'ErrorTest.C4' to 'ErrorTest.C1'. // void Test(C6<C4> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "x").WithArguments("ErrorTest.C6<T>", "ErrorTest.C1", "T", "ErrorTest.C4"), // (37,26): error CS0012: The type 'ErrorTest.C2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C6<C4> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.C2", "MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (19,15): error CS0012: The type 'ErrorTest.C2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // y.M1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "M1").WithArguments("ErrorTest.C2", "MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (19,15): error CS1061: 'ErrorTest.C4' does not contain a definition for 'M1' and no extension method 'M1' accepting a first argument of type 'ErrorTest.C4' could be found (are you missing a using directive or an assembly reference?) // y.M1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("ErrorTest.C4", "M1"), // (8,20): error CS0012: The type 'ErrorTest.C2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // C1 x = y; Diagnostic(ErrorCode.ERR_NoTypeDef, "y").WithArguments("ErrorTest.C2", "MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,20): error CS0029: Cannot implicitly convert type 'ErrorTest.C4' to 'ErrorTest.C1' // C1 x = y; Diagnostic(ErrorCode.ERR_NoImplicitConv, "y").WithArguments("ErrorTest.C4", "ErrorTest.C1"), // (27,20): error CS0012: The type 'ErrorTest.C2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // C1 x = y3; Diagnostic(ErrorCode.ERR_NoTypeDef, "y3").WithArguments("ErrorTest.C2", "MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (27,20): error CS0029: Cannot implicitly convert type 'T' to 'ErrorTest.C1' // C1 x = y3; Diagnostic(ErrorCode.ERR_NoImplicitConv, "y3").WithArguments("T", "ErrorTest.C1"), // (28,16): error CS0012: The type 'ErrorTest.C2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // y3.M1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "M1").WithArguments("ErrorTest.C2", "MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (28,16): error CS1061: 'T' does not contain a definition for 'M1' and no extension method 'M1' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // y3.M1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("T", "M1") }; lib4.VerifyDiagnostics(expectedErrors); lib4 = CreateCompilation(lib4Def, new[] { lib1Ref, lib2Ref, lib3Ref }, TestOptions.ReleaseDll); CompileAndVerify(lib4).VerifyDiagnostics(); lib4 = CreateCompilation(lib4Def, new[] { lib1.EmitToImageReference(), lib3.EmitToImageReference() }, TestOptions.ReleaseDll); lib4.VerifyDiagnostics(expectedErrors); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class BadSymbolReference : CSharpTestBase { //CreateCompilationWithMscorlib(text).VerifyDiagnostics( // // (6,17): error CS0023: Operator '.' cannot be applied to operand of type '<null>' // Diagnostic(ErrorCode.ERR_BadUnaryOp, @"null.Length").WithArguments(".", "<null>")); [Fact] public void MissingTypes1() { var cl2 = TestReferences.SymbolsTests.MissingTypes.CL2; var cl3 = TestReferences.SymbolsTests.MissingTypes.CL3; var compilation1 = CreateCompilation( @" class Module1 { void Main() { CL3_C1 x1; x1 = null; } }", new MetadataReference[] { cl2, cl3 }); var a_cs = @" class Module1 { private CL3_C1 f1; void Main() { CL3_C1 x1; x1 = null; } void Test1() { CL3_C3 x2; x2 = null; } void Test2() { System.Action<CL3_C3> x3; x3 = null; } void Test3() { CL3_C1.Test1(); } void Test4() { global::CL3_C1.Test1(); } void Test5() { C1<CL3_C1>.Test1(); } void Test6() { global::C1<CL3_C1>.Test1(); } void Test7() { object x1; x1 = new CL3_C1(); } void Test8() { CL3_C3[] x4; x4 = null; } void Test9() { object x4; x4 = new CL3_C3[] {}; } void Test10() { C1<CL3_C1> x5; x5 = null; } void Test11() { object x5; x5 = new C1<CL3_C1>(); } void Test() { var v = new CL3_C4(); } void Test12() { var w = new CL3_C5(); } void Test13() { CL3_C2 y = null; object z = y.x; } void Test15() { CL3_C2 y = null; object z; z = y.u; } void Test16() { CL3_C2 y = null; object z; z = y.y; } void Test17() { CL3_C2 y = null; object z; z = y.z; } void Test18() { CL3_C2 y=null; object z; z = y.v; } void Test19() { object z; z = f1; } class C2 : CL3_C1 { } class C3 : System.Collections.Generic.List<CL3_C1> { } class C4 : CL3_S1 { } interface I2 : CL3_I1, I1<CL3_I1> {} class C5 : CL3_I1, I1<CL3_I1> {} void Test20() { CL3_S1? x6; x6 = null; } void Test21() { CL3_C2.Test1(); } void Test22() { CL3_C2.Test1(1); } void Test23() { CL3_C2.Test3(); } void Test24() { CL3_C2.Test4(); } void Test24_1() { CL3_C2.Test4(null); } void Test25() { CL3_C2 y = null; y.Test1(); } void Test26() { CL3_C2 y = null; y.Test1(1); } void Test27() { CL3_C2 y = null; y.Test2(2); } void Test28() { CL3_C2 y = null; CL3_D1 d1 = y.Test2; } void Test29() { CL3_C2 y = null; y.v(null); } void Test30() { CL3_C2 y = null; y.w(null); } void Test31() { CL3_D1 u = (uuu) => System.Console.WriteLine(); } void Test32() { CL3_C2 y = null; object zz = y.P2; } } class C1<T> { public static void Test1() { } } interface I1<T> {} "; DiagnosticDescription[] errors = { // (140,11): error CS0012: The type 'CL2_I1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C5 : CL3_I1, I1<CL3_I1> Diagnostic(ErrorCode.ERR_NoTypeDef, "C5").WithArguments("CL2_I1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(140, 11), // (125,16): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class C2 : CL3_C1 Diagnostic(ErrorCode.ERR_NoTypeDef, "CL3_C1").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(125, 16), // (133,16): error CS0509: 'Module1.C4': cannot derive from sealed type 'CL3_S1' // class C4 : CL3_S1 Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "CL3_S1").WithArguments("Module1.C4", "CL3_S1").WithLocation(133, 16), // (137,15): error CS0012: The type 'CL2_I1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // interface I2 : CL3_I1, I1<CL3_I1> Diagnostic(ErrorCode.ERR_NoTypeDef, "I2").WithArguments("CL2_I1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(137, 15), // (9,16): warning CS0219: The variable 'x1' is assigned but its value is never used // CL3_C1 x1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(9, 16), // (15,16): warning CS0219: The variable 'x2' is assigned but its value is never used // CL3_C3 x2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(15, 16), // (21,31): warning CS0219: The variable 'x3' is assigned but its value is never used // System.Action<CL3_C3> x3; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(21, 31), // (27,16): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CL3_C1.Test1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "Test1").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(27, 16), // (32,24): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // global::CL3_C1.Test1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "Test1").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(32, 24), // (53,18): warning CS0219: The variable 'x4' is assigned but its value is never used // CL3_C3[] x4; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x4").WithArguments("x4").WithLocation(53, 18), // (65,20): warning CS0219: The variable 'x5' is assigned but its value is never used // C1<CL3_C1> x5; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(65, 20), // (88,22): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // object z = y.x; Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(88, 22), // (145,17): warning CS0219: The variable 'x6' is assigned but its value is never used // CL3_S1? x6; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(145, 17), // (151,9): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CL3_C2.Test1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "CL3_C2.Test1").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(151, 9), // (156,9): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CL3_C2.Test1(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "CL3_C2.Test1").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(156, 9), // (156,9): error CS0120: An object reference is required for the non-static field, method, or property 'CL3_C2.Test1(int)' // CL3_C2.Test1(1); Diagnostic(ErrorCode.ERR_ObjectRequired, "CL3_C2.Test1").WithArguments("CL3_C2.Test1(int)").WithLocation(156, 9), // (161,9): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CL3_C2.Test3(); Diagnostic(ErrorCode.ERR_NoTypeDef, "CL3_C2.Test3").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(161, 9), // (166,16): error CS1501: No overload for method 'Test4' takes 0 arguments // CL3_C2.Test4(); Diagnostic(ErrorCode.ERR_BadArgCount, "Test4").WithArguments("Test4", "0").WithLocation(166, 16), // (171,9): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CL3_C2.Test4(null); Diagnostic(ErrorCode.ERR_NoTypeDef, "CL3_C2.Test4").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(171, 9), // (171,16): error CS0121: The call is ambiguous between the following methods or properties: 'CL3_C2.Test4(CL3_C1)' and 'CL3_C2.Test4(CL3_C3)' // CL3_C2.Test4(null); Diagnostic(ErrorCode.ERR_AmbigCall, "Test4").WithArguments("CL3_C2.Test4(CL3_C1)", "CL3_C2.Test4(CL3_C3)").WithLocation(171, 16), // (177,9): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // y.Test1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "y.Test1").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(177, 9), // (195,23): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CL3_D1 d1 = y.Test2; Diagnostic(ErrorCode.ERR_NoTypeDef, "Test2").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(195, 23), // (207,9): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // y.w(null); Diagnostic(ErrorCode.ERR_NoTypeDef, "y.w(null)").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(207, 9), // (212,20): error CS0012: The type 'CL2_C1' is defined in an assembly that is not referenced. You must add a reference to assembly 'CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // CL3_D1 u = (uuu) => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NoTypeDef, "(uuu) => System.Console.WriteLine()").WithArguments("CL2_C1", "CL2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(212, 20), // (5,20): warning CS0649: Field 'Module1.f1' is never assigned to, and will always have its default value null // private CL3_C1 f1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "f1").WithArguments("Module1.f1", "null").WithLocation(5, 20) }; var compilation2 = CreateCompilation(a_cs, new MetadataReference[] { cl3 }); compilation2.VerifyDiagnostics(errors); string cl3Source = @" public class CL3_C1 : CL2_C1 { public static object Test1() { return null; } public static CL2_C1 Test2() { return null; } public CL2_C1 Test3() { return null; } } public class CL3_C2 { public static CL2_C1 Test1() { return null; } public CL2_C1 x; public void Test1(int x) { } public void Test2(int x) { } public static CL2_C1 Test3() { return null; } public static void Test4(CL3_C1 x) { } public static void Test4(CL3_C3 x) { } public CL3_C3 y; public CL3_C4 z; public CL3_C5[] u; public System.Action<CL3_C5> v; public CL3_D1 w; public static CL3_C2 Test5() { return null; } public CL3_C1 P2 { get { return null; } set { } } } public class CL3_C3 : CL2_I1, CL2_I2 { } public class CL3_C4 : CL3_C1 {} public class CL3_C5 : CL3_C3 {} public delegate void CL3_D1(CL2_C1 x); public struct CL3_S1: CL2_I1 {} public interface CL3_I1 : CL2_I1 {} "; var cl3Compilation = CreateCompilation(cl3Source, new MetadataReference[] { cl2 }); cl3Compilation.VerifyDiagnostics(); var compilation3 = CreateCompilation(a_cs, new MetadataReference[] { new CSharpCompilationReference(cl3Compilation) }); compilation3.VerifyDiagnostics(errors); var cl3BadCompilation1 = CreateCompilation(cl3Source, new MetadataReference[] { cl3 }); var compilation4 = CreateCompilation(a_cs, new MetadataReference[] { new CSharpCompilationReference(cl3BadCompilation1) }); DiagnosticDescription[] errors2 = { // (140,11): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // class C5 : CL3_I1, I1<CL3_I1> Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C5").WithArguments("CL2_I1").WithLocation(140, 11), // (125,16): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // class C2 : CL3_C1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL3_C1").WithArguments("CL2_C1").WithLocation(125, 16), // (133,16): error CS0509: 'Module1.C4': cannot derive from sealed type 'CL3_S1' // class C4 : CL3_S1 Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "CL3_S1").WithArguments("Module1.C4", "CL3_S1").WithLocation(133, 16), // (137,15): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // interface I2 : CL3_I1, I1<CL3_I1> Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "I2").WithArguments("CL2_I1").WithLocation(137, 15), // (9,16): warning CS0219: The variable 'x1' is assigned but its value is never used // CL3_C1 x1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(9, 16), // (15,16): warning CS0219: The variable 'x2' is assigned but its value is never used // CL3_C3 x2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(15, 16), // (21,31): warning CS0219: The variable 'x3' is assigned but its value is never used // System.Action<CL3_C3> x3; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(21, 31), // (27,16): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // CL3_C1.Test1(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Test1").WithArguments("CL2_C1").WithLocation(27, 16), // (32,24): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // global::CL3_C1.Test1(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Test1").WithArguments("CL2_C1").WithLocation(32, 24), // (53,18): warning CS0219: The variable 'x4' is assigned but its value is never used // CL3_C3[] x4; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x4").WithArguments("x4").WithLocation(53, 18), // (65,20): warning CS0219: The variable 'x5' is assigned but its value is never used // C1<CL3_C1> x5; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(65, 20), // (88,22): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // object z = y.x; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("CL2_C1").WithLocation(88, 22), // (145,17): warning CS0219: The variable 'x6' is assigned but its value is never used // CL3_S1? x6; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(145, 17), // (151,9): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // CL3_C2.Test1(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL3_C2.Test1").WithArguments("CL2_C1").WithLocation(151, 9), // (156,9): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // CL3_C2.Test1(1); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL3_C2.Test1").WithArguments("CL2_C1").WithLocation(156, 9), // (156,9): error CS0120: An object reference is required for the non-static field, method, or property 'CL3_C2.Test1(int)' // CL3_C2.Test1(1); Diagnostic(ErrorCode.ERR_ObjectRequired, "CL3_C2.Test1").WithArguments("CL3_C2.Test1(int)").WithLocation(156, 9), // (161,9): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // CL3_C2.Test3(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL3_C2.Test3").WithArguments("CL2_C1").WithLocation(161, 9), // (166,16): error CS1501: No overload for method 'Test4' takes 0 arguments // CL3_C2.Test4(); Diagnostic(ErrorCode.ERR_BadArgCount, "Test4").WithArguments("Test4", "0").WithLocation(166, 16), // (171,9): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // CL3_C2.Test4(null); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL3_C2.Test4").WithArguments("CL2_C1").WithLocation(171, 9), // (171,9): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // CL3_C2.Test4(null); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL3_C2.Test4").WithArguments("CL2_I1").WithLocation(171, 9), // (171,16): error CS0121: The call is ambiguous between the following methods or properties: 'CL3_C2.Test4(CL3_C1)' and 'CL3_C2.Test4(CL3_C3)' // CL3_C2.Test4(null); Diagnostic(ErrorCode.ERR_AmbigCall, "Test4").WithArguments("CL3_C2.Test4(CL3_C1)", "CL3_C2.Test4(CL3_C3)").WithLocation(171, 16), // (177,9): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // y.Test1(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "y.Test1").WithArguments("CL2_C1").WithLocation(177, 9), // (195,23): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // CL3_D1 d1 = y.Test2; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Test2").WithArguments("CL2_C1").WithLocation(195, 23), // (207,9): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // y.w(null); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "y.w(null)").WithArguments("CL2_C1").WithLocation(207, 9), // (212,20): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // CL3_D1 u = (uuu) => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "(uuu) => System.Console.WriteLine()").WithArguments("CL2_C1").WithLocation(212, 20), // (5,20): warning CS0649: Field 'Module1.f1' is never assigned to, and will always have its default value null // private CL3_C1 f1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "f1").WithArguments("Module1.f1", "null").WithLocation(5, 20) }; compilation4.VerifyDiagnostics(errors2); var cl3BadCompilation2 = CreateCompilation(cl3Source); DiagnosticDescription[] errors3 = { // (2,23): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public class CL3_C1 : CL2_C1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1"), // (9,19): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public static CL2_C1 Test2() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1"), // (14,12): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public CL2_C1 Test3() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1"), // (22,19): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public static CL2_C1 Test1() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1"), // (37,19): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public static CL2_C1 Test3() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1"), // (27,12): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public CL2_C1 x; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1"), // (76,23): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // public class CL3_C3 : CL2_I1, CL2_I2 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I1").WithArguments("CL2_I1"), // (76,31): error CS0246: The type or namespace name 'CL2_I2' could not be found (are you missing a using directive or an assembly reference?) // public class CL3_C3 : CL2_I1, CL2_I2 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I2").WithArguments("CL2_I2"), // (87,29): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public delegate void CL3_D1(CL2_C1 x); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1"), // (89,23): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // public struct CL3_S1: CL2_I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I1").WithArguments("CL2_I1"), // (92,27): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // public interface CL3_I1 : CL2_I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I1").WithArguments("CL2_I1") }; cl3BadCompilation2.VerifyDiagnostics(errors3); var compilation5 = CreateCompilation(a_cs, new MetadataReference[] { new CSharpCompilationReference(cl3BadCompilation2) }); DiagnosticDescription[] errors5 = { // (133,16): error CS0509: 'Module1.C4': cannot derive from sealed type 'CL3_S1' // class C4 : CL3_S1 Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "CL3_S1").WithArguments("Module1.C4", "CL3_S1").WithLocation(133, 16), // (9,16): warning CS0219: The variable 'x1' is assigned but its value is never used // CL3_C1 x1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(9, 16), // (15,16): warning CS0219: The variable 'x2' is assigned but its value is never used // CL3_C3 x2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(15, 16), // (21,31): warning CS0219: The variable 'x3' is assigned but its value is never used // System.Action<CL3_C3> x3; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(21, 31), // (53,18): warning CS0219: The variable 'x4' is assigned but its value is never used // CL3_C3[] x4; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x4").WithArguments("x4").WithLocation(53, 18), // (65,20): warning CS0219: The variable 'x5' is assigned but its value is never used // C1<CL3_C1> x5; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(65, 20), // (145,17): warning CS0219: The variable 'x6' is assigned but its value is never used // CL3_S1? x6; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(145, 17), // (156,9): error CS0120: An object reference is required for the non-static field, method, or property 'CL3_C2.Test1(int)' // CL3_C2.Test1(1); Diagnostic(ErrorCode.ERR_ObjectRequired, "CL3_C2.Test1").WithArguments("CL3_C2.Test1(int)").WithLocation(156, 9), // (166,16): error CS1501: No overload for method 'Test4' takes 0 arguments // CL3_C2.Test4(); Diagnostic(ErrorCode.ERR_BadArgCount, "Test4").WithArguments("Test4", "0").WithLocation(166, 16), // (171,16): error CS0121: The call is ambiguous between the following methods or properties: 'CL3_C2.Test4(CL3_C1)' and 'CL3_C2.Test4(CL3_C3)' // CL3_C2.Test4(null); Diagnostic(ErrorCode.ERR_AmbigCall, "Test4").WithArguments("CL3_C2.Test4(CL3_C1)", "CL3_C2.Test4(CL3_C3)").WithLocation(171, 16), // (177,9): error CS0176: Member 'CL3_C2.Test1()' cannot be accessed with an instance reference; qualify it with a type name instead // y.Test1(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "y.Test1").WithArguments("CL3_C2.Test1()").WithLocation(177, 9), // (195,23): error CS0123: No overload for 'Test2' matches delegate 'CL3_D1' // CL3_D1 d1 = y.Test2; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "Test2").WithArguments("Test2", "CL3_D1").WithLocation(195, 23), // (5,20): warning CS0649: Field 'Module1.f1' is never assigned to, and will always have its default value null // private CL3_C1 f1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "f1").WithArguments("Module1.f1", "null").WithLocation(5, 20) }; compilation5.VerifyDiagnostics(errors5); string cl4Source = a_cs + cl3Source; var compilation6 = CreateCompilation(cl4Source); DiagnosticDescription[] errors6 = { // (232,23): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public class CL3_C1 : CL2_C1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1").WithLocation(232, 23), // (306,23): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // public class CL3_C3 : CL2_I1, CL2_I2 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I1").WithArguments("CL2_I1").WithLocation(306, 23), // (306,31): error CS0246: The type or namespace name 'CL2_I2' could not be found (are you missing a using directive or an assembly reference?) // public class CL3_C3 : CL2_I1, CL2_I2 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I2").WithArguments("CL2_I2").WithLocation(306, 31), // (319,23): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // public struct CL3_S1: CL2_I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I1").WithArguments("CL2_I1").WithLocation(319, 23), // (239,19): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public static CL2_C1 Test2() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1").WithLocation(239, 19), // (322,27): error CS0246: The type or namespace name 'CL2_I1' could not be found (are you missing a using directive or an assembly reference?) // public interface CL3_I1 : CL2_I1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_I1").WithArguments("CL2_I1").WithLocation(322, 27), // (317,29): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public delegate void CL3_D1(CL2_C1 x); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1").WithLocation(317, 29), // (244,12): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public CL2_C1 Test3() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1").WithLocation(244, 12), // (267,19): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public static CL2_C1 Test3() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1").WithLocation(267, 19), // (252,19): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public static CL2_C1 Test1() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1").WithLocation(252, 19), // (257,12): error CS0246: The type or namespace name 'CL2_C1' could not be found (are you missing a using directive or an assembly reference?) // public CL2_C1 x; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CL2_C1").WithArguments("CL2_C1").WithLocation(257, 12), // (133,16): error CS0509: 'Module1.C4': cannot derive from sealed type 'CL3_S1' // class C4 : CL3_S1 Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "CL3_S1").WithArguments("Module1.C4", "CL3_S1").WithLocation(133, 16), // (9,16): warning CS0219: The variable 'x1' is assigned but its value is never used // CL3_C1 x1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(9, 16), // (15,16): warning CS0219: The variable 'x2' is assigned but its value is never used // CL3_C3 x2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(15, 16), // (21,31): warning CS0219: The variable 'x3' is assigned but its value is never used // System.Action<CL3_C3> x3; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(21, 31), // (53,18): warning CS0219: The variable 'x4' is assigned but its value is never used // CL3_C3[] x4; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x4").WithArguments("x4").WithLocation(53, 18), // (65,20): warning CS0219: The variable 'x5' is assigned but its value is never used // C1<CL3_C1> x5; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(65, 20), // (145,17): warning CS0219: The variable 'x6' is assigned but its value is never used // CL3_S1? x6; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(145, 17), // (156,9): error CS0120: An object reference is required for the non-static field, method, or property 'CL3_C2.Test1(int)' // CL3_C2.Test1(1); Diagnostic(ErrorCode.ERR_ObjectRequired, "CL3_C2.Test1").WithArguments("CL3_C2.Test1(int)").WithLocation(156, 9), // (166,16): error CS1501: No overload for method 'Test4' takes 0 arguments // CL3_C2.Test4(); Diagnostic(ErrorCode.ERR_BadArgCount, "Test4").WithArguments("Test4", "0").WithLocation(166, 16), // (171,16): error CS0121: The call is ambiguous between the following methods or properties: 'CL3_C2.Test4(CL3_C1)' and 'CL3_C2.Test4(CL3_C3)' // CL3_C2.Test4(null); Diagnostic(ErrorCode.ERR_AmbigCall, "Test4").WithArguments("CL3_C2.Test4(CL3_C1)", "CL3_C2.Test4(CL3_C3)").WithLocation(171, 16), // (177,9): error CS0176: Member 'CL3_C2.Test1()' cannot be accessed with an instance reference; qualify it with a type name instead // y.Test1(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "y.Test1").WithArguments("CL3_C2.Test1()").WithLocation(177, 9), // (195,23): error CS0123: No overload for 'Test2' matches delegate 'CL3_D1' // CL3_D1 d1 = y.Test2; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "Test2").WithArguments("Test2", "CL3_D1").WithLocation(195, 23), // (5,20): warning CS0649: Field 'Module1.f1' is never assigned to, and will always have its default value null // private CL3_C1 f1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "f1").WithArguments("Module1.f1", "null").WithLocation(5, 20) }; compilation6.VerifyDiagnostics(errors6); compilation1.VerifyDiagnostics( // (6,16): warning CS0219: The variable 'x1' is assigned but its value is never used // CL3_C1 x1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1") ); } [Fact] public void MissingTypes3() { var cl2 = TestReferences.SymbolsTests.MissingTypes.CL2; var cl3 = TestReferences.SymbolsTests.MissingTypes.CL3; var references = new[] { MscorlibRef, TestMetadata.Net451.SystemData, TestMetadata.Net451.System, cl2, cl3 }; var compilation1 = CreateEmptyCompilation( @" class Program { static void Main(string[] args) { new System.Data.DataSet(); } } ", references); compilation1.VerifyDiagnostics(); } [Fact] [WorkItem(612417, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612417")] public void Repro612417() { var libSource = @" namespace System.Drawing { public class Point { } } "; var project1Source = @" using System.Drawing; public interface I { void Goo(Point p); } "; var project2Source = @" using System.Drawing; public class C { public void Goo(Point p) { } } "; var project3Source = @" class D : C, I { } "; var libRef = CreateEmptyCompilation(libSource, new[] { MscorlibRef }, assemblyName: "System.Drawing").EmitToImageReference(); var comp1 = CreateEmptyCompilation(project1Source, new[] { MscorlibRef, libRef }, assemblyName: "Project1"); comp1.VerifyDiagnostics(); var comp2 = CreateEmptyCompilation(project2Source, new[] { MscorlibRef, libRef }, assemblyName: "Project2"); comp2.VerifyDiagnostics(); // Scenario 1: Projects 1, 2, and 3 are in source; project 3 does not reference lib. { var comp3 = CreateEmptyCompilation(project3Source, new[] { MscorlibRef, comp1.ToMetadataReference(), comp2.ToMetadataReference() }, assemblyName: "Project3"); comp3.VerifyDiagnostics( // (2,7): error CS0012: The type 'System.Drawing.Point' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Drawing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class D : C, I { } Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("System.Drawing.Point", "System.Drawing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } // Scenario 2: Projects 1 and 2 are metadata, and project 3 is in source; project 3 does not reference lib. { var comp3 = CreateEmptyCompilation(project3Source, new[] { MscorlibRef, comp1.EmitToImageReference(), comp2.EmitToImageReference() }, assemblyName: "Project3"); comp3.VerifyDiagnostics( // (2,7): error CS0012: The type 'System.Drawing.Point' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Drawing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class D : C, I { } Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("System.Drawing.Point", "System.Drawing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } } [ClrOnlyFact] public void MissingTypeInTypeArgumentsOfImplementedInterface() { var lib1 = CreateCompilation(@" namespace ErrorTest { public interface I1<out T1> {} public interface I2 {} public interface I6<in T1> {} public class C10<T> where T : I1<I2> {} }", options: TestOptions.ReleaseDll, assemblyName: "MissingTypeInTypeArgumentsOfImplementedInterface1"); var lib1Ref = new CSharpCompilationReference(lib1); var lib2 = CreateCompilation(@" namespace ErrorTest { public interface I3 : I2 {} }", new[] { lib1Ref }, TestOptions.ReleaseDll, assemblyName: "MissingTypeInTypeArgumentsOfImplementedInterface2"); var lib2Ref = new CSharpCompilationReference(lib2); var lib3 = CreateCompilation(@" namespace ErrorTest { public class C4 : I1<I3> {} public interface I5 : I1<I3> {} public class C8<T> where T : I6<I3> {} }", new[] { lib1Ref, lib2Ref }, TestOptions.ReleaseDll, assemblyName: "MissingTypeInTypeArgumentsOfImplementedInterface3"); var lib3Ref = new CSharpCompilationReference(lib3); var lib4Def = @" namespace ErrorTest { class Test { void _Test(C4 y) { I1<I2> x = y; } } public class C6 : I5 {} public class C7 : C4 {} class Test3<T> where T : C4 { void Test(T y3) { I1<I2> x = y3; } } class Test4<T> where T : I5 { void Test(T y4) { I1<I2> x = y4; } } class Test5 { void Test(I5 y5) { I1<I2> x = y5; } } public class C9 : C8<I6<I2>> {} public class C11 : C10<C4> {} public class C12 : C10<I5> {} class Test6 { void Test(C8<I6<I2>> x) {} void Test(C10<C4> x) {} void Test(C10<I5> x) {} } }"; var lib4 = CreateCompilation(lib4Def, new[] { lib1Ref, lib3Ref }, TestOptions.ReleaseDll); DiagnosticDescription[] expectedErrors = { // (52,18): error CS0311: The type 'ErrorTest.I5' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C10<T>'. There is no implicit reference conversion from 'ErrorTest.I5' to 'ErrorTest.I1<ErrorTest.I2>'. // public class C12 Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "C12").WithArguments("ErrorTest.C10<T>", "ErrorTest.I1<ErrorTest.I2>", "T", "ErrorTest.I5"), // (52,18): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C12 Diagnostic(ErrorCode.ERR_NoTypeDef, "C12").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (44,18): error CS0311: The type 'ErrorTest.I6<ErrorTest.I2>' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C8<T>'. There is no implicit reference conversion from 'ErrorTest.I6<ErrorTest.I2>' to 'ErrorTest.I6<ErrorTest.I3>'. // public class C9 Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "C9").WithArguments("ErrorTest.C8<T>", "ErrorTest.I6<ErrorTest.I3>", "T", "ErrorTest.I6<ErrorTest.I2>"), // (44,18): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C9 Diagnostic(ErrorCode.ERR_NoTypeDef, "C9").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (48,18): error CS0311: The type 'ErrorTest.C4' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C10<T>'. There is no implicit reference conversion from 'ErrorTest.C4' to 'ErrorTest.I1<ErrorTest.I2>'. // public class C11 Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "C11").WithArguments("ErrorTest.C10<T>", "ErrorTest.I1<ErrorTest.I2>", "T", "ErrorTest.C4"), // (48,18): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C11 Diagnostic(ErrorCode.ERR_NoTypeDef, "C11").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (12,18): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C6 Diagnostic(ErrorCode.ERR_NoTypeDef, "C6").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (60,27): error CS0311: The type 'ErrorTest.C4' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C10<T>'. There is no implicit reference conversion from 'ErrorTest.C4' to 'ErrorTest.I1<ErrorTest.I2>'. // void Test(C10<C4> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "x").WithArguments("ErrorTest.C10<T>", "ErrorTest.I1<ErrorTest.I2>", "T", "ErrorTest.C4"), // (60,27): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C10<C4> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (62,27): error CS0311: The type 'ErrorTest.I5' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C10<T>'. There is no implicit reference conversion from 'ErrorTest.I5' to 'ErrorTest.I1<ErrorTest.I2>'. // void Test(C10<I5> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "x").WithArguments("ErrorTest.C10<T>", "ErrorTest.I1<ErrorTest.I2>", "T", "ErrorTest.I5"), // (62,27): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C10<I5> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (58,30): error CS0311: The type 'ErrorTest.I6<ErrorTest.I2>' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C8<T>'. There is no implicit reference conversion from 'ErrorTest.I6<ErrorTest.I2>' to 'ErrorTest.I6<ErrorTest.I3>'. // void Test(C8<I6<I2>> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "x").WithArguments("ErrorTest.C8<T>", "ErrorTest.I6<ErrorTest.I3>", "T", "ErrorTest.I6<ErrorTest.I2>"), // (58,30): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C8<I6<I2>> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (32,24): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1<I2> x = y4; Diagnostic(ErrorCode.ERR_NoTypeDef, "y4").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (32,24): error CS0266: Cannot implicitly convert type 'T' to 'ErrorTest.I1<ErrorTest.I2>'. An explicit conversion exists (are you missing a cast?) // I1<I2> x = y4; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y4").WithArguments("T", "ErrorTest.I1<ErrorTest.I2>"), // (40,24): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1<I2> x = y5; Diagnostic(ErrorCode.ERR_NoTypeDef, "y5").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (40,24): error CS0266: Cannot implicitly convert type 'ErrorTest.I5' to 'ErrorTest.I1<ErrorTest.I2>'. An explicit conversion exists (are you missing a cast?) // I1<I2> x = y5; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y5").WithArguments("ErrorTest.I5", "ErrorTest.I1<ErrorTest.I2>"), // (24,24): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1<I2> x = y3; Diagnostic(ErrorCode.ERR_NoTypeDef, "y3").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (24,24): error CS0266: Cannot implicitly convert type 'T' to 'ErrorTest.I1<ErrorTest.I2>'. An explicit conversion exists (are you missing a cast?) // I1<I2> x = y3; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y3").WithArguments("T", "ErrorTest.I1<ErrorTest.I2>"), // (8,24): error CS0012: The type 'ErrorTest.I3' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1<I2> x = y; Diagnostic(ErrorCode.ERR_NoTypeDef, "y").WithArguments("ErrorTest.I3", "MissingTypeInTypeArgumentsOfImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,24): error CS0266: Cannot implicitly convert type 'ErrorTest.C4' to 'ErrorTest.I1<ErrorTest.I2>'. An explicit conversion exists (are you missing a cast?) // I1<I2> x = y; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("ErrorTest.C4", "ErrorTest.I1<ErrorTest.I2>") }; lib4.VerifyDiagnostics(expectedErrors); lib4 = CreateCompilation(lib4Def, new[] { lib1Ref, lib2Ref, lib3Ref }, TestOptions.ReleaseDll); CompileAndVerify(lib4).VerifyDiagnostics(); lib4 = CreateCompilation(lib4Def, new[] { lib1.EmitToImageReference(), lib3.EmitToImageReference() }, TestOptions.ReleaseDll); lib4.VerifyDiagnostics(expectedErrors); } [Fact()] public void MissingImplementedInterface() { var lib1 = CreateCompilation(@" namespace ErrorTest { public interface I1 { void M1(); } public class C9<T> where T : I1 { } } ", options: TestOptions.ReleaseDll, assemblyName: "MissingImplementedInterface1"); var lib1Ref = new CSharpCompilationReference(lib1); var lib2 = CreateCompilation(@" namespace ErrorTest { public interface I2 : I1 {} public class C12 : I2 { private void M1() //Implements I1.M1 {} void I1.M1() { } } } ", new[] { lib1Ref }, TestOptions.ReleaseDll, assemblyName: "MissingImplementedInterface2"); var lib2Ref = new CSharpCompilationReference(lib2); var lib3 = CreateCompilation(@" namespace ErrorTest { public class C4 : I2 { private void M1() //Implements I1.M1 {} void I1.M1() { } } public interface I5 : I2 {} public class C13 : C12 { } } ", new[] { lib1Ref, lib2Ref }, TestOptions.ReleaseDll, assemblyName: "MissingImplementedInterface3"); var lib3Ref = new CSharpCompilationReference(lib3); var lib4Def = @" namespace ErrorTest { class Test { void _Test(C4 y) { I1 x = y; } } public class C6 : I5 { void I1.M1() {} } public class C7 : C4 {} class Test2 { void _Test2(I5 x, C4 y) { x.M1(); y.M1(); } } class Test3<T> where T : C4 { void Test(T y3) { I1 x = y3; y3.M1(); } } class Test4<T> where T : I5 { void Test(T y4) { I1 x = y4; y4.M1(); } } public class C8 : I5 { void I1.M1() {} } public class C10 : C9<C4> {} public class C11 : C9<I5> {} class Test5 { void Test(C9<C4> x) { } void Test(C9<I5> x) { } void Test(C13 c13) { I1 x = c13; } } } "; var lib4 = CreateCompilation(lib4Def, new[] { lib1Ref, lib3Ref }, TestOptions.ReleaseDll); lib4.VerifyDiagnostics( // (48,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C8 : I5 Diagnostic(ErrorCode.ERR_NoTypeDef, "C8").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (12,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C6 : I5 Diagnostic(ErrorCode.ERR_NoTypeDef, "C6").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (50,14): error CS0540: 'ErrorTest.C8.ErrorTest.I1.M1()': containing type does not implement interface 'ErrorTest.I1' // void I1.M1() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("ErrorTest.C8.ErrorTest.I1.M1()", "ErrorTest.I1"), // (14,14): error CS0540: 'ErrorTest.C6.ErrorTest.I1.M1()': containing type does not implement interface 'ErrorTest.I1' // void I1.M1() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("ErrorTest.C6.ErrorTest.I1.M1()", "ErrorTest.I1"), // (54,18): error CS0311: The type 'ErrorTest.C4' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C9<T>'. There is no implicit reference conversion from 'ErrorTest.C4' to 'ErrorTest.I1'. // public class C10 : C9<C4> Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "C10").WithArguments("ErrorTest.C9<T>", "ErrorTest.I1", "T", "ErrorTest.C4"), // (54,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C10 : C9<C4> Diagnostic(ErrorCode.ERR_NoTypeDef, "C10").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (57,18): error CS0311: The type 'ErrorTest.I5' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C9<T>'. There is no implicit reference conversion from 'ErrorTest.I5' to 'ErrorTest.I1'. // public class C11 : C9<I5> Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "C11").WithArguments("ErrorTest.C9<T>", "ErrorTest.I1", "T", "ErrorTest.I5"), // (57,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C11 : C9<I5> Diagnostic(ErrorCode.ERR_NoTypeDef, "C11").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (64,26): error CS0311: The type 'ErrorTest.I5' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C9<T>'. There is no implicit reference conversion from 'ErrorTest.I5' to 'ErrorTest.I1'. // void Test(C9<I5> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "x").WithArguments("ErrorTest.C9<T>", "ErrorTest.I1", "T", "ErrorTest.I5"), // (64,26): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C9<I5> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (62,26): error CS0311: The type 'ErrorTest.C4' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C9<T>'. There is no implicit reference conversion from 'ErrorTest.C4' to 'ErrorTest.I1'. // void Test(C9<C4> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "x").WithArguments("ErrorTest.C9<T>", "ErrorTest.I1", "T", "ErrorTest.C4"), // (62,26): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C9<C4> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (69,20): error CS0012: The type 'ErrorTest.C12' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = c13; Diagnostic(ErrorCode.ERR_NoTypeDef, "c13").WithArguments("ErrorTest.C12", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (69,20): error CS0266: Cannot implicitly convert type 'ErrorTest.C13' to 'ErrorTest.I1'. An explicit conversion exists (are you missing a cast?) // I1 x = c13; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "c13").WithArguments("ErrorTest.C13", "ErrorTest.I1"), // (8,20): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = y; Diagnostic(ErrorCode.ERR_NoTypeDef, "y").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,20): error CS0266: Cannot implicitly convert type 'ErrorTest.C4' to 'ErrorTest.I1'. An explicit conversion exists (are you missing a cast?) // I1 x = y; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("ErrorTest.C4", "ErrorTest.I1"), // (34,20): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = y3; Diagnostic(ErrorCode.ERR_NoTypeDef, "y3").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (34,20): error CS0266: Cannot implicitly convert type 'T' to 'ErrorTest.I1'. An explicit conversion exists (are you missing a cast?) // I1 x = y3; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y3").WithArguments("T", "ErrorTest.I1"), // (35,16): error CS0122: 'ErrorTest.C4.M1()' is inaccessible due to its protection level // y3.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("ErrorTest.C4.M1()"), // (25,15): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // x.M1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "M1").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (25,15): error CS1061: 'ErrorTest.I5' does not contain a definition for 'M1' and no extension method 'M1' accepting a first argument of type 'ErrorTest.I5' could be found (are you missing a using directive or an assembly reference?) // x.M1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("ErrorTest.I5", "M1"), // (26,15): error CS0122: 'ErrorTest.C4.M1()' is inaccessible due to its protection level // y.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("ErrorTest.C4.M1()"), // (43,20): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = y4; Diagnostic(ErrorCode.ERR_NoTypeDef, "y4").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (43,20): error CS0266: Cannot implicitly convert type 'T' to 'ErrorTest.I1'. An explicit conversion exists (are you missing a cast?) // I1 x = y4; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y4").WithArguments("T", "ErrorTest.I1"), // (44,16): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // y4.M1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "M1").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (44,16): error CS1061: 'T' does not contain a definition for 'M1' and no extension method 'M1' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // y4.M1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("T", "M1") ); lib4 = CreateCompilation(lib4Def, new[] { lib1Ref, lib2Ref, lib3Ref }, TestOptions.ReleaseDll); lib4.VerifyDiagnostics( // (35,16): error CS0122: 'ErrorTest.C4.M1()' is inaccessible due to its protection level // y3.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("ErrorTest.C4.M1()"), // (26,15): error CS0122: 'ErrorTest.C4.M1()' is inaccessible due to its protection level // y.M1(); Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("ErrorTest.C4.M1()") ); lib4 = CreateCompilation(lib4Def, new[] { lib1.EmitToImageReference(), lib3.EmitToImageReference() }, TestOptions.ReleaseDll); lib4.VerifyDiagnostics( // (12,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C6 : I5 Diagnostic(ErrorCode.ERR_NoTypeDef, "C6").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (48,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C8 : I5 Diagnostic(ErrorCode.ERR_NoTypeDef, "C8").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (64,26): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C9<I5> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (62,26): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C9<C4> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (54,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C10 : C9<C4> Diagnostic(ErrorCode.ERR_NoTypeDef, "C10").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (57,18): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C11 : C9<I5> Diagnostic(ErrorCode.ERR_NoTypeDef, "C11").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,20): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = y; Diagnostic(ErrorCode.ERR_NoTypeDef, "y").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (69,20): error CS0012: The type 'ErrorTest.C12' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = c13; Diagnostic(ErrorCode.ERR_NoTypeDef, "c13").WithArguments("ErrorTest.C12", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (69,20): error CS0266: Cannot implicitly convert type 'ErrorTest.C13' to 'ErrorTest.I1'. An explicit conversion exists (are you missing a cast?) // I1 x = c13; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "c13").WithArguments("ErrorTest.C13", "ErrorTest.I1"), // (34,20): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = y3; Diagnostic(ErrorCode.ERR_NoTypeDef, "y3").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (35,16): error CS1061: 'T' does not contain a definition for 'M1' and no extension method 'M1' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // y3.M1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("T", "M1"), // (43,20): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // I1 x = y4; Diagnostic(ErrorCode.ERR_NoTypeDef, "y4").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (44,16): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // y4.M1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "M1").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (25,15): error CS0012: The type 'ErrorTest.I2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // x.M1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "M1").WithArguments("ErrorTest.I2", "MissingImplementedInterface2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (26,15): error CS1061: 'ErrorTest.C4' does not contain a definition for 'M1' and no extension method 'M1' accepting a first argument of type 'ErrorTest.C4' could be found (are you missing a using directive or an assembly reference?) // y.M1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("ErrorTest.C4", "M1") ); } [ClrOnlyFact] public void MissingBaseClass() { var lib1 = CreateCompilation(@" namespace ErrorTest { public class C1 { public void M1() {} } public class C6<T> where T : C1 {} }", options: TestOptions.ReleaseDll, assemblyName: "MissingBaseClass1"); var lib1Ref = new CSharpCompilationReference(lib1); var lib2 = CreateCompilation(@" namespace ErrorTest { public class C2 : C1 {} }", new[] { lib1Ref }, TestOptions.ReleaseDll, assemblyName: "MissingBaseClass2"); var lib2Ref = new CSharpCompilationReference(lib2); var lib3 = CreateCompilation(@" namespace ErrorTest { public class C4 : C2 {} }", new[] { lib1Ref, lib2Ref }, TestOptions.ReleaseDll, assemblyName: "MissingBaseClass3"); var lib3Ref = new CSharpCompilationReference(lib3); var lib4Def = @" namespace ErrorTest { class Test { void _Test(C4 y) { C1 x = y; } } public class C5 : C4 {} class Test2 { void _Test2(C4 y) { y.M1(); } } class Test3<T> where T : C4 { void Test(T y3) { C1 x = y3; y3.M1(); } } public class C7 : C6<C4> {} class Test4 { void Test(C6<C4> x) { } } }"; var lib4 = CreateCompilation(lib4Def, new[] { lib1Ref, lib3Ref }, TestOptions.ReleaseDll); DiagnosticDescription[] expectedErrors = { // (12,23): error CS0012: The type 'ErrorTest.C2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C5 : C4 Diagnostic(ErrorCode.ERR_NoTypeDef, "C4").WithArguments("ErrorTest.C2", "MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (32,18): error CS0311: The type 'ErrorTest.C4' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C6<T>'. There is no implicit reference conversion from 'ErrorTest.C4' to 'ErrorTest.C1'. // public class C7 : C6<C4> Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "C7").WithArguments("ErrorTest.C6<T>", "ErrorTest.C1", "T", "ErrorTest.C4"), // (32,18): error CS0012: The type 'ErrorTest.C2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class C7 : C6<C4> Diagnostic(ErrorCode.ERR_NoTypeDef, "C7").WithArguments("ErrorTest.C2", "MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (37,26): error CS0311: The type 'ErrorTest.C4' cannot be used as type parameter 'T' in the generic type or method 'ErrorTest.C6<T>'. There is no implicit reference conversion from 'ErrorTest.C4' to 'ErrorTest.C1'. // void Test(C6<C4> x) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "x").WithArguments("ErrorTest.C6<T>", "ErrorTest.C1", "T", "ErrorTest.C4"), // (37,26): error CS0012: The type 'ErrorTest.C2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // void Test(C6<C4> x) Diagnostic(ErrorCode.ERR_NoTypeDef, "x").WithArguments("ErrorTest.C2", "MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (19,15): error CS0012: The type 'ErrorTest.C2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // y.M1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "M1").WithArguments("ErrorTest.C2", "MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (19,15): error CS1061: 'ErrorTest.C4' does not contain a definition for 'M1' and no extension method 'M1' accepting a first argument of type 'ErrorTest.C4' could be found (are you missing a using directive or an assembly reference?) // y.M1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("ErrorTest.C4", "M1"), // (8,20): error CS0012: The type 'ErrorTest.C2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // C1 x = y; Diagnostic(ErrorCode.ERR_NoTypeDef, "y").WithArguments("ErrorTest.C2", "MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,20): error CS0029: Cannot implicitly convert type 'ErrorTest.C4' to 'ErrorTest.C1' // C1 x = y; Diagnostic(ErrorCode.ERR_NoImplicitConv, "y").WithArguments("ErrorTest.C4", "ErrorTest.C1"), // (27,20): error CS0012: The type 'ErrorTest.C2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // C1 x = y3; Diagnostic(ErrorCode.ERR_NoTypeDef, "y3").WithArguments("ErrorTest.C2", "MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (27,20): error CS0029: Cannot implicitly convert type 'T' to 'ErrorTest.C1' // C1 x = y3; Diagnostic(ErrorCode.ERR_NoImplicitConv, "y3").WithArguments("T", "ErrorTest.C1"), // (28,16): error CS0012: The type 'ErrorTest.C2' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // y3.M1(); Diagnostic(ErrorCode.ERR_NoTypeDef, "M1").WithArguments("ErrorTest.C2", "MissingBaseClass2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (28,16): error CS1061: 'T' does not contain a definition for 'M1' and no extension method 'M1' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // y3.M1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M1").WithArguments("T", "M1") }; lib4.VerifyDiagnostics(expectedErrors); lib4 = CreateCompilation(lib4Def, new[] { lib1Ref, lib2Ref, lib3Ref }, TestOptions.ReleaseDll); CompileAndVerify(lib4).VerifyDiagnostics(); lib4 = CreateCompilation(lib4Def, new[] { lib1.EmitToImageReference(), lib3.EmitToImageReference() }, TestOptions.ReleaseDll); lib4.VerifyDiagnostics(expectedErrors); } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Features/CSharp/Portable/Organizing/CSharpOrganizingService.Rewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.CSharp.Organizing { internal partial class CSharpOrganizingService { private class Rewriter : CSharpSyntaxRewriter { private readonly Func<SyntaxNode, IEnumerable<ISyntaxOrganizer>> _nodeToOrganizersGetter; private readonly SemanticModel _semanticModel; private readonly CancellationToken _cancellationToken; public Rewriter(CSharpOrganizingService treeOrganizer, IEnumerable<ISyntaxOrganizer> organizers, SemanticModel semanticModel, CancellationToken cancellationToken) { _nodeToOrganizersGetter = treeOrganizer.GetNodeToOrganizers(organizers.ToList()); _semanticModel = semanticModel; _cancellationToken = cancellationToken; } public override SyntaxNode DefaultVisit(SyntaxNode node) { _cancellationToken.ThrowIfCancellationRequested(); return node; } public override SyntaxNode Visit(SyntaxNode node) { _cancellationToken.ThrowIfCancellationRequested(); if (node == null) { return null; } // First, recurse into our children, updating them. node = base.Visit(node); // Now, try to update this new node itself. var organizers = _nodeToOrganizersGetter(node); foreach (var organizer in organizers) { node = organizer.OrganizeNode(_semanticModel, node, _cancellationToken); } return node; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.CSharp.Organizing { internal partial class CSharpOrganizingService { private class Rewriter : CSharpSyntaxRewriter { private readonly Func<SyntaxNode, IEnumerable<ISyntaxOrganizer>> _nodeToOrganizersGetter; private readonly SemanticModel _semanticModel; private readonly CancellationToken _cancellationToken; public Rewriter(CSharpOrganizingService treeOrganizer, IEnumerable<ISyntaxOrganizer> organizers, SemanticModel semanticModel, CancellationToken cancellationToken) { _nodeToOrganizersGetter = treeOrganizer.GetNodeToOrganizers(organizers.ToList()); _semanticModel = semanticModel; _cancellationToken = cancellationToken; } public override SyntaxNode DefaultVisit(SyntaxNode node) { _cancellationToken.ThrowIfCancellationRequested(); return node; } public override SyntaxNode Visit(SyntaxNode node) { _cancellationToken.ThrowIfCancellationRequested(); if (node == null) { return null; } // First, recurse into our children, updating them. node = base.Visit(node); // Now, try to update this new node itself. var organizers = _nodeToOrganizersGetter(node); foreach (var organizer in organizers) { node = organizer.OrganizeNode(_semanticModel, node, _cancellationToken); } return node; } } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Compilers/Server/VBCSCompiler/NamedPipeClientConnection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Runtime.CompilerServices; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using System.Security.AccessControl; namespace Microsoft.CodeAnalysis.CompilerServer { internal sealed class NamedPipeClientConnection : IClientConnection { private CancellationTokenSource DisconnectCancellationTokenSource { get; } = new CancellationTokenSource(); private TaskCompletionSource<object> DisconnectTaskCompletionSource { get; } = new TaskCompletionSource<object>(); public NamedPipeServerStream Stream { get; } public ICompilerServerLogger Logger { get; } public bool IsDisposed { get; private set; } public Task DisconnectTask => DisconnectTaskCompletionSource.Task; internal NamedPipeClientConnection(NamedPipeServerStream stream, ICompilerServerLogger logger) { Stream = stream; Logger = logger; } public void Dispose() { if (!IsDisposed) { try { DisconnectTaskCompletionSource.TrySetResult(new object()); DisconnectCancellationTokenSource.Cancel(); Stream.Close(); } catch (Exception ex) { Logger.LogException(ex, $"Error closing client connection"); } IsDisposed = true; } } public async Task<BuildRequest> ReadBuildRequestAsync(CancellationToken cancellationToken) { var request = await BuildRequest.ReadAsync(Stream, cancellationToken).ConfigureAwait(false); // Now that we've read data from the stream we can validate the identity. if (!NamedPipeUtil.CheckClientElevationMatches(Stream)) { throw new Exception("Client identity does not match server identity."); } // The result is deliberately discarded here. The idea is to kick off the monitor code and // when it completes it will trigger the task. Don't want to block on that here. _ = MonitorDisconnect(); return request; async Task MonitorDisconnect() { try { await BuildServerConnection.MonitorDisconnectAsync(Stream, request.RequestId, Logger, DisconnectCancellationTokenSource.Token).ConfigureAwait(false); } catch (Exception ex) { Logger.LogException(ex, $"Error monitoring disconnect {request.RequestId}"); } finally { DisconnectTaskCompletionSource.TrySetResult(this); } } } public Task WriteBuildResponseAsync(BuildResponse response, CancellationToken cancellationToken) => response.WriteAsync(Stream, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Runtime.CompilerServices; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using System.Security.AccessControl; namespace Microsoft.CodeAnalysis.CompilerServer { internal sealed class NamedPipeClientConnection : IClientConnection { private CancellationTokenSource DisconnectCancellationTokenSource { get; } = new CancellationTokenSource(); private TaskCompletionSource<object> DisconnectTaskCompletionSource { get; } = new TaskCompletionSource<object>(); public NamedPipeServerStream Stream { get; } public ICompilerServerLogger Logger { get; } public bool IsDisposed { get; private set; } public Task DisconnectTask => DisconnectTaskCompletionSource.Task; internal NamedPipeClientConnection(NamedPipeServerStream stream, ICompilerServerLogger logger) { Stream = stream; Logger = logger; } public void Dispose() { if (!IsDisposed) { try { DisconnectTaskCompletionSource.TrySetResult(new object()); DisconnectCancellationTokenSource.Cancel(); Stream.Close(); } catch (Exception ex) { Logger.LogException(ex, $"Error closing client connection"); } IsDisposed = true; } } public async Task<BuildRequest> ReadBuildRequestAsync(CancellationToken cancellationToken) { var request = await BuildRequest.ReadAsync(Stream, cancellationToken).ConfigureAwait(false); // Now that we've read data from the stream we can validate the identity. if (!NamedPipeUtil.CheckClientElevationMatches(Stream)) { throw new Exception("Client identity does not match server identity."); } // The result is deliberately discarded here. The idea is to kick off the monitor code and // when it completes it will trigger the task. Don't want to block on that here. _ = MonitorDisconnect(); return request; async Task MonitorDisconnect() { try { await BuildServerConnection.MonitorDisconnectAsync(Stream, request.RequestId, Logger, DisconnectCancellationTokenSource.Token).ConfigureAwait(false); } catch (Exception ex) { Logger.LogException(ex, $"Error monitoring disconnect {request.RequestId}"); } finally { DisconnectTaskCompletionSource.TrySetResult(this); } } } public Task WriteBuildResponseAsync(BuildResponse response, CancellationToken cancellationToken) => response.WriteAsync(Stream, cancellationToken); } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Features/Core/Portable/Completion/Providers/AbstractObjectInitializerCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractObjectInitializerCompletionProvider : LSPCompletionProvider { protected abstract Tuple<ITypeSymbol, Location> GetInitializedType(Document document, SemanticModel semanticModel, int position, CancellationToken cancellationToken); protected abstract HashSet<string> GetInitializedMembers(SyntaxTree tree, int position, CancellationToken cancellationToken); protected abstract string EscapeIdentifier(ISymbol symbol); public override async Task ProvideCompletionsAsync(CompletionContext context) { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); if (!(GetInitializedType(document, semanticModel, position, cancellationToken) is var (type, initializerLocation))) { return; } if (type is ITypeParameterSymbol typeParameterSymbol) { type = typeParameterSymbol.GetNamedTypeSymbolConstraint(); } if (type is not INamedTypeSymbol initializedType) { return; } if (await IsExclusiveAsync(document, position, cancellationToken).ConfigureAwait(false)) { context.IsExclusive = true; } var enclosing = semanticModel.GetEnclosingNamedType(position, cancellationToken); // Find the members that can be initialized. If we have a NamedTypeSymbol, also get the overridden members. IEnumerable<ISymbol> members = semanticModel.LookupSymbols(position, initializedType); members = members.Where(m => IsInitializable(m, enclosing) && m.CanBeReferencedByName && IsLegalFieldOrProperty(m) && !m.IsImplicitlyDeclared); // Filter out those members that have already been typed var alreadyTypedMembers = GetInitializedMembers(semanticModel.SyntaxTree, position, cancellationToken); var uninitializedMembers = members.Where(m => !alreadyTypedMembers.Contains(m.Name)); uninitializedMembers = uninitializedMembers.Where(m => m.IsEditorBrowsable(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)); foreach (var uninitializedMember in uninitializedMembers) { context.AddItem(SymbolCompletionItem.CreateWithSymbolId( displayText: EscapeIdentifier(uninitializedMember), displayTextSuffix: "", insertionText: null, symbols: ImmutableArray.Create(uninitializedMember), contextPosition: initializerLocation.SourceSpan.Start, rules: s_rules)); } } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); protected abstract Task<bool> IsExclusiveAsync(Document document, int position, CancellationToken cancellationToken); private static bool IsLegalFieldOrProperty(ISymbol symbol) { return symbol.IsWriteableFieldOrProperty() || symbol.ContainingType.IsAnonymousType || CanSupportObjectInitializer(symbol); } private static readonly CompletionItemRules s_rules = CompletionItemRules.Create(enterKeyRule: EnterKeyRule.Never); protected virtual bool IsInitializable(ISymbol member, INamedTypeSymbol containingType) { return !member.IsStatic && member.MatchesKind(SymbolKind.Field, SymbolKind.Property) && member.IsAccessibleWithin(containingType); } private static bool CanSupportObjectInitializer(ISymbol symbol) { Debug.Assert(!symbol.IsWriteableFieldOrProperty(), "Assertion failed - expected writable field/property check before calling this method."); if (symbol is IFieldSymbol fieldSymbol) { return !fieldSymbol.Type.IsStructType(); } else if (symbol is IPropertySymbol propertySymbol) { return !propertySymbol.Type.IsStructType(); } 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractObjectInitializerCompletionProvider : LSPCompletionProvider { protected abstract Tuple<ITypeSymbol, Location> GetInitializedType(Document document, SemanticModel semanticModel, int position, CancellationToken cancellationToken); protected abstract HashSet<string> GetInitializedMembers(SyntaxTree tree, int position, CancellationToken cancellationToken); protected abstract string EscapeIdentifier(ISymbol symbol); public override async Task ProvideCompletionsAsync(CompletionContext context) { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); if (!(GetInitializedType(document, semanticModel, position, cancellationToken) is var (type, initializerLocation))) { return; } if (type is ITypeParameterSymbol typeParameterSymbol) { type = typeParameterSymbol.GetNamedTypeSymbolConstraint(); } if (type is not INamedTypeSymbol initializedType) { return; } if (await IsExclusiveAsync(document, position, cancellationToken).ConfigureAwait(false)) { context.IsExclusive = true; } var enclosing = semanticModel.GetEnclosingNamedType(position, cancellationToken); // Find the members that can be initialized. If we have a NamedTypeSymbol, also get the overridden members. IEnumerable<ISymbol> members = semanticModel.LookupSymbols(position, initializedType); members = members.Where(m => IsInitializable(m, enclosing) && m.CanBeReferencedByName && IsLegalFieldOrProperty(m) && !m.IsImplicitlyDeclared); // Filter out those members that have already been typed var alreadyTypedMembers = GetInitializedMembers(semanticModel.SyntaxTree, position, cancellationToken); var uninitializedMembers = members.Where(m => !alreadyTypedMembers.Contains(m.Name)); uninitializedMembers = uninitializedMembers.Where(m => m.IsEditorBrowsable(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)); foreach (var uninitializedMember in uninitializedMembers) { context.AddItem(SymbolCompletionItem.CreateWithSymbolId( displayText: EscapeIdentifier(uninitializedMember), displayTextSuffix: "", insertionText: null, symbols: ImmutableArray.Create(uninitializedMember), contextPosition: initializerLocation.SourceSpan.Start, rules: s_rules)); } } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); protected abstract Task<bool> IsExclusiveAsync(Document document, int position, CancellationToken cancellationToken); private static bool IsLegalFieldOrProperty(ISymbol symbol) { return symbol.IsWriteableFieldOrProperty() || symbol.ContainingType.IsAnonymousType || CanSupportObjectInitializer(symbol); } private static readonly CompletionItemRules s_rules = CompletionItemRules.Create(enterKeyRule: EnterKeyRule.Never); protected virtual bool IsInitializable(ISymbol member, INamedTypeSymbol containingType) { return !member.IsStatic && member.MatchesKind(SymbolKind.Field, SymbolKind.Property) && member.IsAccessibleWithin(containingType); } private static bool CanSupportObjectInitializer(ISymbol symbol) { Debug.Assert(!symbol.IsWriteableFieldOrProperty(), "Assertion failed - expected writable field/property check before calling this method."); if (symbol is IFieldSymbol fieldSymbol) { return !fieldSymbol.Type.IsStructType(); } else if (symbol is IPropertySymbol propertySymbol) { return !propertySymbol.Type.IsStructType(); } throw ExceptionUtilities.Unreachable; } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Compilers/Test/Core/Metadata/PEModuleTestHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Reflection.Metadata; using Microsoft.CodeAnalysis; namespace Roslyn.Test.Utilities { /// <summary> /// Helpers to test metadata. /// </summary> internal static class PEModuleTestHelpers { internal static MetadataReader GetMetadataReader(this PEModule module) { return module.MetadataReader; } internal static MetadataReader GetMetadataReader(this PEAssembly assembly) { return assembly.ManifestModule.MetadataReader; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Reflection.Metadata; using Microsoft.CodeAnalysis; namespace Roslyn.Test.Utilities { /// <summary> /// Helpers to test metadata. /// </summary> internal static class PEModuleTestHelpers { internal static MetadataReader GetMetadataReader(this PEModule module) { return module.MetadataReader; } internal static MetadataReader GetMetadataReader(this PEAssembly assembly) { return assembly.ManifestModule.MetadataReader; } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/DefaultKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class DefaultKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public DefaultKeywordRecommender() : base(SyntaxKind.DefaultKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return IsValidPreProcessorContext(context) || context.IsStatementContext || context.IsGlobalStatementContext || context.IsAnyExpressionContext || context.TargetToken.IsSwitchLabelContext() || context.SyntaxTree.IsTypeParameterConstraintStartContext(position, context.LeftToken); } private static bool IsValidPreProcessorContext(CSharpSyntaxContext context) { // cases: // #line | // #line d| // # line | // # line d| var previousToken1 = context.TargetToken; var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true); return previousToken1.Kind() == SyntaxKind.LineKeyword && previousToken2.Kind() == SyntaxKind.HashToken; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class DefaultKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public DefaultKeywordRecommender() : base(SyntaxKind.DefaultKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return IsValidPreProcessorContext(context) || context.IsStatementContext || context.IsGlobalStatementContext || context.IsAnyExpressionContext || context.TargetToken.IsSwitchLabelContext() || context.SyntaxTree.IsTypeParameterConstraintStartContext(position, context.LeftToken); } private static bool IsValidPreProcessorContext(CSharpSyntaxContext context) { // cases: // #line | // #line d| // # line | // # line d| var previousToken1 = context.TargetToken; var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true); return previousToken1.Kind() == SyntaxKind.LineKeyword && previousToken2.Kind() == SyntaxKind.HashToken; } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractAggregatedFormattingResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract class AbstractAggregatedFormattingResult : IFormattingResult { protected readonly SyntaxNode Node; private readonly IList<AbstractFormattingResult> _formattingResults; private readonly SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? _formattingSpans; private readonly CancellableLazy<IList<TextChange>> _lazyTextChanges; private readonly CancellableLazy<SyntaxNode> _lazyNode; public AbstractAggregatedFormattingResult( SyntaxNode node, IList<AbstractFormattingResult> formattingResults, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? formattingSpans) { Contract.ThrowIfNull(node); Contract.ThrowIfNull(formattingResults); this.Node = node; _formattingResults = formattingResults; _formattingSpans = formattingSpans; _lazyTextChanges = new CancellableLazy<IList<TextChange>>(CreateTextChanges); _lazyNode = new CancellableLazy<SyntaxNode>(CreateFormattedRoot); } /// <summary> /// rewrite the node with the given trivia information in the map /// </summary> protected abstract SyntaxNode Rewriter(Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> changeMap, CancellationToken cancellationToken); protected SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector> GetFormattingSpans() => _formattingSpans ?? SimpleIntervalTree.Create(new TextSpanIntervalIntrospector(), _formattingResults.Select(r => r.FormattedSpan)); #region IFormattingResult implementation public bool ContainsChanges { get { return this.GetTextChanges(CancellationToken.None).Count > 0; } } public IList<TextChange> GetTextChanges(CancellationToken cancellationToken) => _lazyTextChanges.GetValue(cancellationToken); public SyntaxNode GetFormattedRoot(CancellationToken cancellationToken) => _lazyNode.GetValue(cancellationToken); private IList<TextChange> CreateTextChanges(CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Formatting_AggregateCreateTextChanges, cancellationToken)) { // quick check var changes = CreateTextChangesWorker(cancellationToken); // formatted spans and formatting spans are different, filter returns to formatting span return _formattingSpans == null ? changes : changes.Where(s => _formattingSpans.HasIntervalThatIntersectsWith(s.Span)).ToList(); } } private IList<TextChange> CreateTextChangesWorker(CancellationToken cancellationToken) { if (_formattingResults.Count == 1) { return _formattingResults[0].GetTextChanges(cancellationToken); } // pre-allocate list var count = _formattingResults.Sum(r => r.GetTextChanges(cancellationToken).Count); var result = new List<TextChange>(count); foreach (var formattingResult in _formattingResults) { result.AddRange(formattingResult.GetTextChanges(cancellationToken)); } return result; } private SyntaxNode CreateFormattedRoot(CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Formatting_AggregateCreateFormattedRoot, cancellationToken)) { // create a map var map = new Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData>(); _formattingResults.Do(result => result.GetChanges(cancellationToken).Do(change => map.Add(change.Item1, change.Item2))); return Rewriter(map, cancellationToken); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract class AbstractAggregatedFormattingResult : IFormattingResult { protected readonly SyntaxNode Node; private readonly IList<AbstractFormattingResult> _formattingResults; private readonly SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? _formattingSpans; private readonly CancellableLazy<IList<TextChange>> _lazyTextChanges; private readonly CancellableLazy<SyntaxNode> _lazyNode; public AbstractAggregatedFormattingResult( SyntaxNode node, IList<AbstractFormattingResult> formattingResults, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? formattingSpans) { Contract.ThrowIfNull(node); Contract.ThrowIfNull(formattingResults); this.Node = node; _formattingResults = formattingResults; _formattingSpans = formattingSpans; _lazyTextChanges = new CancellableLazy<IList<TextChange>>(CreateTextChanges); _lazyNode = new CancellableLazy<SyntaxNode>(CreateFormattedRoot); } /// <summary> /// rewrite the node with the given trivia information in the map /// </summary> protected abstract SyntaxNode Rewriter(Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> changeMap, CancellationToken cancellationToken); protected SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector> GetFormattingSpans() => _formattingSpans ?? SimpleIntervalTree.Create(new TextSpanIntervalIntrospector(), _formattingResults.Select(r => r.FormattedSpan)); #region IFormattingResult implementation public bool ContainsChanges { get { return this.GetTextChanges(CancellationToken.None).Count > 0; } } public IList<TextChange> GetTextChanges(CancellationToken cancellationToken) => _lazyTextChanges.GetValue(cancellationToken); public SyntaxNode GetFormattedRoot(CancellationToken cancellationToken) => _lazyNode.GetValue(cancellationToken); private IList<TextChange> CreateTextChanges(CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Formatting_AggregateCreateTextChanges, cancellationToken)) { // quick check var changes = CreateTextChangesWorker(cancellationToken); // formatted spans and formatting spans are different, filter returns to formatting span return _formattingSpans == null ? changes : changes.Where(s => _formattingSpans.HasIntervalThatIntersectsWith(s.Span)).ToList(); } } private IList<TextChange> CreateTextChangesWorker(CancellationToken cancellationToken) { if (_formattingResults.Count == 1) { return _formattingResults[0].GetTextChanges(cancellationToken); } // pre-allocate list var count = _formattingResults.Sum(r => r.GetTextChanges(cancellationToken).Count); var result = new List<TextChange>(count); foreach (var formattingResult in _formattingResults) { result.AddRange(formattingResult.GetTextChanges(cancellationToken)); } return result; } private SyntaxNode CreateFormattedRoot(CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Formatting_AggregateCreateFormattedRoot, cancellationToken)) { // create a map var map = new Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData>(); _formattingResults.Do(result => result.GetChanges(cancellationToken).Do(change => map.Add(change.Item1, change.Item2))); return Rewriter(map, cancellationToken); } } #endregion } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Compilers/CSharp/Test/Symbol/Symbols/Metadata/MetadataTypeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MetadataTypeTests : CSharpTestBase { [Fact] public void MetadataNamespaceSymbol01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns = ns2.GetMembers("Serialization").Single() as NamespaceSymbol; Assert.Equal(mscorNS, ns.ContainingAssembly); Assert.Equal(ns2, ns.ContainingSymbol); Assert.Equal(ns2, ns.ContainingNamespace); Assert.True(ns.IsDefinition); // ? Assert.True(ns.IsNamespace); Assert.False(ns.IsType); Assert.Equal(SymbolKind.Namespace, ns.Kind); // bug 1995 Assert.Equal(Accessibility.Public, ns.DeclaredAccessibility); Assert.True(ns.IsStatic); Assert.False(ns.IsAbstract); Assert.False(ns.IsSealed); Assert.False(ns.IsVirtual); Assert.False(ns.IsOverride); // 47 types, 1 namespace (Formatters); Assert.Equal(48, ns.GetMembers().Length); Assert.Equal(47, ns.GetTypeMembers().Length); var fullName = "System.Runtime.Serialization"; Assert.Equal(fullName, ns.ToTestDisplayString()); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolClass01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); var ns1 = mscorNS.GlobalNamespace.GetMembers("Microsoft").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Hosting").Single() as NamespaceSymbol; var class1 = ns3.GetTypeMembers("StrongNameHelpers").First() as NamedTypeSymbol; // internal static class Assert.Equal(0, class1.Arity); Assert.Equal(mscorNS, class1.ContainingAssembly); Assert.Equal(ns3, class1.ContainingSymbol); Assert.Equal(ns3, class1.ContainingNamespace); Assert.True(class1.IsDefinition); Assert.False(class1.IsNamespace); Assert.True(class1.IsType); Assert.True(class1.IsReferenceType); Assert.False(class1.IsValueType); Assert.Equal(SymbolKind.NamedType, class1.Kind); Assert.Equal(TypeKind.Class, class1.TypeKind); Assert.Equal(Accessibility.Internal, class1.DeclaredAccessibility); Assert.True(class1.IsStatic); Assert.False(class1.IsAbstract); Assert.False(class1.IsAbstract); Assert.False(class1.IsExtern); Assert.False(class1.IsSealed); Assert.False(class1.IsVirtual); Assert.False(class1.IsOverride); // 18 members Assert.Equal(18, class1.GetMembers().Length); Assert.Equal(0, class1.GetTypeMembers().Length); Assert.Equal(0, class1.Interfaces().Length); var fullName = "Microsoft.Runtime.Hosting.StrongNameHelpers"; // Internal: Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, class1.ToTestDisplayString()); Assert.Equal(0, class1.TypeArguments().Length); Assert.Equal(0, class1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolGenClass02() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("Dictionary").First() as NamedTypeSymbol; // public generic class Assert.Equal(2, type1.Arity); Assert.Equal(mscorNS, type1.ContainingAssembly); Assert.Equal(ns2, type1.ContainingSymbol); Assert.Equal(ns2, type1.ContainingNamespace); Assert.True(type1.IsDefinition); Assert.False(type1.IsNamespace); Assert.True(type1.IsType); Assert.True(type1.IsReferenceType); Assert.False(type1.IsValueType); Assert.Equal(SymbolKind.NamedType, type1.Kind); Assert.Equal(TypeKind.Class, type1.TypeKind); Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.False(type1.IsStatic); Assert.False(type1.IsAbstract); Assert.False(type1.IsSealed); Assert.False(type1.IsVirtual); Assert.False(type1.IsOverride); // 4 nested types, 67 members overall Assert.Equal(67, type1.GetMembers().Length); Assert.Equal(3, type1.GetTypeMembers().Length); // IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, // IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback Assert.Equal(10, type1.Interfaces().Length); var fullName = "System.Collections.Generic.Dictionary<TKey, TValue>"; // Internal Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, type1.ToTestDisplayString()); Assert.Equal(2, type1.TypeArguments().Length); Assert.Equal(2, type1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolGenInterface01() { var text = "public class A {}"; var compilation = CreateCompilation(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("IList").First() as NamedTypeSymbol; // public generic interface Assert.Equal(1, type1.Arity); Assert.Equal(mscorNS, type1.ContainingAssembly); Assert.Equal(ns2, type1.ContainingSymbol); Assert.Equal(ns2, type1.ContainingNamespace); Assert.True(type1.IsDefinition); Assert.False(type1.IsNamespace); Assert.True(type1.IsType); Assert.True(type1.IsReferenceType); Assert.False(type1.IsValueType); Assert.Equal(SymbolKind.NamedType, type1.Kind); Assert.Equal(TypeKind.Interface, type1.TypeKind); Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.False(type1.IsStatic); Assert.True(type1.IsAbstract); Assert.False(type1.IsSealed); Assert.False(type1.IsVirtual); Assert.False(type1.IsOverride); Assert.False(type1.IsExtern); // 3 method, 2 get|set_<Prop> method, 1 Properties Assert.Equal(6, type1.GetMembers().Length); Assert.Equal(0, type1.GetTypeMembers().Length); // ICollection<T>, IEnumerable<T>, IEnumerable Assert.Equal(3, type1.Interfaces().Length); var fullName = "System.Collections.Generic.IList<T>"; // Internal Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, type1.ToTestDisplayString()); Assert.Equal(1, type1.TypeArguments().Length); Assert.Equal(1, type1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolStruct01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); var ns1 = mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Serialization").Single() as NamespaceSymbol; var type1 = ns3.GetTypeMembers("StreamingContext").First() as NamedTypeSymbol; Assert.Equal(mscorNS, type1.ContainingAssembly); Assert.Equal(ns3, type1.ContainingSymbol); Assert.Equal(ns3, type1.ContainingNamespace); Assert.True(type1.IsDefinition); Assert.False(type1.IsNamespace); Assert.True(type1.IsType); Assert.False(type1.IsReferenceType); Assert.True(type1.IsValueType); Assert.Equal(SymbolKind.NamedType, type1.Kind); Assert.Equal(TypeKind.Struct, type1.TypeKind); Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.False(type1.IsStatic); Assert.False(type1.IsAbstract); Assert.True(type1.IsSealed); Assert.False(type1.IsVirtual); Assert.False(type1.IsOverride); // 4 method + 1 synthesized ctor, 2 get_<Prop> method, 2 Properties, 2 fields Assert.Equal(11, type1.GetMembers().Length); Assert.Equal(0, type1.GetTypeMembers().Length); Assert.Equal(0, type1.Interfaces().Length); var fullName = "System.Runtime.Serialization.StreamingContext"; // Internal Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, type1.ToTestDisplayString()); Assert.Equal(0, type1.TypeArguments().Length); Assert.Equal(0, type1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataArrayTypeSymbol01() { // This is a copy of the EventProviderBase type which existed in a beta of .NET framework // 4.5. Replicating the structure of the type to maintain the test validation. var source1 = @" namespace System.Diagnostics.Eventing { internal class EventProviderBase { internal struct EventData { } internal EventData[] m_eventData = null; protected void WriteTransferEventHelper(int eventId, Guid relatedActivityId, params object[] args) { } } } "; var compilation1 = CreateEmptyCompilation(source1, new[] { TestMetadata.Net40.mscorlib, TestMetadata.Net40.SystemCore }); compilation1.VerifyDiagnostics(); var source2 = "public class A {}"; var compilation2 = CreateEmptyCompilation(source2, new MetadataReference[] { TestMetadata.Net40.mscorlib, TestMetadata.Net40.SystemCore, compilation1.EmitToImageReference() }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var compilation1Lib = compilation2.ExternalReferences[2]; var systemCoreNS = compilation2.GetReferencedAssemblySymbol(compilation1Lib); var ns1 = systemCoreNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Diagnostics").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Eventing").Single() as NamespaceSymbol; var type1 = ns3.GetTypeMembers("EventProviderBase").Single() as NamedTypeSymbol; // EventData[] var type2 = (type1.GetMembers("m_eventData").Single() as FieldSymbol).Type as ArrayTypeSymbol; var member2 = type1.GetMembers("WriteTransferEventHelper").Single() as MethodSymbol; Assert.Equal(3, member2.Parameters.Length); // params object[] var type3 = (member2.Parameters[2] as ParameterSymbol).Type as ArrayTypeSymbol; Assert.Equal(SymbolKind.ArrayType, type2.Kind); Assert.Equal(SymbolKind.ArrayType, type3.Kind); Assert.Equal(Accessibility.NotApplicable, type2.DeclaredAccessibility); Assert.Equal(Accessibility.NotApplicable, type3.DeclaredAccessibility); Assert.True(type2.IsSZArray); Assert.True(type3.IsSZArray); Assert.Equal(TypeKind.Array, type2.TypeKind); Assert.Equal(TypeKind.Array, type3.TypeKind); Assert.Equal("EventData", type2.ElementType.Name); Assert.Equal("Array", type2.BaseType().Name); Assert.Equal("Object", type3.ElementType.Name); Assert.Equal("System.Diagnostics.Eventing.EventProviderBase.EventData[]", type2.ToTestDisplayString()); Assert.Equal("System.Object[]", type3.ToTestDisplayString()); Assert.Equal(1, type2.Interfaces().Length); Assert.Equal(1, type3.Interfaces().Length); // bug // Assert.False(type2.IsDefinition); Assert.False(type2.IsNamespace); Assert.True(type3.IsType); Assert.True(type2.IsReferenceType); Assert.True(type2.ElementType.IsValueType); Assert.True(type3.IsReferenceType); Assert.False(type3.IsValueType); Assert.False(type2.IsStatic); Assert.False(type2.IsAbstract); Assert.False(type2.IsSealed); Assert.False(type3.IsVirtual); Assert.False(type3.IsOverride); Assert.Equal(0, type2.GetMembers().Length); Assert.Equal(0, type3.GetMembers(String.Empty).Length); Assert.Equal(0, type3.GetTypeMembers().Length); Assert.Equal(0, type2.GetTypeMembers(String.Empty).Length); Assert.Equal(0, type3.GetTypeMembers(String.Empty, 0).Length); Assert.Empty(compilation2.GetDeclarationDiagnostics()); } [Fact, WorkItem(531619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531619"), WorkItem(531619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531619")] public void InheritFromNetModuleMetadata01() { var modRef = TestReferences.MetadataTests.NetModule01.ModuleCS00; var text1 = @" class Test : StaticModClass {"; var text2 = @" public static int Main() { r"; var tree = SyntaxFactory.ParseSyntaxTree(String.Empty); var comp = CreateCompilation(source: tree, references: new[] { modRef }); var currComp = comp; var oldTree = comp.SyntaxTrees.First(); var oldIText = oldTree.GetText(); var span = new TextSpan(oldIText.Length, 0); var change = new TextChange(span, text1); var newIText = oldIText.WithChanges(change); var newTree = oldTree.WithChangedText(newIText); currComp = currComp.ReplaceSyntaxTree(oldTree, newTree); var model = currComp.GetSemanticModel(newTree); var id = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(s => s.ToString() == "StaticModClass").First(); // NRE is thrown later but this one has to be called first var symInfo = model.GetSymbolInfo(id); Assert.NotNull(symInfo.Symbol); oldTree = newTree; oldIText = oldTree.GetText(); span = new TextSpan(oldIText.Length, 0); change = new TextChange(span, text2); newIText = oldIText.WithChanges(change); newTree = oldTree.WithChangedText(newIText); currComp = currComp.ReplaceSyntaxTree(oldTree, newTree); model = currComp.GetSemanticModel(newTree); id = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(s => s.ToString() == "StaticModClass").First(); symInfo = model.GetSymbolInfo(id); Assert.NotNull(symInfo.Symbol); } [WorkItem(1066489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066489")] [Fact] public void InstanceIterator_ExplicitInterfaceImplementation_OldName() { var ilSource = @" .class interface public abstract auto ansi I`1<T> { .method public hidebysig newslot abstract virtual instance class [mscorlib]System.Collections.IEnumerable F() cil managed { } // end of method I`1::F } // end of class I`1 .class public auto ansi beforefieldinit C extends [mscorlib]System.Object implements class I`1<int32> { .class auto ansi sealed nested private beforefieldinit '<I<System.Int32>'.'F>d__0' extends [mscorlib]System.Object implements class [mscorlib]System.Collections.Generic.IEnumerable`1<object>, [mscorlib]System.Collections.IEnumerable, class [mscorlib]System.Collections.Generic.IEnumerator`1<object>, [mscorlib]System.Collections.IEnumerator, [mscorlib]System.IDisposable { .field private object '<>2__current' .field private int32 '<>1__state' .field private int32 '<>l__initialThreadId' .field public class C '<>4__this' .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.Generic.IEnumerator`1<object> 'System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator'() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance bool MoveNext() cil managed { ldnull throw } .method private hidebysig newslot specialname virtual final instance object 'System.Collections.Generic.IEnumerator<System.Object>.get_Current'() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance void System.Collections.IEnumerator.Reset() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance void System.IDisposable.Dispose() cil managed { ldnull throw } .method private hidebysig newslot specialname virtual final instance object System.Collections.IEnumerator.get_Current() cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor(int32 '<>1__state') cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance object 'System.Collections.Generic.IEnumerator<System.Object>.Current'() { .get instance object C/'<I<System.Int32>'.'F>d__0'::'System.Collections.Generic.IEnumerator<System.Object>.get_Current'() } .property instance object System.Collections.IEnumerator.Current() { .get instance object C/'<I<System.Int32>'.'F>d__0'::System.Collections.IEnumerator.get_Current() } } // end of class '<I<System.Int32>'.'F>d__0' .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.IEnumerable 'I<System.Int32>.F'() cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class C "; var comp = CreateCompilationWithILAndMscorlib40("", ilSource); var stateMachineClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<NamedTypeSymbol>().Single(); Assert.Equal("<I<System.Int32>.F>d__0", stateMachineClass.Name); // The name has been reconstructed correctly. Assert.Equal("C.<I<System.Int32>.F>d__0", stateMachineClass.ToTestDisplayString()); // SymbolDisplay works. Assert.Equal(stateMachineClass, comp.GetTypeByMetadataName("C+<I<System.Int32>.F>d__0")); // GetTypeByMetadataName works. } [ConditionalFact(typeof(ClrOnly))] [WorkItem(23761, "https://github.com/dotnet/roslyn/issues/23761")] // reason for skipping mono public void EmptyNamespaceNames() { var ilSource = @".class public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } .namespace '.N' { .class public B { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace '.' { .class public C { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace '..' { .class public D { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace '..N' { .class public E { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace N.M { .class public F { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace 'N.M.' { .class public G { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace 'N.M..' { .class public H { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } }"; var comp = CreateCompilationWithILAndMscorlib40("", ilSource); comp.VerifyDiagnostics(); var builder = ArrayBuilder<string>.GetInstance(); var module = comp.GetMember<NamedTypeSymbol>("A").ContainingModule; GetAllNamespaceNames(builder, module.GlobalNamespace); Assert.Equal(new[] { "<global namespace>", "", ".", "..N", ".N", "N", "N.M", "N.M." }, builder); builder.Free(); } private static void GetAllNamespaceNames(ArrayBuilder<string> builder, NamespaceSymbol @namespace) { builder.Add(@namespace.ToTestDisplayString()); foreach (var member in @namespace.GetMembers()) { if (member.Kind != SymbolKind.Namespace) { continue; } GetAllNamespaceNames(builder, (NamespaceSymbol)member); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MetadataTypeTests : CSharpTestBase { [Fact] public void MetadataNamespaceSymbol01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns = ns2.GetMembers("Serialization").Single() as NamespaceSymbol; Assert.Equal(mscorNS, ns.ContainingAssembly); Assert.Equal(ns2, ns.ContainingSymbol); Assert.Equal(ns2, ns.ContainingNamespace); Assert.True(ns.IsDefinition); // ? Assert.True(ns.IsNamespace); Assert.False(ns.IsType); Assert.Equal(SymbolKind.Namespace, ns.Kind); // bug 1995 Assert.Equal(Accessibility.Public, ns.DeclaredAccessibility); Assert.True(ns.IsStatic); Assert.False(ns.IsAbstract); Assert.False(ns.IsSealed); Assert.False(ns.IsVirtual); Assert.False(ns.IsOverride); // 47 types, 1 namespace (Formatters); Assert.Equal(48, ns.GetMembers().Length); Assert.Equal(47, ns.GetTypeMembers().Length); var fullName = "System.Runtime.Serialization"; Assert.Equal(fullName, ns.ToTestDisplayString()); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolClass01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); var ns1 = mscorNS.GlobalNamespace.GetMembers("Microsoft").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Hosting").Single() as NamespaceSymbol; var class1 = ns3.GetTypeMembers("StrongNameHelpers").First() as NamedTypeSymbol; // internal static class Assert.Equal(0, class1.Arity); Assert.Equal(mscorNS, class1.ContainingAssembly); Assert.Equal(ns3, class1.ContainingSymbol); Assert.Equal(ns3, class1.ContainingNamespace); Assert.True(class1.IsDefinition); Assert.False(class1.IsNamespace); Assert.True(class1.IsType); Assert.True(class1.IsReferenceType); Assert.False(class1.IsValueType); Assert.Equal(SymbolKind.NamedType, class1.Kind); Assert.Equal(TypeKind.Class, class1.TypeKind); Assert.Equal(Accessibility.Internal, class1.DeclaredAccessibility); Assert.True(class1.IsStatic); Assert.False(class1.IsAbstract); Assert.False(class1.IsAbstract); Assert.False(class1.IsExtern); Assert.False(class1.IsSealed); Assert.False(class1.IsVirtual); Assert.False(class1.IsOverride); // 18 members Assert.Equal(18, class1.GetMembers().Length); Assert.Equal(0, class1.GetTypeMembers().Length); Assert.Equal(0, class1.Interfaces().Length); var fullName = "Microsoft.Runtime.Hosting.StrongNameHelpers"; // Internal: Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, class1.ToTestDisplayString()); Assert.Equal(0, class1.TypeArguments().Length); Assert.Equal(0, class1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolGenClass02() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("Dictionary").First() as NamedTypeSymbol; // public generic class Assert.Equal(2, type1.Arity); Assert.Equal(mscorNS, type1.ContainingAssembly); Assert.Equal(ns2, type1.ContainingSymbol); Assert.Equal(ns2, type1.ContainingNamespace); Assert.True(type1.IsDefinition); Assert.False(type1.IsNamespace); Assert.True(type1.IsType); Assert.True(type1.IsReferenceType); Assert.False(type1.IsValueType); Assert.Equal(SymbolKind.NamedType, type1.Kind); Assert.Equal(TypeKind.Class, type1.TypeKind); Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.False(type1.IsStatic); Assert.False(type1.IsAbstract); Assert.False(type1.IsSealed); Assert.False(type1.IsVirtual); Assert.False(type1.IsOverride); // 4 nested types, 67 members overall Assert.Equal(67, type1.GetMembers().Length); Assert.Equal(3, type1.GetTypeMembers().Length); // IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, // IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback Assert.Equal(10, type1.Interfaces().Length); var fullName = "System.Collections.Generic.Dictionary<TKey, TValue>"; // Internal Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, type1.ToTestDisplayString()); Assert.Equal(2, type1.TypeArguments().Length); Assert.Equal(2, type1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolGenInterface01() { var text = "public class A {}"; var compilation = CreateCompilation(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("IList").First() as NamedTypeSymbol; // public generic interface Assert.Equal(1, type1.Arity); Assert.Equal(mscorNS, type1.ContainingAssembly); Assert.Equal(ns2, type1.ContainingSymbol); Assert.Equal(ns2, type1.ContainingNamespace); Assert.True(type1.IsDefinition); Assert.False(type1.IsNamespace); Assert.True(type1.IsType); Assert.True(type1.IsReferenceType); Assert.False(type1.IsValueType); Assert.Equal(SymbolKind.NamedType, type1.Kind); Assert.Equal(TypeKind.Interface, type1.TypeKind); Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.False(type1.IsStatic); Assert.True(type1.IsAbstract); Assert.False(type1.IsSealed); Assert.False(type1.IsVirtual); Assert.False(type1.IsOverride); Assert.False(type1.IsExtern); // 3 method, 2 get|set_<Prop> method, 1 Properties Assert.Equal(6, type1.GetMembers().Length); Assert.Equal(0, type1.GetTypeMembers().Length); // ICollection<T>, IEnumerable<T>, IEnumerable Assert.Equal(3, type1.Interfaces().Length); var fullName = "System.Collections.Generic.IList<T>"; // Internal Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, type1.ToTestDisplayString()); Assert.Equal(1, type1.TypeArguments().Length); Assert.Equal(1, type1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataTypeSymbolStruct01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); var ns1 = mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Serialization").Single() as NamespaceSymbol; var type1 = ns3.GetTypeMembers("StreamingContext").First() as NamedTypeSymbol; Assert.Equal(mscorNS, type1.ContainingAssembly); Assert.Equal(ns3, type1.ContainingSymbol); Assert.Equal(ns3, type1.ContainingNamespace); Assert.True(type1.IsDefinition); Assert.False(type1.IsNamespace); Assert.True(type1.IsType); Assert.False(type1.IsReferenceType); Assert.True(type1.IsValueType); Assert.Equal(SymbolKind.NamedType, type1.Kind); Assert.Equal(TypeKind.Struct, type1.TypeKind); Assert.Equal(Accessibility.Public, type1.DeclaredAccessibility); Assert.False(type1.IsStatic); Assert.False(type1.IsAbstract); Assert.True(type1.IsSealed); Assert.False(type1.IsVirtual); Assert.False(type1.IsOverride); // 4 method + 1 synthesized ctor, 2 get_<Prop> method, 2 Properties, 2 fields Assert.Equal(11, type1.GetMembers().Length); Assert.Equal(0, type1.GetTypeMembers().Length); Assert.Equal(0, type1.Interfaces().Length); var fullName = "System.Runtime.Serialization.StreamingContext"; // Internal Assert.Equal(fullName, class1.GetFullNameWithoutGenericArgs()); Assert.Equal(fullName, type1.ToTestDisplayString()); Assert.Equal(0, type1.TypeArguments().Length); Assert.Equal(0, type1.TypeParameters.Length); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataArrayTypeSymbol01() { // This is a copy of the EventProviderBase type which existed in a beta of .NET framework // 4.5. Replicating the structure of the type to maintain the test validation. var source1 = @" namespace System.Diagnostics.Eventing { internal class EventProviderBase { internal struct EventData { } internal EventData[] m_eventData = null; protected void WriteTransferEventHelper(int eventId, Guid relatedActivityId, params object[] args) { } } } "; var compilation1 = CreateEmptyCompilation(source1, new[] { TestMetadata.Net40.mscorlib, TestMetadata.Net40.SystemCore }); compilation1.VerifyDiagnostics(); var source2 = "public class A {}"; var compilation2 = CreateEmptyCompilation(source2, new MetadataReference[] { TestMetadata.Net40.mscorlib, TestMetadata.Net40.SystemCore, compilation1.EmitToImageReference() }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var compilation1Lib = compilation2.ExternalReferences[2]; var systemCoreNS = compilation2.GetReferencedAssemblySymbol(compilation1Lib); var ns1 = systemCoreNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Diagnostics").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Eventing").Single() as NamespaceSymbol; var type1 = ns3.GetTypeMembers("EventProviderBase").Single() as NamedTypeSymbol; // EventData[] var type2 = (type1.GetMembers("m_eventData").Single() as FieldSymbol).Type as ArrayTypeSymbol; var member2 = type1.GetMembers("WriteTransferEventHelper").Single() as MethodSymbol; Assert.Equal(3, member2.Parameters.Length); // params object[] var type3 = (member2.Parameters[2] as ParameterSymbol).Type as ArrayTypeSymbol; Assert.Equal(SymbolKind.ArrayType, type2.Kind); Assert.Equal(SymbolKind.ArrayType, type3.Kind); Assert.Equal(Accessibility.NotApplicable, type2.DeclaredAccessibility); Assert.Equal(Accessibility.NotApplicable, type3.DeclaredAccessibility); Assert.True(type2.IsSZArray); Assert.True(type3.IsSZArray); Assert.Equal(TypeKind.Array, type2.TypeKind); Assert.Equal(TypeKind.Array, type3.TypeKind); Assert.Equal("EventData", type2.ElementType.Name); Assert.Equal("Array", type2.BaseType().Name); Assert.Equal("Object", type3.ElementType.Name); Assert.Equal("System.Diagnostics.Eventing.EventProviderBase.EventData[]", type2.ToTestDisplayString()); Assert.Equal("System.Object[]", type3.ToTestDisplayString()); Assert.Equal(1, type2.Interfaces().Length); Assert.Equal(1, type3.Interfaces().Length); // bug // Assert.False(type2.IsDefinition); Assert.False(type2.IsNamespace); Assert.True(type3.IsType); Assert.True(type2.IsReferenceType); Assert.True(type2.ElementType.IsValueType); Assert.True(type3.IsReferenceType); Assert.False(type3.IsValueType); Assert.False(type2.IsStatic); Assert.False(type2.IsAbstract); Assert.False(type2.IsSealed); Assert.False(type3.IsVirtual); Assert.False(type3.IsOverride); Assert.Equal(0, type2.GetMembers().Length); Assert.Equal(0, type3.GetMembers(String.Empty).Length); Assert.Equal(0, type3.GetTypeMembers().Length); Assert.Equal(0, type2.GetTypeMembers(String.Empty).Length); Assert.Equal(0, type3.GetTypeMembers(String.Empty, 0).Length); Assert.Empty(compilation2.GetDeclarationDiagnostics()); } [Fact, WorkItem(531619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531619"), WorkItem(531619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531619")] public void InheritFromNetModuleMetadata01() { var modRef = TestReferences.MetadataTests.NetModule01.ModuleCS00; var text1 = @" class Test : StaticModClass {"; var text2 = @" public static int Main() { r"; var tree = SyntaxFactory.ParseSyntaxTree(String.Empty); var comp = CreateCompilation(source: tree, references: new[] { modRef }); var currComp = comp; var oldTree = comp.SyntaxTrees.First(); var oldIText = oldTree.GetText(); var span = new TextSpan(oldIText.Length, 0); var change = new TextChange(span, text1); var newIText = oldIText.WithChanges(change); var newTree = oldTree.WithChangedText(newIText); currComp = currComp.ReplaceSyntaxTree(oldTree, newTree); var model = currComp.GetSemanticModel(newTree); var id = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(s => s.ToString() == "StaticModClass").First(); // NRE is thrown later but this one has to be called first var symInfo = model.GetSymbolInfo(id); Assert.NotNull(symInfo.Symbol); oldTree = newTree; oldIText = oldTree.GetText(); span = new TextSpan(oldIText.Length, 0); change = new TextChange(span, text2); newIText = oldIText.WithChanges(change); newTree = oldTree.WithChangedText(newIText); currComp = currComp.ReplaceSyntaxTree(oldTree, newTree); model = currComp.GetSemanticModel(newTree); id = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(s => s.ToString() == "StaticModClass").First(); symInfo = model.GetSymbolInfo(id); Assert.NotNull(symInfo.Symbol); } [WorkItem(1066489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066489")] [Fact] public void InstanceIterator_ExplicitInterfaceImplementation_OldName() { var ilSource = @" .class interface public abstract auto ansi I`1<T> { .method public hidebysig newslot abstract virtual instance class [mscorlib]System.Collections.IEnumerable F() cil managed { } // end of method I`1::F } // end of class I`1 .class public auto ansi beforefieldinit C extends [mscorlib]System.Object implements class I`1<int32> { .class auto ansi sealed nested private beforefieldinit '<I<System.Int32>'.'F>d__0' extends [mscorlib]System.Object implements class [mscorlib]System.Collections.Generic.IEnumerable`1<object>, [mscorlib]System.Collections.IEnumerable, class [mscorlib]System.Collections.Generic.IEnumerator`1<object>, [mscorlib]System.Collections.IEnumerator, [mscorlib]System.IDisposable { .field private object '<>2__current' .field private int32 '<>1__state' .field private int32 '<>l__initialThreadId' .field public class C '<>4__this' .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.Generic.IEnumerator`1<object> 'System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator'() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance bool MoveNext() cil managed { ldnull throw } .method private hidebysig newslot specialname virtual final instance object 'System.Collections.Generic.IEnumerator<System.Object>.get_Current'() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance void System.Collections.IEnumerator.Reset() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance void System.IDisposable.Dispose() cil managed { ldnull throw } .method private hidebysig newslot specialname virtual final instance object System.Collections.IEnumerator.get_Current() cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor(int32 '<>1__state') cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance object 'System.Collections.Generic.IEnumerator<System.Object>.Current'() { .get instance object C/'<I<System.Int32>'.'F>d__0'::'System.Collections.Generic.IEnumerator<System.Object>.get_Current'() } .property instance object System.Collections.IEnumerator.Current() { .get instance object C/'<I<System.Int32>'.'F>d__0'::System.Collections.IEnumerator.get_Current() } } // end of class '<I<System.Int32>'.'F>d__0' .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.IEnumerable 'I<System.Int32>.F'() cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class C "; var comp = CreateCompilationWithILAndMscorlib40("", ilSource); var stateMachineClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<NamedTypeSymbol>().Single(); Assert.Equal("<I<System.Int32>.F>d__0", stateMachineClass.Name); // The name has been reconstructed correctly. Assert.Equal("C.<I<System.Int32>.F>d__0", stateMachineClass.ToTestDisplayString()); // SymbolDisplay works. Assert.Equal(stateMachineClass, comp.GetTypeByMetadataName("C+<I<System.Int32>.F>d__0")); // GetTypeByMetadataName works. } [ConditionalFact(typeof(ClrOnly))] [WorkItem(23761, "https://github.com/dotnet/roslyn/issues/23761")] // reason for skipping mono public void EmptyNamespaceNames() { var ilSource = @".class public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } .namespace '.N' { .class public B { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace '.' { .class public C { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace '..' { .class public D { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace '..N' { .class public E { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace N.M { .class public F { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace 'N.M.' { .class public G { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } } .namespace 'N.M..' { .class public H { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } } }"; var comp = CreateCompilationWithILAndMscorlib40("", ilSource); comp.VerifyDiagnostics(); var builder = ArrayBuilder<string>.GetInstance(); var module = comp.GetMember<NamedTypeSymbol>("A").ContainingModule; GetAllNamespaceNames(builder, module.GlobalNamespace); Assert.Equal(new[] { "<global namespace>", "", ".", "..N", ".N", "N", "N.M", "N.M." }, builder); builder.Free(); } private static void GetAllNamespaceNames(ArrayBuilder<string> builder, NamespaceSymbol @namespace) { builder.Add(@namespace.ToTestDisplayString()); foreach (var member in @namespace.GetMembers()) { if (member.Kind != SymbolKind.Namespace) { continue; } GetAllNamespaceNames(builder, (NamespaceSymbol)member); } } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService.WrappedPropertySymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.DocumentationComments; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { private class WrappedPropertySymbol : AbstractWrappedSymbol, IPropertySymbol { private readonly IPropertySymbol _symbol; public WrappedPropertySymbol(IPropertySymbol propertySymbol, bool canImplementImplicitly, IDocumentationCommentFormattingService docCommentFormattingService) : base(propertySymbol, canImplementImplicitly, docCommentFormattingService) { _symbol = propertySymbol; } public ImmutableArray<IPropertySymbol> ExplicitInterfaceImplementations { get { return CanImplementImplicitly ? ImmutableArray.Create<IPropertySymbol>() : _symbol.ExplicitInterfaceImplementations; } } public IMethodSymbol GetMethod => _symbol.GetMethod; public bool IsIndexer => _symbol.IsIndexer; public bool IsReadOnly => _symbol.IsReadOnly; public bool IsWithEvents => _symbol.IsWithEvents; public bool IsWriteOnly => _symbol.IsWriteOnly; public bool ReturnsByRef => _symbol.ReturnsByRef; public bool ReturnsByRefReadonly => _symbol.ReturnsByRefReadonly; public RefKind RefKind => _symbol.RefKind; public IPropertySymbol OverriddenProperty => _symbol.OverriddenProperty; public ImmutableArray<IParameterSymbol> Parameters => _symbol.Parameters; public IMethodSymbol SetMethod => _symbol.SetMethod; public ITypeSymbol Type => _symbol.Type; public NullableAnnotation NullableAnnotation => _symbol.NullableAnnotation; public ImmutableArray<CustomModifier> RefCustomModifiers => _symbol.RefCustomModifiers; public ImmutableArray<CustomModifier> TypeCustomModifiers => _symbol.TypeCustomModifiers; ISymbol ISymbol.OriginalDefinition => _symbol.OriginalDefinition; public new IPropertySymbol OriginalDefinition { get { return this; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.DocumentationComments; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { private class WrappedPropertySymbol : AbstractWrappedSymbol, IPropertySymbol { private readonly IPropertySymbol _symbol; public WrappedPropertySymbol(IPropertySymbol propertySymbol, bool canImplementImplicitly, IDocumentationCommentFormattingService docCommentFormattingService) : base(propertySymbol, canImplementImplicitly, docCommentFormattingService) { _symbol = propertySymbol; } public ImmutableArray<IPropertySymbol> ExplicitInterfaceImplementations { get { return CanImplementImplicitly ? ImmutableArray.Create<IPropertySymbol>() : _symbol.ExplicitInterfaceImplementations; } } public IMethodSymbol GetMethod => _symbol.GetMethod; public bool IsIndexer => _symbol.IsIndexer; public bool IsReadOnly => _symbol.IsReadOnly; public bool IsWithEvents => _symbol.IsWithEvents; public bool IsWriteOnly => _symbol.IsWriteOnly; public bool ReturnsByRef => _symbol.ReturnsByRef; public bool ReturnsByRefReadonly => _symbol.ReturnsByRefReadonly; public RefKind RefKind => _symbol.RefKind; public IPropertySymbol OverriddenProperty => _symbol.OverriddenProperty; public ImmutableArray<IParameterSymbol> Parameters => _symbol.Parameters; public IMethodSymbol SetMethod => _symbol.SetMethod; public ITypeSymbol Type => _symbol.Type; public NullableAnnotation NullableAnnotation => _symbol.NullableAnnotation; public ImmutableArray<CustomModifier> RefCustomModifiers => _symbol.RefCustomModifiers; public ImmutableArray<CustomModifier> TypeCustomModifiers => _symbol.TypeCustomModifiers; ISymbol ISymbol.OriginalDefinition => _symbol.OriginalDefinition; public new IPropertySymbol OriginalDefinition { get { return this; } } } } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AnalyzerProperty.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public enum AnalyzerProperty { Title, Description, HelpLink, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public enum AnalyzerProperty { Title, Description, HelpLink, } }
-1
dotnet/roslyn
55,530
Ignore modules with bad metadata in function resolver
Fixes https://github.com/dotnet/roslyn/issues/55475
tmat
2021-08-10T18:56:37Z
2021-08-11T18:37:09Z
cd0c0464c069a2b80774d70f071c29333d9fa23c
bc874ebc5111a2a33221409f895953b1536f6612
Ignore modules with bad metadata in function resolver. Fixes https://github.com/dotnet/roslyn/issues/55475
./src/EditorFeatures/TestUtilities/TestObscuringTipManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.UnitTests { // In 15.6 the editor (QuickInfo in particular) took a dependency on // IObscuringTipManager, which is only exported in VS editor layer. // This is tracked by the editor bug https://devdiv.visualstudio.com/DevDiv/_workitems?id=544569. // Meantime a workaround is to export dummy IObscuringTipManager. // Do not delete: this one is still used in Editor and implicitly required for EventHookupCommandHandlerTests in Roslyn. [Export(typeof(IObscuringTipManager))] internal class TestObscuringTipManager : IObscuringTipManager { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestObscuringTipManager() { } public void PushTip(ITextView view, IObscuringTip tip) { } public void RemoveTip(ITextView view, IObscuringTip tip) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.UnitTests { // In 15.6 the editor (QuickInfo in particular) took a dependency on // IObscuringTipManager, which is only exported in VS editor layer. // This is tracked by the editor bug https://devdiv.visualstudio.com/DevDiv/_workitems?id=544569. // Meantime a workaround is to export dummy IObscuringTipManager. // Do not delete: this one is still used in Editor and implicitly required for EventHookupCommandHandlerTests in Roslyn. [Export(typeof(IObscuringTipManager))] internal class TestObscuringTipManager : IObscuringTipManager { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestObscuringTipManager() { } public void PushTip(ITextView view, IObscuringTip tip) { } public void RemoveTip(ITextView view, IObscuringTip tip) { } } }
-1