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><Extension> |</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><Extension> |</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
' // &
' // '
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
' // <
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
' // >
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
' // "
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
' // &
' // '
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
' // <
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
' // >
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
' // "
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 < 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 < 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 < 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 < 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.
$ PE L jM ! >/ @ @ @ . K @ ` H .text D `.rsrc @ @ @.reloc ` @ B / H d
*
*
*(
* BSJB v4.0.30319 l | #~ #Strings #US #GUID #Blob W %3 0
qR R R
* F a R R R R R R !R 1R FR a fR zR ! ) 1 ) ? )
G ) ] ) s ) ) )
1 ր9 V> VB VF
$& |